diff --git a/mobile/rpc-foundation/goldens/lifecycle-inventory-lifecycle.json b/mobile/rpc-foundation/goldens/lifecycle-inventory-lifecycle.json index 8784dc311689..d4adb3e24fd3 100644 --- a/mobile/rpc-foundation/goldens/lifecycle-inventory-lifecycle.json +++ b/mobile/rpc-foundation/goldens/lifecycle-inventory-lifecycle.json @@ -298,8 +298,8 @@ { "id": "inventory-lifecycle.unmount-before-1:settled", "observation": { - "sender": ["32c9018052ba", "2f1953cc0315"], - "payloads": ["8db0d1234c94", "c9b9d7a9b388"], + "sender": ["32c9018052ba"], + "payloads": ["8db0d1234c94"], "settlements": { "mount": "eb79a9b3682a", "old": "eb79a9b3682a", @@ -312,8 +312,8 @@ { "id": "inventory-lifecycle.unmount-before-1:remounted", "observation": { - "sender": ["32c9018052ba", "2f1953cc0315"], - "payloads": ["8db0d1234c94", "c9b9d7a9b388"], + "sender": ["32c9018052ba"], + "payloads": ["8db0d1234c94"], "settlements": { "mount": "eb79a9b3682a", "old": "eb79a9b3682a", diff --git a/mobile/src/session/mobile-file-search-owner-cleanup.test.tsx b/mobile/src/session/mobile-file-search-owner-cleanup.test.tsx new file mode 100644 index 000000000000..3cecdb9ac0ac --- /dev/null +++ b/mobile/src/session/mobile-file-search-owner-cleanup.test.tsx @@ -0,0 +1,280 @@ +import { createElement, StrictMode, type ReactNode } from 'react' +import { act, create } from 'react-test-renderer' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import type { RpcClient } from '../transport/rpc-client' +import { MobileNativeChatComposer } from './MobileNativeChatComposer' +import { useMobileNativeChatFileSearch } from './use-mobile-native-chat-file-search' + +vi.mock('react-native', async () => { + const React = await import('react') + return { + ActivityIndicator: 'ActivityIndicator', + Image: 'Image', + Text: 'Text', + TextInput: 'TextInput', + View: 'View', + Pressable: 'Pressable', + Keyboard: { dismiss: vi.fn() }, + ScrollView: ({ children, ...props }: { children?: ReactNode }) => + React.createElement('ScrollView', props, children), + StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1 } + } +}) +vi.mock('lucide-react-native', () => ({ + ArrowUp: 'ArrowUp', + Check: 'Check', + ChevronDown: 'ChevronDown', + ChevronLeft: 'ChevronLeft', + ChevronRight: 'ChevronRight', + ImagePlus: 'ImagePlus', + Mic: 'Mic', + Square: 'Square', + X: 'X' +})) +vi.mock('../components/BottomDrawer', async () => { + const React = await import('react') + return { + BottomDrawer: ({ visible, children }: { visible: boolean; children?: ReactNode }) => + visible ? React.createElement('BottomDrawer', { visible }, children) : null + } +}) + +type Reply = Awaited> +const missing: Reply = { + id: 'search', + ok: false, + error: { code: 'method_not_found', message: 'legacy host' }, + _meta: { runtimeId: 'legacy' } +} +const inventory: Reply = { + id: 'list', + ok: true, + result: { files: [{ relativePath: 'src/apple.ts' }] }, + _meta: { runtimeId: 'legacy' } +} +const searchCall = [ + 'files.searchPaths', + { + worktree: 'id:folder:remote', + query: 'apple', + limit: 16 + } +] +function pendingReply() { + let resolve: (reply: Reply) => void = () => { + throw new Error('uninitialized reply') + } + const promise = new Promise((settle) => { + resolve = settle + }) + return { promise, resolve } +} +function mount(sendRequest: RpcClient['sendRequest'], strict = false, getGeneration = () => 1) { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The actual hook only reads these two RPC members at the fake transport boundary. + const client = { sendRequest, getGeneration } as RpcClient + let search: ReturnType | undefined + function Route({ showChat }: { showChat: boolean }) { + search = useMobileNativeChatFileSearch({ client, worktreeId: 'folder:remote' }) + return showChat + ? createElement(MobileNativeChatComposer, { + value: '@apple', + onChangeText: vi.fn(), + onSend: async () => false, + sendSurfaceId: 'remote-chat', + getSendCompletionGeneration: () => 0, + getComposerEditGeneration: () => 0, + filePaths: search.nativeChatFilePaths, + onNeedFiles: search.loadNativeChatFiles + }) + : null + } + const element = (showChat: boolean) => + strict + ? createElement(StrictMode, null, createElement(Route, { showChat })) + : createElement(Route, { showChat }) + let renderer: ReturnType | undefined + act(() => { + renderer = create(element(false)) + }) + if (!renderer || !search) { + throw new Error('actual route hook did not mount') + } + const view = renderer + return { + query: () => + act(() => { + search?.loadNativeChatFiles('apple') + }), + showChat: () => + act(() => { + view.update(element(true)) + }), + triggerComposer: () => + act(() => { + view.root + .find((node) => typeof node.props.onSelectionChange === 'function') + .props.onSelectionChange({ nativeEvent: { selection: { end: 6 } } }) + }), + hideChat: () => + act(() => { + view.update(element(false)) + }), + paths: () => search?.nativeChatFilePaths, + dispose: () => + act(() => { + view.unmount() + }) + } +} +async function debounce(): Promise { + await act(async () => { + await vi.advanceTimersByTimeAsync(120) + }) +} +async function refuse(search: ReturnType): Promise { + await act(async () => { + search.resolve(missing) + await search.promise + }) +} +beforeEach(() => { + vi.useFakeTimers() +}) +afterEach(() => { + vi.clearAllTimers() + vi.useRealTimers() +}) + +it.each([false, true])( + 'a disposed actual composer owner admits no new inventory; StrictMode=%s', + async (strict) => { + const search = pendingReply() + const send = vi.fn((method) => + method === 'files.searchPaths' ? search.promise : Promise.resolve(inventory) + ) + const view = mount(send, strict) + view.showChat() + view.triggerComposer() + await debounce() + expect(send.mock.calls).toEqual([searchCall]) + view.dispose() + expect(vi.getTimerCount()).toBe(0) + await refuse(search) + expect(send.mock.calls.filter(([method]) => method === 'files.searchPaths')).toHaveLength(1) + expect(send.mock.calls.filter(([method]) => method === 'files.list')).toHaveLength(0) + } +) + +it.each([false, true])( + 'removing only the composer retains live fallback and cache; StrictMode=%s', + async (strict) => { + const search = pendingReply() + const send = vi.fn((method) => + method === 'files.searchPaths' ? search.promise : Promise.resolve(inventory) + ) + const view = mount(send, strict) + view.showChat() + view.triggerComposer() + await debounce() + expect(send.mock.calls).toEqual([searchCall]) + view.hideChat() + await refuse(search) + expect(send.mock.calls).toEqual([searchCall, ['files.list', { worktree: 'id:folder:remote' }]]) + expect(view.paths()).toEqual(['src/apple.ts']) + view.showChat() + view.triggerComposer() + await debounce() + expect(view.paths()).toEqual(['src/apple.ts']) + expect(send).toHaveBeenCalledTimes(2) + view.dispose() + } +) + +it('64 retired actual hooks do not start 64 whole-workspace reads', async () => { + const pending = Array.from({ length: 64 }, pendingReply) + let index = 0 + const send = vi.fn((method) => + method === 'files.searchPaths' ? pending[index++]!.promise : Promise.resolve(inventory) + ) + for (let owner = 0; owner < pending.length; owner++) { + const view = mount(send) + view.query() + await debounce() + view.dispose() + } + expect(send.mock.calls).toEqual(pending.map(() => searchCall)) + expect(vi.getTimerCount()).toBe(0) + await act(async () => { + pending.forEach((reply) => reply.resolve(missing)) + await Promise.all(pending.map((reply) => reply.promise)) + }) + expect(send.mock.calls.filter(([method]) => method === 'files.list')).toHaveLength(0) +}) + +it.each([false, true])( + 'a same-client successor owns its live fallback; StrictMode=%s', + async (strict) => { + const retiredSearch = pendingReply() + let searches = 0 + const send = vi.fn((method) => + method === 'files.searchPaths' + ? ++searches === 1 + ? retiredSearch.promise + : Promise.resolve(missing) + : Promise.resolve(inventory) + ) + const retired = mount(send, strict) + retired.query() + await debounce() + retired.dispose() + const successor = mount(send, strict) + successor.query() + await debounce() + expect(successor.paths()).toEqual(['src/apple.ts']) + expect(send.mock.calls).toEqual([ + searchCall, + searchCall, + ['files.list', { worktree: 'id:folder:remote' }] + ]) + await refuse(retiredSearch) + expect(successor.paths()).toEqual(['src/apple.ts']) + expect(send.mock.calls.filter(([method]) => method === 'files.list')).toHaveLength(1) + successor.dispose() + } +) + +it('reentrant disposal after fallback entry preserves the admitted inventory', async () => { + const search = pendingReply() + let disposal: (() => void) | undefined + const send = vi.fn((method) => + method === 'files.searchPaths' ? search.promise : Promise.resolve(inventory) + ) + const view = mount(send, false, () => { + disposal?.() + return 1 + }) + view.query() + await debounce() + expect(send.mock.calls).toEqual([searchCall]) + disposal = view.dispose + await refuse(search) + expect(send.mock.calls).toEqual([searchCall, ['files.list', { worktree: 'id:folder:remote' }]]) +}) + +it('already admitted inventory still settles after full owner disposal', async () => { + const list = pendingReply() + const send = vi.fn((method) => + method === 'files.searchPaths' ? Promise.resolve(missing) : list.promise + ) + const view = mount(send) + view.query() + await debounce() + expect(send.mock.calls).toEqual([searchCall, ['files.list', { worktree: 'id:folder:remote' }]]) + view.dispose() + await act(async () => { + list.resolve(inventory) + await list.promise + }) + expect(send.mock.calls).toEqual([searchCall, ['files.list', { worktree: 'id:folder:remote' }]]) + expect(vi.getTimerCount()).toBe(0) +}) diff --git a/mobile/src/session/use-mobile-native-chat-file-search.ts b/mobile/src/session/use-mobile-native-chat-file-search.ts index a71ad83829d7..8fe58a8ccd60 100644 --- a/mobile/src/session/use-mobile-native-chat-file-search.ts +++ b/mobile/src/session/use-mobile-native-chat-file-search.ts @@ -34,6 +34,14 @@ export function useMobileNativeChatFileSearch(args: { new GenerationScopedRequestOwner() ).current + const mountedRef = useRef(true) + useEffect(() => { + mountedRef.current = true + return () => { + mountedRef.current = false + } + }, []) + useEffect(() => { sequenceRef.current++ queryCacheRef.current.clear() @@ -90,6 +98,9 @@ export function useMobileNativeChatFileSearch(args: { setNativeChatFilePaths(paths) } const loadLegacyPaths = async (): Promise => { + if (!mountedRef.current) { + return + } // What retires the inventory: this host, this workspace, this logical authority. A // reconnect to the same host leaves the files on disk alone, so the physical session // epoch is deliberately not in it. Read once, so a cutover between the two calls below diff --git a/mobile/src/test-support/rpc-recording/derived-goldens.ts b/mobile/src/test-support/rpc-recording/derived-goldens.ts index 67ffa4a7e13c..940b04e06456 100644 --- a/mobile/src/test-support/rpc-recording/derived-goldens.ts +++ b/mobile/src/test-support/rpc-recording/derived-goldens.ts @@ -53,6 +53,24 @@ function baseScenario(manifest: readonly RecordingScenario[], id: string): Recor return found } +function omitRetiredInventoryAdmission(scenario: RecordingScenario): RecordingScenario { + if (scenario.id !== 'inventory-lifecycle.unmount-before-1') { + return scenario + } + // A late search refusal cannot start an inventory after this owner's unmount. + return { + ...scenario, + steps: scenario.steps.filter( + (step) => + !( + ('bind' in step && + (step.bind === 'old-inventory' || step.bind === 'lifecycle-old-inventory')) || + ('complete' in step && step.complete === 'lifecycle-old-inventory') + ) + ) + } +} + /** The manifest scenario a pilot golden expands from, which its suite also mounts and mutates. */ export type PilotGolden = DerivedGolden & { scenario: RecordingScenario } @@ -144,7 +162,7 @@ export function familyGoldens(manifest: readonly RecordingScenario[]): DerivedGo actions .flatMap((action) => lifecycleSchedules(base, action)) .filter(({ scenario }) => !id.includes('hydration') || !scenario.id.endsWith('-1')) - ) + ).map(omitRetiredInventoryAdmission) }) } return goldens diff --git a/mobile/src/test-support/rpc-recording/inventory-lifecycle-derivation.test.ts b/mobile/src/test-support/rpc-recording/inventory-lifecycle-derivation.test.ts new file mode 100644 index 000000000000..9cf6c5947bce --- /dev/null +++ b/mobile/src/test-support/rpc-recording/inventory-lifecycle-derivation.test.ts @@ -0,0 +1,64 @@ +import { resolve } from 'node:path' +import { expect, it } from 'vitest' +import { familyGoldens } from './derived-goldens' +import { hoistPreludeCheckpoints } from './prelude-checkpoints' +import { readScenarios } from './scenario-input' +import { bindCompletions, lifecycleSchedules } from './schedule-driver' + +it('omits only the inventory admission following a refusal to a fully unmounted owner', () => { + const manifest = readScenarios( + resolve(import.meta.dirname, '../../../rpc-foundation/pilot-scenarios.json') + ) + const base = manifest.scenarios.find((scenario) => scenario.id === 'inventory-lifecycle') + if (!base) { + throw new Error('missing inventory base scenario') + } + const golden = familyGoldens(manifest.scenarios).find( + (item) => item.id === 'lifecycle-inventory-lifecycle' + ) + if (!golden) { + throw new Error('missing inventory lifecycle golden') + } + const original = hoistPreludeCheckpoints( + { ...base, steps: bindCompletions(base.steps) }, + (['reset', 'unmount', 'blur'] as const).flatMap((action) => lifecycleSchedules(base, action)) + ) + const derived = golden.scenarios() + expect(derived.map((scenario) => scenario.id)).toEqual(original.map((scenario) => scenario.id)) + expect(derived).toHaveLength(12) + for (const [index, scenario] of original.entries()) { + if (scenario.id !== 'inventory-lifecycle.unmount-before-1') { + expect(derived[index]).toEqual(scenario) + expect(JSON.stringify(derived[index])).toBe(JSON.stringify(scenario)) + continue + } + expect(scenario.steps).toHaveLength(13) + expect(scenario.steps.slice(7, 10)).toEqual([ + { bind: 'old-inventory', request: 'files.list#1', params: { worktree: 'id:A' } }, + { bind: 'lifecycle-old-inventory', request: 'old-inventory', params: { worktree: 'id:A' } }, + { + complete: 'lifecycle-old-inventory', + params: { worktree: 'id:A' }, + reply: { ok: true, result: { files: [{ relativePath: 'old.ts' }] } } + } + ]) + const expected = { + ...scenario, + steps: [...scenario.steps.slice(0, 7), ...scenario.steps.slice(10)] + } + expect(derived[index]).toEqual(expected) + expect(JSON.stringify(derived[index])).toBe(JSON.stringify(expected)) + expect(expected.steps.filter((step) => 'checkpoint' in step)).toEqual([ + { checkpoint: 'lifecycle-boundary' }, + { checkpoint: 'settled' }, + { checkpoint: 'remounted' } + ]) + expect(expected.steps.filter((step) => 'bind' in step)).toEqual([ + { + bind: 'lifecycle-files.searchPaths#1', + request: 'files.searchPaths#1', + params: { worktree: 'id:A', query: 'old', limit: 16 } + } + ]) + } +})