diff --git a/.oxfmtrc.json b/.oxfmtrc.json index 8720ee1c64..3e731cbaff 100644 --- a/.oxfmtrc.json +++ b/.oxfmtrc.json @@ -9,6 +9,8 @@ "bun.lock", "*.tsbuildinfo", "**/routeTree.gen.ts", + "apps/mobile/android/**", + "apps/mobile/ios/**", "apps/web/public/mockServiceWorker.js", "apps/web/src/lib/vendor/qrcodegen.ts", "apps/mobile/uniwind-types.d.ts", diff --git a/.oxlintrc.json b/.oxlintrc.json index 12fc3f8da4..fe9d133e09 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -7,6 +7,8 @@ "bun.lock", "*.tsbuildinfo", "**/routeTree.gen.ts", + "apps/mobile/android/**", + "apps/mobile/ios/**", "apps/mobile/uniwind-types.d.ts" ], "plugins": ["eslint", "oxc", "react", "unicorn", "typescript"], diff --git a/apps/mobile/src/features/review/ReviewHighlighterProvider.tsx b/apps/mobile/src/features/review/ReviewHighlighterProvider.tsx index 0952019291..150584aede 100644 --- a/apps/mobile/src/features/review/ReviewHighlighterProvider.tsx +++ b/apps/mobile/src/features/review/ReviewHighlighterProvider.tsx @@ -1,101 +1,15 @@ -import { createContext, type ReactNode, useContext, useEffect, useMemo, useState } from "react"; +import { createContext, type ReactNode, useContext, useMemo } from "react"; -import { - getActiveReviewHighlighterEngine, - prepareReviewHighlighter, - prepareReviewHighlighterLanguages, - type ReviewHighlighterEngine, -} from "./shikiReviewHighlighter"; +import { type ReviewHighlighterState, useReviewHighlighterState } from "./reviewHighlighterState"; -type ReviewHighlighterStatus = "idle" | "initializing" | "ready" | "error"; - -interface ReviewHighlighterContextValue { - readonly engine: ReviewHighlighterEngine | null; - readonly error: string | null; - readonly status: ReviewHighlighterStatus; -} - -const ReviewHighlighterContext = createContext({ +const ReviewHighlighterContext = createContext({ engine: null, error: null, status: "idle", }); -const REVIEW_INITIAL_LANGUAGES = [ - "typescript", - "tsx", - "javascript", - "jsx", - "json", - "yaml", - "bash", -] as const; - -function isReviewHighlighterProviderDebugLoggingEnabled(): boolean { - return typeof __DEV__ !== "undefined" ? __DEV__ : false; -} - -function logReviewHighlighterProviderDiagnostic( - message: string, - details?: Record, -): void { - if (!isReviewHighlighterProviderDebugLoggingEnabled()) { - return; - } - - if (details) { - console.log(`[review-highlighter-provider] ${message}`, details); - return; - } - - console.log(`[review-highlighter-provider] ${message}`); -} - export function ReviewHighlighterProvider(props: { readonly children: ReactNode }) { - const [value, setValue] = useState({ - engine: null, - error: null, - status: "idle", - }); - - useEffect(() => { - let cancelled = false; - - setValue({ engine: null, error: null, status: "initializing" }); - - void (async () => { - const startedAt = performance.now(); - try { - await prepareReviewHighlighter(); - await prepareReviewHighlighterLanguages(REVIEW_INITIAL_LANGUAGES); - const engine = await getActiveReviewHighlighterEngine(); - - if (cancelled) { - return; - } - - const durationMs = Math.round(performance.now() - startedAt); - logReviewHighlighterProviderDiagnostic("initialized", { - durationMs, - engine, - }); - setValue({ engine, error: null, status: "ready" }); - } catch (error) { - if (cancelled) { - return; - } - - const message = error instanceof Error ? error.message : String(error); - logReviewHighlighterProviderDiagnostic("initialization failed", { error: message }); - setValue({ engine: null, error: message, status: "error" }); - } - })(); - - return () => { - cancelled = true; - }; - }, []); - + const value = useReviewHighlighterState(); const contextValue = useMemo(() => value, [value]); return ( @@ -105,6 +19,6 @@ export function ReviewHighlighterProvider(props: { readonly children: ReactNode ); } -export function useReviewHighlighterStatus(): ReviewHighlighterContextValue { +export function useReviewHighlighterStatus(): ReviewHighlighterState { return useContext(ReviewHighlighterContext); } diff --git a/apps/mobile/src/features/review/reviewHighlighterState.test.ts b/apps/mobile/src/features/review/reviewHighlighterState.test.ts new file mode 100644 index 0000000000..90c71350fd --- /dev/null +++ b/apps/mobile/src/features/review/reviewHighlighterState.test.ts @@ -0,0 +1,75 @@ +import { assert, beforeEach, it } from "vitest"; +import { AtomRegistry } from "effect/unstable/reactivity"; + +import { + createReviewHighlighterManager, + IDLE_REVIEW_HIGHLIGHTER_STATE, +} from "./reviewHighlighterState"; + +let registry = AtomRegistry.make(); + +beforeEach(() => { + registry.dispose(); + registry = AtomRegistry.make(); +}); + +function flushAsyncWork(): Promise { + return Promise.resolve().then(() => undefined); +} + +it("initializes review highlighter state once", async () => { + let prepareCalls = 0; + let languageCalls = 0; + let engineCalls = 0; + const manager = createReviewHighlighterManager({ + getRegistry: () => registry, + loader: { + prepare: async () => { + prepareCalls += 1; + }, + prepareLanguages: async () => { + languageCalls += 1; + }, + getEngine: async () => { + engineCalls += 1; + return "javascript"; + }, + }, + }); + + assert.deepStrictEqual(manager.getSnapshot(), IDLE_REVIEW_HIGHLIGHTER_STATE); + + await Promise.all([manager.initialize(), manager.initialize()]); + await manager.initialize(); + + assert.strictEqual(prepareCalls, 1); + assert.strictEqual(languageCalls, 1); + assert.strictEqual(engineCalls, 1); + assert.deepStrictEqual(manager.getSnapshot(), { + engine: "javascript", + error: null, + status: "ready", + }); +}); + +it("stores initialization failures in atom state", async () => { + const manager = createReviewHighlighterManager({ + getRegistry: () => registry, + loader: { + prepare: async () => { + throw new Error("load failed"); + }, + prepareLanguages: async () => undefined, + getEngine: async () => "javascript", + }, + }); + + void manager.initialize(); + await flushAsyncWork(); + + assert.deepStrictEqual(manager.getSnapshot(), { + engine: null, + error: "load failed", + status: "error", + }); +}); diff --git a/apps/mobile/src/features/review/reviewHighlighterState.ts b/apps/mobile/src/features/review/reviewHighlighterState.ts new file mode 100644 index 0000000000..2622ecbe05 --- /dev/null +++ b/apps/mobile/src/features/review/reviewHighlighterState.ts @@ -0,0 +1,154 @@ +import { useAtomValue } from "@effect/atom-react"; +import { Atom, type AtomRegistry } from "effect/unstable/reactivity"; +import { useEffect } from "react"; + +import { appAtomRegistry } from "../../state/atom-registry"; +import { + getActiveReviewHighlighterEngine, + prepareReviewHighlighter, + prepareReviewHighlighterLanguages, + type ReviewHighlighterEngine, +} from "./shikiReviewHighlighter"; + +export type ReviewHighlighterStatus = "idle" | "initializing" | "ready" | "error"; + +export interface ReviewHighlighterState { + readonly engine: ReviewHighlighterEngine | null; + readonly error: string | null; + readonly status: ReviewHighlighterStatus; +} + +export interface ReviewHighlighterLoader { + readonly prepare: () => Promise; + readonly prepareLanguages: (languages: ReadonlyArray) => Promise; + readonly getEngine: () => Promise; +} + +const REVIEW_INITIAL_LANGUAGES = [ + "typescript", + "tsx", + "javascript", + "jsx", + "json", + "yaml", + "bash", +] as const; + +export const IDLE_REVIEW_HIGHLIGHTER_STATE = Object.freeze({ + engine: null, + error: null, + status: "idle", +}); + +const INITIALIZING_REVIEW_HIGHLIGHTER_STATE = Object.freeze({ + engine: null, + error: null, + status: "initializing", +}); + +export const reviewHighlighterStateAtom = Atom.make(IDLE_REVIEW_HIGHLIGHTER_STATE).pipe( + Atom.keepAlive, + Atom.withLabel("mobile:review-highlighter"), +); + +function isReviewHighlighterProviderDebugLoggingEnabled(): boolean { + return typeof __DEV__ !== "undefined" ? __DEV__ : false; +} + +function logReviewHighlighterProviderDiagnostic( + message: string, + details?: Record, +): void { + if (!isReviewHighlighterProviderDebugLoggingEnabled()) { + return; + } + + if (details) { + console.log(`[review-highlighter-provider] ${message}`, details); + return; + } + + console.log(`[review-highlighter-provider] ${message}`); +} + +export function createReviewHighlighterManager(config: { + readonly getRegistry: () => AtomRegistry.AtomRegistry; + readonly loader: ReviewHighlighterLoader; + readonly languages?: ReadonlyArray; +}) { + let started = false; + let inFlight: Promise | null = null; + + function getSnapshot(): ReviewHighlighterState { + return config.getRegistry().get(reviewHighlighterStateAtom); + } + + function setState(state: ReviewHighlighterState): void { + config.getRegistry().set(reviewHighlighterStateAtom, state); + } + + function initialize(): Promise { + if (inFlight) { + return inFlight; + } + + if (started && getSnapshot().status === "ready") { + return Promise.resolve(); + } + + started = true; + setState(INITIALIZING_REVIEW_HIGHLIGHTER_STATE); + + inFlight = (async () => { + const startedAt = performance.now(); + try { + await config.loader.prepare(); + await config.loader.prepareLanguages(config.languages ?? REVIEW_INITIAL_LANGUAGES); + const engine = await config.loader.getEngine(); + const durationMs = Math.round(performance.now() - startedAt); + logReviewHighlighterProviderDiagnostic("initialized", { + durationMs, + engine, + }); + setState({ engine, error: null, status: "ready" }); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + logReviewHighlighterProviderDiagnostic("initialization failed", { error: message }); + setState({ engine: null, error: message, status: "error" }); + } finally { + inFlight = null; + } + })(); + + return inFlight; + } + + function reset(): void { + started = false; + inFlight = null; + setState(IDLE_REVIEW_HIGHLIGHTER_STATE); + } + + return { + getSnapshot, + initialize, + reset, + }; +} + +const reviewHighlighterManager = createReviewHighlighterManager({ + getRegistry: () => appAtomRegistry, + loader: { + prepare: prepareReviewHighlighter, + prepareLanguages: prepareReviewHighlighterLanguages, + getEngine: getActiveReviewHighlighterEngine, + }, +}); + +export function useReviewHighlighterState(): ReviewHighlighterState { + useEffect(() => { + void reviewHighlighterManager.initialize(); + }, []); + + return useAtomValue(reviewHighlighterStateAtom); +} diff --git a/apps/mobile/src/features/review/reviewModel.ts b/apps/mobile/src/features/review/reviewModel.ts index f599d00e1b..26aee94d13 100644 --- a/apps/mobile/src/features/review/reviewModel.ts +++ b/apps/mobile/src/features/review/reviewModel.ts @@ -1,4 +1,5 @@ -import { parsePatchFiles, type ChangeTypes, type FileDiffMetadata } from "@pierre/diffs/utils"; +import type { ChangeTypes, FileDiffMetadata } from "@pierre/diffs/types"; +import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles"; import type { OrchestrationCheckpointSummary, ReviewDiffPreviewSource } from "@t3tools/contracts"; import * as Arr from "effect/Array"; import * as Order from "effect/Order"; diff --git a/apps/mobile/src/features/review/reviewState.test.ts b/apps/mobile/src/features/review/reviewState.test.ts new file mode 100644 index 0000000000..74d16b606b --- /dev/null +++ b/apps/mobile/src/features/review/reviewState.test.ts @@ -0,0 +1,32 @@ +import { assert, it } from "vitest"; + +import { + getReviewAsyncStateSnapshot, + setReviewAsyncError, + setReviewGitDiffsLoading, + setReviewTurnDiffLoading, +} from "./reviewState"; + +it("stores review async loading and error state in atoms", () => { + const threadKey = `env-local:thread-review-state-${Date.now()}`; + + setReviewGitDiffsLoading(threadKey, true); + setReviewTurnDiffLoading(threadKey, "turn-1", true); + setReviewAsyncError(threadKey, "load failed"); + + assert.deepStrictEqual(getReviewAsyncStateSnapshot(threadKey), { + loadingGitDiffs: true, + loadingTurnIds: { "turn-1": true }, + error: "load failed", + }); + + setReviewGitDiffsLoading(threadKey, false); + setReviewTurnDiffLoading(threadKey, "turn-1", false); + setReviewAsyncError(threadKey, null); + + assert.deepStrictEqual(getReviewAsyncStateSnapshot(threadKey), { + loadingGitDiffs: false, + loadingTurnIds: {}, + error: null, + }); +}); diff --git a/apps/mobile/src/features/review/reviewState.ts b/apps/mobile/src/features/review/reviewState.ts index 7d30813813..00e60957db 100644 --- a/apps/mobile/src/features/review/reviewState.ts +++ b/apps/mobile/src/features/review/reviewState.ts @@ -9,6 +9,12 @@ import { buildReviewParsedDiff, type ReviewParsedDiff } from "./reviewModel"; const EMPTY_GIT_REVIEW_SECTIONS = Object.freeze>([]); const EMPTY_REVIEW_TURN_DIFFS = Object.freeze>>({}); +const EMPTY_REVIEW_LOADING_TURN_IDS = Object.freeze>>({}); +const EMPTY_REVIEW_ASYNC_STATE = Object.freeze({ + loadingGitDiffs: false, + loadingTurnIds: EMPTY_REVIEW_LOADING_TURN_IDS, + error: null, +}); const EMPTY_REVIEW_SECTION_FILE_IDS = Object.freeze< Readonly | undefined>> >({}); @@ -24,6 +30,10 @@ const EMPTY_REVIEW_SELECTED_SECTION_ID_ATOM = Atom.make(null).pip Atom.keepAlive, Atom.withLabel("mobile:review:selected-section-id:null"), ); +const EMPTY_REVIEW_ASYNC_STATE_ATOM = Atom.make(EMPTY_REVIEW_ASYNC_STATE).pipe( + Atom.keepAlive, + Atom.withLabel("mobile:review:async-state:null"), +); const EMPTY_REVIEW_SECTION_FILE_IDS_ATOM = Atom.make(EMPTY_REVIEW_SECTION_FILE_IDS).pipe( Atom.keepAlive, Atom.withLabel("mobile:review:section-file-ids:null"), @@ -50,6 +60,13 @@ const reviewSelectedSectionIdByThreadKeyAtom = Atom.family((threadKey: string) = ), ); +const reviewAsyncStateByThreadKeyAtom = Atom.family((threadKey: string) => + Atom.make(EMPTY_REVIEW_ASYNC_STATE).pipe( + Atom.keepAlive, + Atom.withLabel(`mobile:review:async-state:${threadKey}`), + ), +); + const reviewExpandedFileIdsByThreadKeyAtom = Atom.family((threadKey: string) => Atom.make(EMPTY_REVIEW_SECTION_FILE_IDS).pipe( Atom.keepAlive, @@ -83,6 +100,7 @@ export interface ReviewCacheForThread { readonly gitSections: ReadonlyArray; readonly turnDiffById: Readonly>; readonly selectedSectionId: string | null; + readonly asyncState: ReviewAsyncState; readonly expandedFileIdsBySection: Readonly | undefined>>; readonly revealedLargeFileIdsBySection: Readonly< Record | undefined> @@ -90,6 +108,12 @@ export interface ReviewCacheForThread { readonly viewedFileIdsBySection: Readonly | undefined>>; } +export interface ReviewAsyncState { + readonly loadingGitDiffs: boolean; + readonly loadingTurnIds: Readonly>; + readonly error: string | null; +} + function buildThreadKey(input: { readonly environmentId?: EnvironmentId; readonly threadId?: ThreadId; @@ -119,6 +143,9 @@ export function useReviewCacheForThread(input: { ? reviewSelectedSectionIdByThreadKeyAtom(threadKey) : EMPTY_REVIEW_SELECTED_SECTION_ID_ATOM, ); + const asyncState = useAtomValue( + threadKey ? reviewAsyncStateByThreadKeyAtom(threadKey) : EMPTY_REVIEW_ASYNC_STATE_ATOM, + ); const expandedFileIdsBySection = useAtomValue( threadKey ? reviewExpandedFileIdsByThreadKeyAtom(threadKey) @@ -138,6 +165,7 @@ export function useReviewCacheForThread(input: { gitSections, turnDiffById, selectedSectionId, + asyncState, expandedFileIdsBySection, revealedLargeFileIdsBySection, viewedFileIdsBySection, @@ -164,6 +192,51 @@ export function setReviewSelectedSectionId(threadKey: string, sectionId: string appAtomRegistry.set(reviewSelectedSectionIdByThreadKeyAtom(threadKey), sectionId); } +function updateReviewAsyncState( + threadKey: string, + update: (current: ReviewAsyncState) => ReviewAsyncState, +): void { + const atom = reviewAsyncStateByThreadKeyAtom(threadKey); + appAtomRegistry.set(atom, update(appAtomRegistry.get(atom))); +} + +export function setReviewGitDiffsLoading(threadKey: string, loadingGitDiffs: boolean): void { + updateReviewAsyncState(threadKey, (current) => ({ + ...current, + loadingGitDiffs, + })); +} + +export function setReviewTurnDiffLoading( + threadKey: string, + sectionId: string, + isLoading: boolean, +): void { + updateReviewAsyncState(threadKey, (current) => { + const loadingTurnIds = { ...current.loadingTurnIds }; + if (isLoading) { + loadingTurnIds[sectionId] = true; + } else { + delete loadingTurnIds[sectionId]; + } + return { + ...current, + loadingTurnIds, + }; + }); +} + +export function setReviewAsyncError(threadKey: string, error: string | null): void { + updateReviewAsyncState(threadKey, (current) => ({ + ...current, + error, + })); +} + +export function getReviewAsyncStateSnapshot(threadKey: string): ReviewAsyncState { + return appAtomRegistry.get(reviewAsyncStateByThreadKeyAtom(threadKey)); +} + export function updateReviewExpandedFileIds( threadKey: string, sectionId: string, diff --git a/apps/mobile/src/features/review/shikiReviewHighlighter.ts b/apps/mobile/src/features/review/shikiReviewHighlighter.ts index eb6bf6973c..17e7ff4967 100644 --- a/apps/mobile/src/features/review/shikiReviewHighlighter.ts +++ b/apps/mobile/src/features/review/shikiReviewHighlighter.ts @@ -9,7 +9,7 @@ import typescriptLanguage from "@shikijs/langs/typescript"; import yamlLanguage from "@shikijs/langs/yaml"; import githubDarkDefault from "@shikijs/themes/github-dark-default"; import githubLightDefault from "@shikijs/themes/github-light-default"; -import { getFiletypeFromFileName } from "@pierre/diffs/utils"; +import { getFiletypeFromFileName } from "@pierre/diffs/utils/getFiletypeFromFileName"; import { resolveReviewHighlighterEngine, diff --git a/apps/mobile/src/features/review/useReviewSections.ts b/apps/mobile/src/features/review/useReviewSections.ts index 248a6cb139..19bc7adf7e 100644 --- a/apps/mobile/src/features/review/useReviewSections.ts +++ b/apps/mobile/src/features/review/useReviewSections.ts @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { useCallback, useEffect, useMemo, useRef } from "react"; import type { EnvironmentId, OrchestrationCheckpointSummary, ThreadId } from "@t3tools/contracts"; @@ -12,8 +12,11 @@ import { getReviewSectionIdForCheckpoint, } from "./reviewModel"; import { + setReviewAsyncError, + setReviewGitDiffsLoading, setReviewGitSections, setReviewSelectedSectionId, + setReviewTurnDiffLoading, setReviewTurnDiff, type ReviewCacheForThread, } from "./reviewState"; @@ -26,9 +29,7 @@ export function useReviewSections(input: { const { environmentId, reviewCache, threadId } = input; const selectedThread = useSelectedThreadDetail(); const { selectedThreadCwd } = useSelectedThreadWorktree(); - const [loadingTurnIds, setLoadingTurnIds] = useState>({}); - const [loadingGitDiffs, setLoadingGitDiffs] = useState(false); - const [error, setError] = useState(null); + const { error, loadingGitDiffs, loadingTurnIds } = reviewCache.asyncState; const turnDiffByIdRef = useRef(reviewCache.turnDiffById); useEffect(() => { @@ -84,21 +85,32 @@ export function useReviewSections(input: { const client = getEnvironmentClient(environmentId); if (!client) { - setError("Remote connection is not ready."); + if (reviewCache.threadKey) { + setReviewAsyncError(reviewCache.threadKey, "Remote connection is not ready."); + } return; } - setLoadingGitDiffs(true); - setError(null); + if (reviewCache.threadKey) { + setReviewGitDiffsLoading(reviewCache.threadKey, true); + setReviewAsyncError(reviewCache.threadKey, null); + } try { const result = await client.review.getDiffPreview({ cwd: selectedThreadCwd }); if (reviewCache.threadKey) { setReviewGitSections(reviewCache.threadKey, result.sources); } } catch (cause) { - setError(cause instanceof Error ? cause.message : "Failed to load review diffs."); + if (reviewCache.threadKey) { + setReviewAsyncError( + reviewCache.threadKey, + cause instanceof Error ? cause.message : "Failed to load review diffs.", + ); + } } finally { - setLoadingGitDiffs(false); + if (reviewCache.threadKey) { + setReviewGitDiffsLoading(reviewCache.threadKey, false); + } } }, [environmentId, reviewCache.threadKey, selectedThreadCwd]); @@ -119,12 +131,16 @@ export function useReviewSections(input: { const client = getEnvironmentClient(environmentId); if (!client) { - setError("Remote connection is not ready."); + if (reviewCache.threadKey) { + setReviewAsyncError(reviewCache.threadKey, "Remote connection is not ready."); + } return; } - setLoadingTurnIds((current) => ({ ...current, [sectionId]: true })); - setError(null); + if (reviewCache.threadKey) { + setReviewTurnDiffLoading(reviewCache.threadKey, sectionId, true); + setReviewAsyncError(reviewCache.threadKey, null); + } try { const result = await client.orchestration.getTurnDiff({ threadId, @@ -135,13 +151,16 @@ export function useReviewSections(input: { setReviewTurnDiff(reviewCache.threadKey, sectionId, result.diff); } } catch (cause) { - setError(cause instanceof Error ? cause.message : "Failed to load turn diff."); + if (reviewCache.threadKey) { + setReviewAsyncError( + reviewCache.threadKey, + cause instanceof Error ? cause.message : "Failed to load turn diff.", + ); + } } finally { - setLoadingTurnIds((current) => { - const next = { ...current }; - delete next[sectionId]; - return next; - }); + if (reviewCache.threadKey) { + setReviewTurnDiffLoading(reviewCache.threadKey, sectionId, false); + } } }, [environmentId, reviewCache.threadKey, threadId], diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx index b16ba0248d..503601646b 100644 --- a/apps/mobile/src/features/threads/ThreadComposer.tsx +++ b/apps/mobile/src/features/threads/ThreadComposer.tsx @@ -42,7 +42,7 @@ import { normalizeSearchQuery, scoreQueryMatch, } from "@t3tools/shared/searchRanking"; -import { getEnvironmentClient } from "../../state/environment-session-registry"; +import { useComposerPathSearch } from "../../state/use-composer-path-search"; import { CLAUDE_AGENT_EFFORT_OPTIONS, type ClaudeAgentEffort } from "./claudeEffortOptions"; import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover"; @@ -209,12 +209,6 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer // ── Trigger detection ──────────────────────────────────── const [cursorPosition, setCursorPosition] = useState(0); - const [composerTrigger, setComposerTrigger] = useState(null); - const [pathSearchResults, setPathSearchResults] = useState< - ReadonlyArray<{ path: string; kind: "file" | "directory" }> - >([]); - const [pathSearchLoading, setPathSearchLoading] = useState(false); - const pathSearchTimerRef = useRef | null>(null); const handleSelectionChange = useCallback( (event: NativeSyntheticEvent) => { @@ -224,60 +218,15 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer [], ); - useEffect(() => { - const trigger = detectComposerTrigger(props.draftMessage, cursorPosition); - setComposerTrigger(trigger); - }, [props.draftMessage, cursorPosition]); - - // ── File search (debounced) ────────────────────────────── - useEffect(() => { - if (pathSearchTimerRef.current) { - clearTimeout(pathSearchTimerRef.current); - pathSearchTimerRef.current = null; - } - - if (composerTrigger?.kind !== "path" || !composerTrigger.query || !props.projectCwd) { - setPathSearchResults([]); - setPathSearchLoading(false); - return; - } - - setPathSearchLoading(true); - const query = composerTrigger.query; - const cwd = props.projectCwd; - const envId = props.environmentId; - - pathSearchTimerRef.current = setTimeout(() => { - const client = getEnvironmentClient(envId); - if (!client) { - setPathSearchLoading(false); - return; - } - - void client.projects - .searchEntries({ cwd, query, limit: 20 }) - .then((result) => { - setPathSearchResults( - result.entries.map((entry) => ({ - path: entry.path, - kind: entry.kind === "directory" ? ("directory" as const) : ("file" as const), - })), - ); - }) - .catch(() => { - setPathSearchResults([]); - }) - .finally(() => { - setPathSearchLoading(false); - }); - }, 200); - - return () => { - if (pathSearchTimerRef.current) { - clearTimeout(pathSearchTimerRef.current); - } - }; - }, [composerTrigger?.kind, composerTrigger?.query, props.projectCwd, props.environmentId]); + const composerTrigger = useMemo( + () => detectComposerTrigger(props.draftMessage, cursorPosition), + [cursorPosition, props.draftMessage], + ); + const pathSearch = useComposerPathSearch({ + environmentId: props.environmentId, + cwd: composerTrigger?.kind === "path" ? props.projectCwd : null, + query: composerTrigger?.kind === "path" ? composerTrigger.query : null, + }); // ── Build menu items ───────────────────────────────────── const selectedProviderStatus = useMemo(() => { @@ -416,7 +365,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer } if (composerTrigger.kind === "path") { - return pathSearchResults.map((entry) => { + return pathSearch.entries.map((entry) => { const parts = entry.path.split("/"); return { id: `path:${entry.path}`, @@ -430,7 +379,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer } return []; - }, [composerTrigger, selectedProviderStatus, pathSearchResults]); + }, [composerTrigger, pathSearch.entries, selectedProviderStatus]); // ── Handle command selection ────────────────────────────── const { onChangeDraftMessage, onUpdateInteractionMode, draftMessage, onSendMessage } = props; @@ -680,7 +629,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer diff --git a/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx b/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx index c051ad8d34..ddf9361c7b 100644 --- a/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx +++ b/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx @@ -1,6 +1,6 @@ import { sanitizeFeatureBranchName } from "@t3tools/shared/git"; import { useRouter } from "expo-router"; -import { useEffect, useState } from "react"; +import { useState } from "react"; import { Pressable, ScrollView, View } from "react-native"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { useThemeColor } from "../../../lib/useThemeColor"; @@ -52,10 +52,6 @@ export function GitBranchesSheet() { .map((branch) => branch.name), ); - useEffect(() => { - void gitActions.refreshSelectedThreadBranches(); - }, [gitActions]); - return ( ({ - getRegistry: () => appAtomRegistry, - getClient: (environmentId) => getEnvironmentClient(environmentId)?.server ?? null, -}); - -export function sourceControlDiscoveryTargetForEnvironment( - environmentId: EnvironmentId | null, -): SourceControlDiscoveryTarget { - return { key: environmentId ?? null }; -} - -export function refreshSourceControlDiscoveryForEnvironment( - environmentId: EnvironmentId | null, - client?: SourceControlDiscoveryClient | null, -): Promise { - return sourceControlDiscoveryManager.refresh( - sourceControlDiscoveryTargetForEnvironment(environmentId), - client ?? undefined, - ); -} - -export function invalidateSourceControlDiscoveryForEnvironment( - environmentId: EnvironmentId | null, -): void { - sourceControlDiscoveryManager.invalidate( - sourceControlDiscoveryTargetForEnvironment(environmentId), - ); -} - -export function resetSourceControlDiscoveryState(): void { - sourceControlDiscoveryManager.reset(); -} - -export function resetSourceControlDiscoveryStateForTests(): void { - resetSourceControlDiscoveryState(); -} diff --git a/apps/mobile/src/state/use-composer-path-search.ts b/apps/mobile/src/state/use-composer-path-search.ts new file mode 100644 index 0000000000..88f27f7ccc --- /dev/null +++ b/apps/mobile/src/state/use-composer-path-search.ts @@ -0,0 +1,43 @@ +import { useAtomValue } from "@effect/atom-react"; +import { + type ComposerPathSearchState, + type ComposerPathSearchTarget, + EMPTY_COMPOSER_PATH_SEARCH_ATOM, + EMPTY_COMPOSER_PATH_SEARCH_STATE, + composerPathSearchStateAtom, + createComposerPathSearchManager, + getComposerPathSearchTargetKey, + normalizeComposerPathSearchQuery, +} from "@t3tools/client-runtime"; +import { useEffect, useMemo } from "react"; + +import { appAtomRegistry } from "./atom-registry"; +import { + getEnvironmentClient, + subscribeEnvironmentConnections, +} from "./environment-session-registry"; + +const composerPathSearchManager = createComposerPathSearchManager({ + getRegistry: () => appAtomRegistry, + getClient: (environmentId) => getEnvironmentClient(environmentId)?.projects ?? null, + subscribeClientChanges: subscribeEnvironmentConnections, +}); + +export function useComposerPathSearch(target: ComposerPathSearchTarget): ComposerPathSearchState { + const stableTarget = useMemo( + () => ({ + environmentId: target.environmentId, + cwd: target.cwd, + query: normalizeComposerPathSearchQuery(target.query), + }), + [target.cwd, target.environmentId, target.query], + ); + const targetKey = getComposerPathSearchTargetKey(stableTarget); + + useEffect(() => composerPathSearchManager.watch(stableTarget), [stableTarget]); + + const state = useAtomValue( + targetKey !== null ? composerPathSearchStateAtom(targetKey) : EMPTY_COMPOSER_PATH_SEARCH_ATOM, + ); + return targetKey === null ? EMPTY_COMPOSER_PATH_SEARCH_STATE : state; +} diff --git a/apps/mobile/src/state/use-git-branches.ts b/apps/mobile/src/state/use-git-branches.ts index b516906147..5c932a99c1 100644 --- a/apps/mobile/src/state/use-git-branches.ts +++ b/apps/mobile/src/state/use-git-branches.ts @@ -1,4 +1,5 @@ import { useAtomValue } from "@effect/atom-react"; +import { useEffect, useMemo } from "react"; import { type GitBranchState, type GitBranchTarget, @@ -10,7 +11,10 @@ import { } from "@t3tools/client-runtime"; import { appAtomRegistry } from "./atom-registry"; -import { getEnvironmentClient } from "./environment-session-registry"; +import { + getEnvironmentClient, + subscribeEnvironmentConnections, +} from "./environment-session-registry"; export const gitBranchManager = createGitBranchManager({ getRegistry: () => appAtomRegistry, @@ -18,10 +22,21 @@ export const gitBranchManager = createGitBranchManager({ const client = getEnvironmentClient(environmentId); return client ? client.git : null; }, + subscribeClientChanges: subscribeEnvironmentConnections, + watchLimit: 100, }); export function useGitBranches(target: GitBranchTarget): GitBranchState { - const targetKey = getGitBranchTargetKey(target); + const stableTarget = useMemo( + () => ({ + environmentId: target.environmentId, + cwd: target.cwd, + query: target.query ?? null, + }), + [target.cwd, target.environmentId, target.query], + ); + const targetKey = getGitBranchTargetKey(stableTarget); + useEffect(() => gitBranchManager.watch(stableTarget), [stableTarget]); const state = useAtomValue( targetKey !== null ? gitBranchStateAtom(targetKey) : EMPTY_GIT_BRANCH_ATOM, ); diff --git a/apps/mobile/src/state/use-remote-environment-registry.ts b/apps/mobile/src/state/use-remote-environment-registry.ts index 2b9edd817e..0d68352c6f 100644 --- a/apps/mobile/src/state/use-remote-environment-registry.ts +++ b/apps/mobile/src/state/use-remote-environment-registry.ts @@ -31,7 +31,7 @@ import { type ConnectedEnvironmentSummary } from "./remote-runtime-types"; import { invalidateSourceControlDiscoveryForEnvironment, resetSourceControlDiscoveryState, -} from "./source-control-discovery-manager"; +} from "./use-source-control-discovery"; import { environmentRuntimeManager, useEnvironmentRuntimeStates } from "./use-environment-runtime"; import { shellSnapshotManager } from "./use-shell-snapshot"; import { subscribeTerminalMetadata, terminalSessionManager } from "./use-terminal-session"; diff --git a/apps/mobile/src/state/use-source-control-discovery.ts b/apps/mobile/src/state/use-source-control-discovery.ts index 45fba416a9..8f206be2ce 100644 --- a/apps/mobile/src/state/use-source-control-discovery.ts +++ b/apps/mobile/src/state/use-source-control-discovery.ts @@ -2,44 +2,72 @@ import { useAtomValue } from "@effect/atom-react"; import { EMPTY_SOURCE_CONTROL_DISCOVERY_ATOM, EMPTY_SOURCE_CONTROL_DISCOVERY_STATE, + type SourceControlDiscoveryClient, type SourceControlDiscoveryState, + type SourceControlDiscoveryTarget, + createSourceControlDiscoveryManager, getSourceControlDiscoveryTargetKey, sourceControlDiscoveryStateAtom, } from "@t3tools/client-runtime"; -import type { EnvironmentId } from "@t3tools/contracts"; -import { useEffect } from "react"; +import type { EnvironmentId, SourceControlDiscoveryResult } from "@t3tools/contracts"; +import { useEffect, useMemo } from "react"; +import { appAtomRegistry } from "./atom-registry"; import { getEnvironmentClient, subscribeEnvironmentConnections, } from "./environment-session-registry"; -import { - refreshSourceControlDiscoveryForEnvironment, - sourceControlDiscoveryTargetForEnvironment, -} from "./source-control-discovery-manager"; + +const sourceControlDiscoveryManager = createSourceControlDiscoveryManager({ + getRegistry: () => appAtomRegistry, + getClient: (environmentId) => getEnvironmentClient(environmentId)?.server ?? null, + subscribeClientChanges: subscribeEnvironmentConnections, +}); + +function sourceControlDiscoveryTargetForEnvironment( + environmentId: EnvironmentId | null, +): SourceControlDiscoveryTarget { + return { key: environmentId ?? null }; +} + +export function refreshSourceControlDiscoveryForEnvironment( + environmentId: EnvironmentId | null, + client?: SourceControlDiscoveryClient | null, +): Promise { + return sourceControlDiscoveryManager.refresh( + sourceControlDiscoveryTargetForEnvironment(environmentId), + client ?? undefined, + ); +} + +export function invalidateSourceControlDiscoveryForEnvironment( + environmentId: EnvironmentId | null, +): void { + sourceControlDiscoveryManager.invalidate( + sourceControlDiscoveryTargetForEnvironment(environmentId), + ); +} + +export function resetSourceControlDiscoveryState(): void { + sourceControlDiscoveryManager.reset(); +} + +export function resetSourceControlDiscoveryStateForTests(): void { + resetSourceControlDiscoveryState(); +} export function useSourceControlDiscovery( environmentId: EnvironmentId | null, ): SourceControlDiscoveryState { + const target = useMemo( + () => sourceControlDiscoveryTargetForEnvironment(environmentId), + [environmentId], + ); + useEffect(() => { - if (!environmentId) { - return; - } + return sourceControlDiscoveryManager.watch(target); + }, [target]); - const refresh = () => { - const client = getEnvironmentClient(environmentId); - if (!client) { - return; - } - - void refreshSourceControlDiscoveryForEnvironment(environmentId, client.server); - }; - - refresh(); - return subscribeEnvironmentConnections(refresh); - }, [environmentId]); - - const target = sourceControlDiscoveryTargetForEnvironment(environmentId); const targetKey = getSourceControlDiscoveryTargetKey(target); const state = useAtomValue( targetKey !== null diff --git a/apps/mobile/src/state/use-thread-detail.ts b/apps/mobile/src/state/use-thread-detail.ts index 9d1285130a..900dbd648b 100644 --- a/apps/mobile/src/state/use-thread-detail.ts +++ b/apps/mobile/src/state/use-thread-detail.ts @@ -39,7 +39,7 @@ function shouldKeepThreadDetailWarm(state: ThreadDetailState): boolean { ); } -export const threadDetailManager = createThreadDetailManager({ +const threadDetailManager = createThreadDetailManager({ getRegistry: () => appAtomRegistry, getClient: (environmentId) => { const client = getEnvironmentClient(environmentId); diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 96fc34c101..61a42d5125 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -2,7 +2,6 @@ import type { ApprovalRequestId, EnvironmentId, ModelSelection, - ProjectEntry, ProviderApprovalDecision, ProviderInteractionMode, ResolvedKeybindingsConfig, @@ -29,9 +28,6 @@ import { useRef, useState, } from "react"; -import { useQuery } from "@tanstack/react-query"; -import { useDebouncedValue } from "@tanstack/react-pacer"; -import { projectSearchEntriesQueryOptions } from "~/lib/projectReactQuery"; import { clampCollapsedComposerCursor, type ComposerTrigger, @@ -55,6 +51,7 @@ import { insertInlineTerminalContextPlaceholder, removeInlineTerminalContextPlaceholder, } from "../../lib/terminalContext"; +import { useComposerPathSearch } from "../../lib/composerPathSearchState"; import { shouldUseCompactComposerPrimaryActions, shouldUseCompactComposerFooter, @@ -136,8 +133,6 @@ const runtimeModeConfig: Record< }; const runtimeModeOptions = Object.keys(runtimeModeConfig) as RuntimeMode[]; -const COMPOSER_PATH_QUERY_DEBOUNCE_MS = 120; -const EMPTY_PROJECT_ENTRIES: ProjectEntry[] = []; const COMPOSER_FLOATING_LAYER_SELECTOR = [ '[data-slot="popover-popup"]', '[data-slot="menu-popup"]', @@ -833,27 +828,16 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const composerTriggerKind = composerTrigger?.kind ?? null; const pathTriggerQuery = composerTrigger?.kind === "path" ? composerTrigger.query : ""; const isPathTrigger = composerTriggerKind === "path"; - const [debouncedPathQuery, composerPathQueryDebouncer] = useDebouncedValue( - pathTriggerQuery, - { wait: COMPOSER_PATH_QUERY_DEBOUNCE_MS }, - (debouncerState) => ({ isPending: debouncerState.isPending }), - ); - const effectivePathQuery = pathTriggerQuery.length > 0 ? debouncedPathQuery : ""; - const workspaceEntriesQuery = useQuery( - projectSearchEntriesQueryOptions({ - environmentId, - cwd: gitCwd, - query: effectivePathQuery, - enabled: isPathTrigger, - limit: 80, - }), - ); - const workspaceEntries = workspaceEntriesQuery.data?.entries ?? EMPTY_PROJECT_ENTRIES; + const workspaceEntries = useComposerPathSearch({ + environmentId, + cwd: isPathTrigger ? gitCwd : null, + query: isPathTrigger ? pathTriggerQuery : null, + }); const composerMenuItems = useMemo(() => { if (!composerTrigger) return []; if (composerTrigger.kind === "path") { - return workspaceEntries.map((entry) => ({ + return workspaceEntries.entries.map((entry) => ({ id: `path:${entry.kind}:${entry.path}`, type: "path", path: entry.path, @@ -919,7 +903,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ); } return []; - }, [composerTrigger, selectedProvider, selectedProviderStatus, workspaceEntries]); + }, [composerTrigger, selectedProvider, selectedProviderStatus, workspaceEntries.entries]); const composerMenuOpen = Boolean(composerTrigger); const composerMenuSearchKey = composerTrigger @@ -984,10 +968,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ]); const isComposerMenuLoading = - composerTriggerKind === "path" && - ((pathTriggerQuery.length > 0 && composerPathQueryDebouncer.state.isPending) || - workspaceEntriesQuery.isLoading || - workspaceEntriesQuery.isFetching); + composerTriggerKind === "path" && pathTriggerQuery.length > 0 && workspaceEntries.isPending; const composerMenuEmptyState = useMemo(() => { if (composerTriggerKind === "skill") { return "No skills found. Try / to browse provider commands."; diff --git a/apps/web/src/lib/composerPathSearchState.ts b/apps/web/src/lib/composerPathSearchState.ts new file mode 100644 index 0000000000..c117e373c7 --- /dev/null +++ b/apps/web/src/lib/composerPathSearchState.ts @@ -0,0 +1,48 @@ +import { useAtomValue } from "@effect/atom-react"; +import { + type ComposerPathSearchState, + type ComposerPathSearchTarget, + EMPTY_COMPOSER_PATH_SEARCH_ATOM, + EMPTY_COMPOSER_PATH_SEARCH_STATE, + composerPathSearchStateAtom, + createComposerPathSearchManager, + getComposerPathSearchTargetKey, + normalizeComposerPathSearchQuery, +} from "@t3tools/client-runtime"; +import { useEffect, useMemo } from "react"; + +import { + readEnvironmentConnection, + subscribeEnvironmentConnections, +} from "../environments/runtime"; +import { appAtomRegistry } from "../rpc/atomRegistry"; + +const COMPOSER_PATH_SEARCH_LIMIT = 80; +const COMPOSER_PATH_SEARCH_DEBOUNCE_MS = 120; + +const composerPathSearchManager = createComposerPathSearchManager({ + getRegistry: () => appAtomRegistry, + getClient: (environmentId) => readEnvironmentConnection(environmentId)?.client.projects ?? null, + subscribeClientChanges: subscribeEnvironmentConnections, + limit: COMPOSER_PATH_SEARCH_LIMIT, + debounceMs: COMPOSER_PATH_SEARCH_DEBOUNCE_MS, +}); + +export function useComposerPathSearch(target: ComposerPathSearchTarget): ComposerPathSearchState { + const stableTarget = useMemo( + () => ({ + environmentId: target.environmentId, + cwd: target.cwd, + query: normalizeComposerPathSearchQuery(target.query), + }), + [target.cwd, target.environmentId, target.query], + ); + const targetKey = getComposerPathSearchTargetKey(stableTarget); + + useEffect(() => composerPathSearchManager.watch(stableTarget), [stableTarget]); + + const state = useAtomValue( + targetKey !== null ? composerPathSearchStateAtom(targetKey) : EMPTY_COMPOSER_PATH_SEARCH_ATOM, + ); + return targetKey === null ? EMPTY_COMPOSER_PATH_SEARCH_STATE : state; +} diff --git a/apps/web/src/lib/sourceControlDiscoveryState.ts b/apps/web/src/lib/sourceControlDiscoveryState.ts index daff900a0d..e70ff048f6 100644 --- a/apps/web/src/lib/sourceControlDiscoveryState.ts +++ b/apps/web/src/lib/sourceControlDiscoveryState.ts @@ -35,7 +35,7 @@ function sourceControlDiscoveryTarget( : { key: environmentId }; } -export const sourceControlDiscoveryManager = createSourceControlDiscoveryManager({ +const sourceControlDiscoveryManager = createSourceControlDiscoveryManager({ getRegistry: () => appAtomRegistry, getClient: (key) => { if (key === SOURCE_CONTROL_DISCOVERY_TARGET.key) { diff --git a/bun.lock b/bun.lock index 73a60420ae..bf07f09815 100644 --- a/bun.lock +++ b/bun.lock @@ -339,7 +339,10 @@ "node-pty", ], "patchedDependencies": { + "expo-dev-launcher@55.0.28": "patches/expo-dev-launcher@55.0.28.patch", + "react-native-nitro-modules@0.35.4": "patches/react-native-nitro-modules@0.35.4.patch", "effect@4.0.0-beta.59": "patches/effect@4.0.0-beta.59.patch", + "@pierre/diffs@1.1.20": "patches/@pierre%2Fdiffs@1.1.20.patch", }, "overrides": { "@effect/atom-react": "catalog:", diff --git a/package.json b/package.json index cc581b634c..49f97ad6f5 100644 --- a/package.json +++ b/package.json @@ -92,7 +92,10 @@ ] }, "patchedDependencies": { - "effect@4.0.0-beta.59": "patches/effect@4.0.0-beta.59.patch" + "effect@4.0.0-beta.59": "patches/effect@4.0.0-beta.59.patch", + "expo-dev-launcher@55.0.28": "patches/expo-dev-launcher@55.0.28.patch", + "react-native-nitro-modules@0.35.4": "patches/react-native-nitro-modules@0.35.4.patch", + "@pierre/diffs@1.1.20": "patches/@pierre%2Fdiffs@1.1.20.patch" }, "trustedDependencies": [ "node-pty", diff --git a/packages/client-runtime/src/composerPathSearchState.test.ts b/packages/client-runtime/src/composerPathSearchState.test.ts new file mode 100644 index 0000000000..b3b928c1e1 --- /dev/null +++ b/packages/client-runtime/src/composerPathSearchState.test.ts @@ -0,0 +1,111 @@ +import { assert, beforeEach, it } from "vitest"; +import type { EnvironmentId } from "@t3tools/contracts"; +import { AtomRegistry } from "effect/unstable/reactivity"; + +import { + type ComposerPathSearchClient, + createComposerPathSearchManager, + EMPTY_COMPOSER_PATH_SEARCH_STATE, + getComposerPathSearchTargetKey, +} from "./composerPathSearchState.ts"; + +let registry = AtomRegistry.make(); + +const noop = () => undefined; + +beforeEach(() => { + registry.dispose(); + registry = AtomRegistry.make(); +}); + +function flushAsyncWork(): Promise { + return Promise.resolve().then(() => undefined); +} + +const TARGET = { + environmentId: "env-local" as EnvironmentId, + cwd: "/repo", + query: "src", +}; + +it("derives null keys for inactive path searches", () => { + assert.strictEqual(getComposerPathSearchTargetKey({ ...TARGET, query: "" }), null); + assert.strictEqual(getComposerPathSearchTargetKey({ ...TARGET, cwd: null }), null); + assert.strictEqual(getComposerPathSearchTargetKey({ ...TARGET, environmentId: null }), null); +}); + +it("stores path search results in atom state", async () => { + const manager = createComposerPathSearchManager({ + getRegistry: () => registry, + debounceMs: 0, + getClient: () => ({ + searchEntries: async () => ({ + entries: [ + { path: "src/index.ts", kind: "file" }, + { path: "src/components", kind: "directory" }, + ], + truncated: false, + }), + }), + }); + + manager.search(TARGET); + await flushAsyncWork(); + + assert.deepStrictEqual(manager.getSnapshot(TARGET), { + entries: [ + { path: "src/index.ts", kind: "file" }, + { path: "src/components", kind: "directory" }, + ], + isPending: false, + error: null, + }); +}); + +it("ignores stale path search results after a newer request starts", async () => { + let resolveFirst: (value: { + entries: ReadonlyArray<{ path: string; kind: "file" | "directory" }>; + truncated: boolean; + }) => void = noop; + const manager = createComposerPathSearchManager({ + getRegistry: () => registry, + debounceMs: 0, + getClient: () => ({ + searchEntries: (input: Parameters[0]) => { + if (input.query === "first") { + return new Promise((resolve) => { + resolveFirst = resolve; + }); + } + return Promise.resolve({ + entries: [{ path: "second.ts", kind: "file" }], + truncated: false, + }); + }, + }), + }); + + manager.search({ ...TARGET, query: "first" }); + manager.search({ ...TARGET, query: "second" }); + await flushAsyncWork(); + resolveFirst({ entries: [{ path: "first.ts", kind: "file" }], truncated: false }); + await flushAsyncWork(); + + assert.deepStrictEqual(manager.getSnapshot({ ...TARGET, query: "second" }), { + entries: [{ path: "second.ts", kind: "file" }], + isPending: false, + error: null, + }); +}); + +it("returns the empty snapshot for inactive targets", () => { + const manager = createComposerPathSearchManager({ + getRegistry: () => registry, + getClient: () => null, + }); + + assert.deepStrictEqual( + manager.getSnapshot({ environmentId: null, cwd: null, query: null }), + EMPTY_COMPOSER_PATH_SEARCH_STATE, + ); +}); diff --git a/packages/client-runtime/src/composerPathSearchState.ts b/packages/client-runtime/src/composerPathSearchState.ts new file mode 100644 index 0000000000..aaa1f8ce4f --- /dev/null +++ b/packages/client-runtime/src/composerPathSearchState.ts @@ -0,0 +1,288 @@ +import type { EnvironmentId, ProjectSearchEntriesResult } from "@t3tools/contracts"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import { Atom, type AtomRegistry } from "effect/unstable/reactivity"; + +export interface ComposerPathSearchEntry { + readonly path: string; + readonly kind: "file" | "directory"; + readonly parentPath?: string; +} + +export interface ComposerPathSearchState { + readonly entries: ReadonlyArray; + readonly isPending: boolean; + readonly error: string | null; +} + +export interface ComposerPathSearchTarget { + readonly environmentId: EnvironmentId | null; + readonly cwd: string | null; + readonly query: string | null; +} + +export interface ComposerPathSearchClient { + readonly searchEntries: (input: { + readonly cwd: string; + readonly query: string; + readonly limit: number; + }) => Promise; +} + +interface WatchedEntry { + refCount: number; + teardown: () => void; +} + +export const EMPTY_COMPOSER_PATH_SEARCH_STATE = Object.freeze({ + entries: [], + isPending: false, + error: null, +}); + +const PENDING_COMPOSER_PATH_SEARCH_STATE = Object.freeze({ + entries: [], + isPending: true, + error: null, +}); + +const NOOP: () => void = () => undefined; +const DEFAULT_DEBOUNCE_MS = 200; +const DEFAULT_LIMIT = 20; + +export const composerPathSearchStateAtom = Atom.family((key: string) => + Atom.make(EMPTY_COMPOSER_PATH_SEARCH_STATE).pipe( + Atom.keepAlive, + Atom.withLabel(`composer-path-search:${key}`), + ), +); + +export const EMPTY_COMPOSER_PATH_SEARCH_ATOM = Atom.make(EMPTY_COMPOSER_PATH_SEARCH_STATE).pipe( + Atom.keepAlive, + Atom.withLabel("composer-path-search:null"), +); + +export function normalizeComposerPathSearchQuery(query: string | null): string { + return query?.trim() ?? ""; +} + +export function getComposerPathSearchTargetKey(target: ComposerPathSearchTarget): string | null { + const query = normalizeComposerPathSearchQuery(target.query); + if (target.environmentId === null || target.cwd === null || query.length === 0) { + return null; + } + + return `${target.environmentId}:${target.cwd}:${query}`; +} + +function toSearchEntries( + entries: ProjectSearchEntriesResult["entries"], +): ReadonlyArray { + return entries.map((entry) => ({ + path: entry.path, + kind: entry.kind === "directory" ? "directory" : "file", + ...(entry.parentPath !== undefined ? { parentPath: entry.parentPath } : {}), + })); +} + +export function createComposerPathSearchManager(config: { + readonly getRegistry: () => AtomRegistry.AtomRegistry; + readonly getClient: (environmentId: EnvironmentId) => ComposerPathSearchClient | null; + readonly subscribeClientChanges?: (listener: () => void) => () => void; + readonly debounceMs?: number; + readonly limit?: number; +}) { + const watched = new Map(); + const versions = new Map(); + const timers = new Map>(); + const debounceMs = config.debounceMs ?? DEFAULT_DEBOUNCE_MS; + const limit = config.limit ?? DEFAULT_LIMIT; + + function bumpVersion(targetKey: string): number { + const next = (versions.get(targetKey) ?? 0) + 1; + versions.set(targetKey, next); + return next; + } + + function setState(targetKey: string, state: ComposerPathSearchState): void { + config.getRegistry().set(composerPathSearchStateAtom(targetKey), state); + } + + function clearTimer(targetKey: string): void { + const fiber = timers.get(targetKey); + if (fiber) { + Effect.runFork(Fiber.interrupt(fiber)); + timers.delete(targetKey); + } + } + + function getSnapshot(target: ComposerPathSearchTarget): ComposerPathSearchState { + const targetKey = getComposerPathSearchTargetKey(target); + return targetKey === null + ? EMPTY_COMPOSER_PATH_SEARCH_STATE + : config.getRegistry().get(composerPathSearchStateAtom(targetKey)); + } + + function runSearch( + targetKey: string, + target: ComposerPathSearchTarget & { + readonly environmentId: EnvironmentId; + readonly cwd: string; + }, + client: ComposerPathSearchClient, + version: number, + ): void { + void client + .searchEntries({ + cwd: target.cwd, + query: normalizeComposerPathSearchQuery(target.query), + limit, + }) + .then((result) => { + if (versions.get(targetKey) !== version) { + return; + } + setState(targetKey, { + entries: toSearchEntries(result.entries), + isPending: false, + error: null, + }); + }) + .catch((error: unknown) => { + if (versions.get(targetKey) !== version) { + return; + } + setState(targetKey, { + entries: [], + isPending: false, + error: error instanceof Error ? error.message : "Failed to search project files.", + }); + }); + } + + function search(target: ComposerPathSearchTarget, client?: ComposerPathSearchClient): void { + const targetKey = getComposerPathSearchTargetKey(target); + if (targetKey === null || target.environmentId === null || target.cwd === null) { + return; + } + + const resolved = client ?? config.getClient(target.environmentId); + if (!resolved) { + setState(targetKey, { + entries: [], + isPending: false, + error: "Remote connection is not ready.", + }); + return; + } + + const version = bumpVersion(targetKey); + clearTimer(targetKey); + setState(targetKey, PENDING_COMPOSER_PATH_SEARCH_STATE); + + const readyTarget = { + ...target, + environmentId: target.environmentId, + cwd: target.cwd, + }; + + if (debounceMs <= 0) { + runSearch(targetKey, readyTarget, resolved, version); + return; + } + + const fiber = Effect.runFork( + Effect.sleep(Duration.millis(debounceMs)).pipe( + Effect.andThen( + Effect.sync(() => { + timers.delete(targetKey); + runSearch(targetKey, readyTarget, resolved, version); + }), + ), + ), + ); + timers.set(targetKey, fiber); + } + + function watch(target: ComposerPathSearchTarget): () => void { + const targetKey = getComposerPathSearchTargetKey(target); + if (targetKey === null || target.environmentId === null || target.cwd === null) { + return NOOP; + } + + const existing = watched.get(targetKey); + if (existing) { + existing.refCount += 1; + return () => unwatch(targetKey); + } + + let currentClient: ComposerPathSearchClient | null = null; + const sync = () => { + const client = config.getClient(target.environmentId!); + if (!client) { + currentClient = null; + setState(targetKey, { + entries: [], + isPending: false, + error: "Remote connection is not ready.", + }); + return; + } + + if (currentClient === client) { + return; + } + + currentClient = client; + search(target, client); + }; + + const unsubscribe = config.subscribeClientChanges?.(sync) ?? NOOP; + sync(); + + watched.set(targetKey, { + refCount: 1, + teardown: () => { + unsubscribe(); + clearTimer(targetKey); + bumpVersion(targetKey); + }, + }); + + return () => unwatch(targetKey); + } + + function unwatch(targetKey: string): void { + const entry = watched.get(targetKey); + if (!entry) { + return; + } + + entry.refCount -= 1; + if (entry.refCount > 0) { + return; + } + + entry.teardown(); + watched.delete(targetKey); + } + + function reset(): void { + for (const entry of watched.values()) { + entry.teardown(); + } + watched.clear(); + versions.clear(); + for (const targetKey of timers.keys()) { + clearTimer(targetKey); + } + } + + return { + getSnapshot, + search, + watch, + reset, + }; +} diff --git a/packages/client-runtime/src/gitBranchState.test.ts b/packages/client-runtime/src/gitBranchState.test.ts index 78f53a02bc..5220c6dcac 100644 --- a/packages/client-runtime/src/gitBranchState.test.ts +++ b/packages/client-runtime/src/gitBranchState.test.ts @@ -16,6 +16,8 @@ function resetAtomRegistry() { atomRegistry = AtomRegistry.make(); } +const noop = () => undefined; + const TARGET = { environmentId: EnvironmentId.make("env-local"), cwd: "/repo" } as const; const FIRST_PAGE: GitListBranchesResult = { @@ -158,4 +160,35 @@ describe("createGitBranchManager", () => { expect(manager.getSnapshot(TARGET)).toEqual(EMPTY_GIT_BRANCH_STATE); }); + + it("watches branches with a ref-counted client-change subscription", async () => { + const mock = createMockClient(); + let listener: () => void = noop; + const unsubscribe = vi.fn(); + const manager = createGitBranchManager({ + getRegistry: () => atomRegistry, + getClient: () => mock.client, + subscribeClientChanges: (nextListener) => { + listener = nextListener; + return unsubscribe; + }, + watchLimit: 100, + }); + + const firstUnwatch = manager.watch(TARGET); + const secondUnwatch = manager.watch(TARGET); + await Promise.resolve(); + + expect(mock.listRefs).toHaveBeenCalledTimes(1); + expect(mock.listRefs).toHaveBeenCalledWith({ cwd: "/repo", limit: 100 }); + + listener(); + await Promise.resolve(); + expect(mock.listRefs).toHaveBeenCalledTimes(1); + + firstUnwatch(); + expect(unsubscribe).not.toHaveBeenCalled(); + secondUnwatch(); + expect(unsubscribe).toHaveBeenCalledTimes(1); + }); }); diff --git a/packages/client-runtime/src/gitBranchState.ts b/packages/client-runtime/src/gitBranchState.ts index fe70a30cec..7753b341fb 100644 --- a/packages/client-runtime/src/gitBranchState.ts +++ b/packages/client-runtime/src/gitBranchState.ts @@ -82,10 +82,22 @@ function mergeBranches( export interface GitBranchManagerConfig { readonly getRegistry: () => AtomRegistry.AtomRegistry; readonly getClient: (environmentId: EnvironmentId) => GitBranchClient | null; + readonly subscribeClientChanges?: (listener: () => void) => () => void; + readonly watchLimit?: number; } +interface WatchedEntry { + refCount: number; + teardown: () => void; +} + +const NOOP: () => void = () => undefined; + export function createGitBranchManager(config: GitBranchManagerConfig) { const inFlight = new Map>(); + const watched = new Map(); + const watchLoadOptions = + config.watchLimit === undefined ? undefined : { limit: config.watchLimit }; function getSnapshot(target: GitBranchTarget): GitBranchState { const targetKey = getGitBranchTargetKey(target); @@ -204,6 +216,70 @@ export function createGitBranchManager(config: GitBranchManagerConfig) { }); } + function watch(target: GitBranchTarget, client?: GitBranchClient): () => void { + const targetKey = getGitBranchTargetKey(target); + if (targetKey === null || target.environmentId === null || target.cwd === null) { + return NOOP; + } + + const existing = watched.get(targetKey); + if (existing) { + existing.refCount += 1; + return () => unwatch(targetKey); + } + + let teardown: () => void; + + if (client) { + void load(target, client, watchLoadOptions); + teardown = NOOP; + } else if (config.subscribeClientChanges) { + let currentClient: GitBranchClient | null = null; + const sync = () => { + const resolved = config.getClient(target.environmentId!); + if (!resolved) { + currentClient = null; + return; + } + if (currentClient === resolved) { + return; + } + + currentClient = resolved; + void load(target, resolved, watchLoadOptions); + }; + + const unsubscribe = config.subscribeClientChanges(sync); + sync(); + teardown = unsubscribe; + } else { + const resolved = config.getClient(target.environmentId); + if (!resolved) { + return NOOP; + } + void load(target, resolved, watchLoadOptions); + teardown = NOOP; + } + + watched.set(targetKey, { refCount: 1, teardown }); + return () => unwatch(targetKey); + } + + function unwatch(targetKey: string): void { + const entry = watched.get(targetKey); + if (!entry) { + return; + } + + entry.refCount -= 1; + if (entry.refCount > 0) { + return; + } + + entry.teardown(); + watched.delete(targetKey); + } + function invalidate(target?: GitBranchTarget): void { if (target) { const targetKey = getGitBranchTargetKey(target); @@ -219,11 +295,16 @@ export function createGitBranchManager(config: GitBranchManagerConfig) { } function reset(): void { + for (const entry of watched.values()) { + entry.teardown(); + } + watched.clear(); invalidate(); } return { getSnapshot, + watch, load, loadNext, invalidate, diff --git a/packages/client-runtime/src/index.ts b/packages/client-runtime/src/index.ts index cfc6359ff5..8f35bf51cb 100644 --- a/packages/client-runtime/src/index.ts +++ b/packages/client-runtime/src/index.ts @@ -19,3 +19,4 @@ export * from "./wsRpcProtocol.ts"; export * from "./wsTransport.ts"; export * from "./wsRpcClient.ts"; export * from "./environmentConnection.ts"; +export * from "./composerPathSearchState.ts"; diff --git a/packages/client-runtime/src/sourceControlDiscoveryState.test.ts b/packages/client-runtime/src/sourceControlDiscoveryState.test.ts index 583dcfa551..7a047bf413 100644 --- a/packages/client-runtime/src/sourceControlDiscoveryState.test.ts +++ b/packages/client-runtime/src/sourceControlDiscoveryState.test.ts @@ -50,11 +50,17 @@ function unresolvedDiscovery() { let registry = AtomRegistry.make(); +const noop = () => undefined; + beforeEach(() => { registry.dispose(); registry = AtomRegistry.make(); }); +function flushAsyncWork(): Promise { + return Promise.resolve().then(() => undefined); +} + it("stores refreshed discovery data in an atom snapshot", async () => { const manager = createSourceControlDiscoveryManager({ getRegistry: () => registry, @@ -181,3 +187,99 @@ it("ignores an in-flight refresh after the target is invalidated", async () => { isPending: true, }); }); + +it("watches a discovery target with ref-counted client-change subscriptions", async () => { + let listener: () => void = noop; + let subscribeCalls = 0; + let unsubscribeCalls = 0; + let discoveryCalls = 0; + const client = { + discoverSourceControl: async () => { + discoveryCalls += 1; + return EMPTY_RESULT; + }, + }; + const manager = createSourceControlDiscoveryManager({ + getRegistry: () => registry, + getClient: () => client, + subscribeClientChanges: (nextListener) => { + subscribeCalls += 1; + listener = nextListener; + return () => { + unsubscribeCalls += 1; + }; + }, + }); + + const firstUnwatch = manager.watch({ key: "primary" }); + const secondUnwatch = manager.watch({ key: "primary" }); + await flushAsyncWork(); + + assert.strictEqual(subscribeCalls, 1); + assert.strictEqual(discoveryCalls, 1); + assert.deepStrictEqual(manager.getSnapshot({ key: "primary" }), { + data: EMPTY_RESULT, + error: null, + isPending: false, + }); + + listener(); + await flushAsyncWork(); + assert.strictEqual(discoveryCalls, 1); + + firstUnwatch(); + assert.strictEqual(unsubscribeCalls, 0); + + secondUnwatch(); + assert.strictEqual(unsubscribeCalls, 1); +}); + +it("refreshes a watched discovery target when the resolved client is replaced", async () => { + let listener: () => void = noop; + let activeResult = EMPTY_RESULT; + let discoveryCalls = 0; + const firstClient = { + discoverSourceControl: async () => { + discoveryCalls += 1; + return activeResult; + }, + }; + const secondClient = { + discoverSourceControl: async () => { + discoveryCalls += 1; + return activeResult; + }, + }; + let activeClient = firstClient; + const manager = createSourceControlDiscoveryManager({ + getRegistry: () => registry, + getClient: () => activeClient, + subscribeClientChanges: (nextListener) => { + listener = nextListener; + return () => undefined; + }, + }); + + const unwatch = manager.watch({ key: "primary" }); + await flushAsyncWork(); + + assert.deepStrictEqual(manager.getSnapshot({ key: "primary" }), { + data: EMPTY_RESULT, + error: null, + isPending: false, + }); + + activeClient = secondClient; + activeResult = GITHUB_RESULT; + listener(); + await flushAsyncWork(); + + assert.strictEqual(discoveryCalls, 2); + assert.deepStrictEqual(manager.getSnapshot({ key: "primary" }), { + data: GITHUB_RESULT, + error: null, + isPending: false, + }); + + unwatch(); +}); diff --git a/packages/client-runtime/src/sourceControlDiscoveryState.ts b/packages/client-runtime/src/sourceControlDiscoveryState.ts index c74d1dd85f..5d1f1beda3 100644 --- a/packages/client-runtime/src/sourceControlDiscoveryState.ts +++ b/packages/client-runtime/src/sourceControlDiscoveryState.ts @@ -17,6 +17,11 @@ export interface SourceControlDiscoveryClient { readonly discoverSourceControl: () => Promise; } +interface WatchedEntry { + refCount: number; + teardown: () => void; +} + /* --- Constants ------------------------------------------------------ */ export const EMPTY_SOURCE_CONTROL_DISCOVERY_STATE = Object.freeze({ @@ -71,13 +76,29 @@ export interface SourceControlDiscoveryManagerConfig SourceControlDiscoveryClient | null; + /** + * Optional: subscribe to environment/client availability changes. + * + * When provided, `watch` refreshes as clients appear or are replaced + * instead of relying on React hooks to manually kick discovery. + */ + readonly subscribeClientChanges?: (listener: () => void) => () => void; } +const NOOP: () => void = () => undefined; + export function createSourceControlDiscoveryManager( config: SourceControlDiscoveryManagerConfig, ) { - const refreshInFlight = new Map>(); + const refreshInFlight = new Map< + string, + { + readonly client: SourceControlDiscoveryClient; + readonly promise: Promise; + } + >(); const refreshVersions = new Map(); + const watched = new Map(); function getRefreshVersion(targetKey: string): number { return refreshVersions.get(targetKey) ?? 0; @@ -154,11 +175,6 @@ export function createSourceControlDiscoveryManager refresh(target, resolvedClient)); + } + markPending(targetKey); const refreshVersion = getRefreshVersion(targetKey); const promise = resolvedClient.discoverSourceControl().then( @@ -184,11 +209,14 @@ export function createSourceControlDiscoveryManager; tracked = promise.finally(() => { - if (refreshInFlight.get(targetKey) === tracked) { + if (refreshInFlight.get(targetKey)?.promise === tracked) { refreshInFlight.delete(targetKey); } }); - refreshInFlight.set(targetKey, tracked); + refreshInFlight.set(targetKey, { + client: resolvedClient, + promise: tracked, + }); return tracked; } @@ -228,12 +256,93 @@ export function createSourceControlDiscoveryManager, + client?: SourceControlDiscoveryClient, + ): () => void { + const targetKey = getSourceControlDiscoveryTargetKey(target); + if (targetKey === null) { + return NOOP; + } + + const existing = watched.get(targetKey); + if (existing) { + existing.refCount += 1; + return () => unwatch(targetKey); + } + + let teardown: () => void; + + if (client) { + void refresh(target, client); + teardown = NOOP; + } else if (config.subscribeClientChanges) { + let currentClient: SourceControlDiscoveryClient | null = null; + + const sync = () => { + const resolved = config.getClient(targetKey); + if (!resolved) { + currentClient = null; + markPending(targetKey); + return; + } + + if (currentClient === resolved) { + return; + } + + currentClient = resolved; + void refresh(target, resolved); + }; + + const unsubChanges = config.subscribeClientChanges(sync); + sync(); + teardown = unsubChanges; + } else { + const resolved = config.getClient(targetKey); + if (!resolved) { + return NOOP; + } + void refresh(target, resolved); + teardown = NOOP; + } + + watched.set(targetKey, { refCount: 1, teardown }); + return () => unwatch(targetKey); + } + + function unwatch(targetKey: string): void { + const entry = watched.get(targetKey); + if (!entry) { + return; + } + + entry.refCount -= 1; + if (entry.refCount > 0) { + return; + } + + entry.teardown(); + watched.delete(targetKey); + } + /** * Clear in-flight refresh tracking and reset every known discovery atom. * Primarily used by tests and runtime teardown. */ function reset(): void { const keys = new Set([...knownSourceControlDiscoveryKeys, ...refreshInFlight.keys()]); + for (const entry of watched.values()) { + entry.teardown(); + } + watched.clear(); refreshInFlight.clear(); for (const key of keys) { bumpRefreshVersion(key); @@ -242,6 +351,7 @@ export function createSourceControlDiscoveryManager diff --git a/scripts/patch-expo-dev-launcher.mjs b/scripts/patch-expo-dev-launcher.mjs deleted file mode 100644 index 9f0a3bd340..0000000000 --- a/scripts/patch-expo-dev-launcher.mjs +++ /dev/null @@ -1,63 +0,0 @@ -import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs"; -import { join } from "node:path"; - -const root = process.cwd(); - -const candidates = [join(root, "node_modules/expo-dev-launcher/ios/EXDevLauncherController.m")]; - -const bunStorePath = join(root, "node_modules/.bun"); - -if (existsSync(bunStorePath)) { - for (const entry of readdirSync(bunStorePath)) { - if (!entry.startsWith("expo-dev-launcher@")) { - continue; - } - - candidates.push( - join(bunStorePath, entry, "node_modules/expo-dev-launcher/ios/EXDevLauncherController.m"), - ); - } -} - -const targetLine = "[manager updateCurrentBridge:self.appBridge];"; -const replacement = [ - " // Expo SDK 55's dev launcher still references `self.appBridge`,", - " // but React Native 0.83 removed that property from the delegate base class.", - " // Newer Expo builds stop updating the dev menu bridge here.", -].join("\n"); - -let patchedCount = 0; -let locatedCount = 0; - -for (const filePath of candidates) { - if (!existsSync(filePath)) { - continue; - } - - locatedCount += 1; - const source = readFileSync(filePath, "utf8"); - - if (source.includes(replacement)) { - continue; - } - - if (!source.includes(targetLine)) { - throw new Error( - `Found expo-dev-launcher source at ${filePath}, but the expected bridge line was missing.`, - ); - } - - const nextSource = source.replace(` ${targetLine}`, replacement); - writeFileSync(filePath, nextSource); - patchedCount += 1; -} - -if (patchedCount > 0) { - console.log( - `[patch-expo-dev-launcher] patched ${patchedCount} expo-dev-launcher installation(s).`, - ); -} else if (locatedCount > 0) { - console.log("[patch-expo-dev-launcher] expo-dev-launcher already patched."); -} else { - console.log("[patch-expo-dev-launcher] expo-dev-launcher not installed; skipping."); -} diff --git a/scripts/patch-pierre-diffs-utils.mjs b/scripts/patch-pierre-diffs-utils.mjs deleted file mode 100644 index 11ab526ee3..0000000000 --- a/scripts/patch-pierre-diffs-utils.mjs +++ /dev/null @@ -1,105 +0,0 @@ -import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs"; -import { join } from "node:path"; - -const root = process.cwd(); -const bunStorePath = join(root, "node_modules/.bun"); - -const packageDirs = []; - -if (existsSync(join(root, "node_modules/@pierre/diffs"))) { - packageDirs.push(join(root, "node_modules/@pierre/diffs")); -} - -if (existsSync(bunStorePath)) { - for (const entry of readdirSync(bunStorePath)) { - if (!entry.startsWith("@pierre+diffs@")) { - continue; - } - - packageDirs.push(join(bunStorePath, entry, "node_modules/@pierre/diffs")); - } -} - -const utilsIndexJs = [ - 'export { parsePatchFiles, processFile, processPatch } from "./parsePatchFiles.js";', - "export {", - " EXTENSION_TO_FILE_FORMAT,", - " getCustomExtensionsMap,", - " getCustomExtensionsVersion,", - " getFiletypeFromFileName,", - " replaceCustomExtensions,", - " setCustomExtension,", - '} from "./getFiletypeFromFileName.js";', - "", -].join("\n"); - -const utilsIndexDts = [ - 'export { parsePatchFiles, processFile, processPatch } from "./parsePatchFiles.js";', - "export {", - " EXTENSION_TO_FILE_FORMAT,", - " getCustomExtensionsMap,", - " getCustomExtensionsVersion,", - " getFiletypeFromFileName,", - " replaceCustomExtensions,", - " setCustomExtension,", - '} from "./getFiletypeFromFileName.js";', - 'export type { ChangeTypes, FileDiffMetadata, ParsedPatch, SupportedLanguages } from "../types.js";', - "", -].join("\n"); - -let patchedCount = 0; -let locatedCount = 0; - -for (const packageDir of packageDirs) { - if (!existsSync(packageDir)) { - continue; - } - - locatedCount += 1; - - const packageJsonPath = join(packageDir, "package.json"); - const utilsIndexJsPath = join(packageDir, "dist/utils/index.js"); - const utilsIndexDtsPath = join(packageDir, "dist/utils/index.d.ts"); - - const pkg = JSON.parse(readFileSync(packageJsonPath, "utf8")); - const currentUtilsExport = pkg.exports?.["./utils"]; - - const expectedUtilsExport = { - types: "./dist/utils/index.d.ts", - import: "./dist/utils/index.js", - }; - - const needsExportPatch = - currentUtilsExport?.types !== expectedUtilsExport.types || - currentUtilsExport?.import !== expectedUtilsExport.import; - - if (needsExportPatch) { - pkg.exports = { - ...pkg.exports, - "./utils": expectedUtilsExport, - }; - writeFileSync(packageJsonPath, `${JSON.stringify(pkg, null, 2)}\n`); - } - - const currentJs = existsSync(utilsIndexJsPath) ? readFileSync(utilsIndexJsPath, "utf8") : null; - if (currentJs !== utilsIndexJs) { - writeFileSync(utilsIndexJsPath, utilsIndexJs); - } - - const currentDts = existsSync(utilsIndexDtsPath) ? readFileSync(utilsIndexDtsPath, "utf8") : null; - if (currentDts !== utilsIndexDts) { - writeFileSync(utilsIndexDtsPath, utilsIndexDts); - } - - if (needsExportPatch || currentJs !== utilsIndexJs || currentDts !== utilsIndexDts) { - patchedCount += 1; - } -} - -if (patchedCount > 0) { - console.log(`[patch-pierre-diffs-utils] patched ${patchedCount} @pierre/diffs installation(s).`); -} else if (locatedCount > 0) { - console.log("[patch-pierre-diffs-utils] @pierre/diffs already patched."); -} else { - console.log("[patch-pierre-diffs-utils] @pierre/diffs not installed; skipping."); -} diff --git a/scripts/patch-react-native-nitro-modules.mjs b/scripts/patch-react-native-nitro-modules.mjs deleted file mode 100644 index 17caedc8b8..0000000000 --- a/scripts/patch-react-native-nitro-modules.mjs +++ /dev/null @@ -1,73 +0,0 @@ -import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs"; -import { join } from "node:path"; - -const root = process.cwd(); - -const candidates = [join(root, "node_modules/react-native-nitro-modules/package.json")]; - -const bunStorePath = join(root, "node_modules/.bun"); - -if (existsSync(bunStorePath)) { - for (const entry of readdirSync(bunStorePath)) { - if (!entry.startsWith("react-native-nitro-modules@")) { - continue; - } - - candidates.push( - join(bunStorePath, entry, "node_modules/react-native-nitro-modules/package.json"), - ); - } -} - -let patchedCount = 0; -let locatedCount = 0; - -for (const filePath of candidates) { - if (!existsSync(filePath)) { - continue; - } - - locatedCount += 1; - - const source = readFileSync(filePath, "utf8"); - const pkg = JSON.parse(source); - - if (pkg.codegenConfig == null || typeof pkg.codegenConfig !== "object") { - throw new Error( - `Found react-native-nitro-modules package at ${filePath}, but codegenConfig was missing.`, - ); - } - - const iosConfig = - pkg.codegenConfig.ios != null && typeof pkg.codegenConfig.ios === "object" - ? pkg.codegenConfig.ios - : {}; - - const modulesProvider = - iosConfig.modulesProvider != null && typeof iosConfig.modulesProvider === "object" - ? iosConfig.modulesProvider - : {}; - - if (modulesProvider.NitroModules === "NativeNitroModules") { - continue; - } - - modulesProvider.NitroModules = "NativeNitroModules"; - iosConfig.modulesProvider = modulesProvider; - pkg.codegenConfig.ios = iosConfig; - - writeFileSync(filePath, `${JSON.stringify(pkg, null, 2)}\n`); - patchedCount += 1; -} - -if (patchedCount > 0) { - console.log( - `[patch-react-native-nitro-modules] patched ${patchedCount} react-native-nitro-modules installation(s).`, - ); -} else if (locatedCount > 0) { - console.log("[patch-react-native-nitro-modules] react-native-nitro-modules already patched."); -} else { - console.log( - "[patch-react-native-nitro-modules] react-native-nitro-modules not installed; skipping.", - ); -}