Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
test(mobile): 通过真实 React hook 验证新建草稿恢复
Dash6484ad929acb
diff --cc apps/mobile/app/sessions/new.tsxindex 7e712d15c8,ec19ed5f79..7bb6b53b82--- a/apps/mobile/app/sessions/new.tsx+++ b/apps/mobile/app/sessions/new.tsx@@@ -111,6 -111,6 +111,7 @@@ importimport { useAuth } from '@/auth/AuthContext';import { discardMobileUploadedAttachment } from '@/session/mobileAttachmentUpload';import { discardNewSessionUploadedAttachments } from '@/session/newSessionAttachmentCleanup';++import { useAutoResumeNewSessionDraft, useNewSessionDurableEdit } from '@/session/useNewSessionDraftRecovery';import { goBackGuarded } from '@/utils/backGuard';import { buildMobileImageAttachmentCandidate } from '@/session/mobileImageAttachment';import { useMobileLocalAttachments } from '@/session/useMobileLocalAttachments';@@@ -244,9 -244,8 +245,7 @@@ importimport { useTranslation } from 'react-i18next';import {createNewSessionId,-- completeNewSessionDurableEdit,drainStashedNewSessionDraft,- findNewSessionEditDraft,hasLiveNewSessionCreation,holdNewSessionCreationDraft,startNewSessionCreation,@@@ -856,36 -851,34 +855,22 @@@ export default function NewRemoteSessiorouter.replace('/devices');return true;}, [router]);-- useEffect(() => {-- const owner = outboxOwner;-- if (leaveForeignOutboxRecovery()) return;-- const sid = String(params.recoverySessionId ?? '');-- if (!sid) return;-- let active = true;-- let restored = false;-- let releaseEditClaim: (() => void) | undefined;-- const restore = () => {-- if (!active || restored || !isMobileAuthOwnerCurrent(owner)) return;-- const record = getCurrentMobileOutboxRecords().find((r) => r.item.sessionId === sid && r.creation-- && r.accountId === owner.accountKey && r.deviceId === routeDeviceId);-- if (!record?.creation || record.prepared) return;-- restored = true;++ useNewSessionDurableEdit({++ sessionId: String(params.recoverySessionId ?? ''), deviceId: routeDeviceId, owner: outboxOwner,++ leaveForeignRecovery: leaveForeignOutboxRecovery,++ onRestore: record => {outboxRecoveryRef.current = record;userTouchedDeviceRef.current = true;restoreCreationDraft(record.creation.draft,record.item.attachmentSlots.filter((a): a is RemoteSerializedAttachment => a !== null),{ enabled: record.creation.planModeArm, restorePermissionMode: record.creation.restorePermissionMode },record.deviceId);+ if (record.creation.notice) setAttachmentError(record.creation.notice);+ if (record.error) setError(t('session.screen.createFailedNotice', { message: record.error }));setSelectedDeviceId(record.deviceId);setSelectedDeviceName(record.creation.deviceName);-- releaseEditClaim = completeNewSessionDurableEdit(sid, record.deviceId);-- };-- const unsubscribe = mobileDurableOutbox.subscribe(restore);-- void mobileDurableOutbox.ready().then(restore);-- return () => { active = false; unsubscribe(); releaseEditClaim?.(); };- }, [params.recoverySessionId, routeDeviceId, outboxOwner, leaveForeignOutboxRecovery, restoreCreationDraft, t]);- }, [params.recoverySessionId, routeDeviceId, outboxOwner, leaveForeignOutboxRecovery, restoreCreationDraft]);++ },++ });useEffect(() => {const stashed = drainStashedNewSessionDraft(readRouteString(params.editSessionId) ?? undefined, routeDeviceId);if (!stashed) return;@@@ -961,29 -953,7 +946,19 @@@setAttachmentError(null);}), [auth.getAccessToken, discardAllPendingUploads]);const incomingShareBatch = useIncomingShareBatch();+ const incomingShareReceivedRef = useRef(false);+ if (incomingShareBatch) incomingShareReceivedRef.current = true;const isShareTargetFocused = useIsFocused();- useEffect(() => {- if (params.recoverySessionId || params.editSessionId || params.draft || params.suggestion- || visualInitialDraft || !newSessionPreferencesLoaded || !selectedDeviceId) return;- const owner = outboxOwner;- let active = true;- const resume = () => {- if (!active || !isMobileAuthOwnerCurrent(owner) || outboxRecoveryRef.current++ useAutoResumeNewSessionDraft({++ enabled: !(params.recoverySessionId || params.editSessionId || params.draft || params.suggestion++ || visualInitialDraft || !newSessionPreferencesLoaded),++ deviceId: selectedDeviceId, workingDir: initialWorkingDir, owner: outboxOwner,++ hasInput: () => !!(outboxRecoveryRef.current+ || firstMessageRef.current || attachmentsRef.current.length || hasAttachmentInput()+ || incomingShareReceivedRef.current- || userTouchedRuntimeRef.current || userTouchedWorkspaceRef.current) return;- const saved = findNewSessionEditDraft(selectedDeviceId, initialWorkingDir);- if (!saved) return;- active = false;- router.setParams({ recoverySessionId: saved.item.sessionId, deviceId: saved.deviceId });- };- const unsubscribe = mobileDurableOutbox.subscribe(resume);- void mobileDurableOutbox.ready().then(resume);- return () => { active = false; unsubscribe(); };- }, [params.recoverySessionId, params.editSessionId, params.draft, params.suggestion, visualInitialDraft,- newSessionPreferencesLoaded, selectedDeviceId, initialWorkingDir, outboxOwner, router, hasAttachmentInput]);++ || userTouchedRuntimeRef.current || userTouchedWorkspaceRef.current),++ onResume: next => router.setParams(next),++ });useEffect(() => {if (!isShareTargetFocused || !auth.isAuthenticated || !incomingShareBatch|| getMobileAuthOwner().accountId !== auth.user?.id) return;diff --cc apps/mobile/src/__tests__/newSessionCreation.test.tsindex 219eabbe38,bcebea61b1..daf7876281--- a/apps/mobile/src/__tests__/newSessionCreation.test.ts+++ b/apps/mobile/src/__tests__/newSessionCreation.test.ts@@@ -27,7 -26,7 +27,7 @@@ vi.mock('@/session/mobileDurableOutbox'isDurableOutboxCreationHeld: () => false,mobileDurableOutbox: { update: editOutbox.update, subscribe: () => () => {} },}));--import { getMobileAuthOwner, isMobileAuthOwnerCurrent, setMobileAuthOwner } from '@/auth/authOwnerGeneration';++import { getMobileAuthOwner, setMobileAuthOwner } from '@/auth/authOwnerGeneration';import { returnNewSessionToEdit } from '@/session/returnNewSessionToEdit';const recoveryAsyncStorage = vi.hoisted(() => ({getItem: vi.fn(async (key: string) => recoveryStorage.get(key) ?? null),@@@ -208,83 -204,7 +208,43 @@@ async function flushPipeline(): Promise}}- // Reuse the existing native-page effect harness for both explicit recovery and- // blank-form resume; execute production callbacks, never duplicate their guards.- const recoveryPage = ts.createSourceFile('new.tsx', readFileSync(resolve(process.cwd(), 'app/sessions/new.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);- function runRecoveryEffect(marker: string, bindings: Record<string, unknown>): (() => void) | undefined {- let effect = '';- function visit(node: ts.Node) {- if (ts.isCallExpression(node) && node.expression.getText(recoveryPage) === 'useEffect'- && node.arguments[0]?.getText(recoveryPage).includes(marker)) effect = node.arguments[0].getText(recoveryPage);- ts.forEachChild(node, visit);- }- visit(recoveryPage);- if (!effect) throw new Error('Missing production creation recovery effect');- const compiled = ts.transpileModule(`function run(bindings) { const { ${Object.keys(bindings).join(', ')} } = bindings; return (${effect})(); }`,- { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;- return new Function(`${compiled}; return run;`)()(bindings);- }-describe('newSessionCreation pipeline', () => {- it.each(['blank', 'upload', 'paste', 'received-share', 'input-before-ready'])('blank form recovery respects active input: %s', async scenario => {- const original = recoveryOutboxRecord('s1');- editOutbox.records.mockReturnValue([{ ...original, accountId: getMobileAuthOwner().accountKey,- suspended: true, creation: { ...original.creation!, editReady: true } }]);- let pendingInput = scenario === 'upload' || scenario === 'paste';- let ready!: () => void;- const router = { setParams: vi.fn() };- const cleanup = runRecoveryEffect('findNewSessionEditDraft(', {- params: {}, visualInitialDraft: null, newSessionPreferencesLoaded: true, selectedDeviceId: 'dev-1',- outboxOwner: getMobileAuthOwner(), isMobileAuthOwnerCurrent, outboxRecoveryRef: { current: null },- firstMessageRef: { current: '' }, attachmentsRef: { current: [] },- userTouchedRuntimeRef: { current: false }, userTouchedWorkspaceRef: { current: false },- hasAttachmentInput: () => pendingInput, incomingShareReceivedRef: { current: scenario === 'received-share' },- findNewSessionEditDraft, initialWorkingDir: null, router,- mobileDurableOutbox: { subscribe: () => () => {}, ready: () => new Promise<void>(resolve => { ready = resolve; }) },- });- if (scenario === 'input-before-ready') pendingInput = true;- ready();- await flushPipeline();- expect(router.setParams).toHaveBeenCalledTimes(scenario === 'blank' ? 1 : 0);- cleanup?.();- });-+ it('carries unsent composer text and files through legacy memory recovery', async () => {+ const maker = makeMaker({ createSession: vi.fn(async () => { throw new Error('[MODEL_UNAVAILABLE] unavailable'); }) });+ startNewSessionCreation(makeParams('s1', maker));+ await flushPipeline();+ await returnNewSessionToEdit({ sessionId: 's1', deviceId: 'dev-1', isCurrent: () => true, onReady: vi.fn() });+ const file = { id: 'new-file', path: 'oss://new-file', category: 'image', name: 'new.png', ext: 'png', size: 1 } as RemoteSerializedAttachment;+ await appendNewSessionEditComposer('s1', 'dev-1', { text: 'unsent addition', attachments: [file], notice: 'one pending upload' });+ const restored = drainStashedNewSessionDraft('s1', 'dev-1')!;+ expect(restored.draft.firstMessage).toBe(`${DRAFT.firstMessage}\n\nunsent addition`);+ expect(restored.attachments).toEqual([file]);+ expect(restored.notice).toBe('one pending upload');+ });+ it.each([false, true])('deletes a failed local task only after worktree cleanup (cleanup fails: %s)', async fails => {+ const maker = makeMaker();+ startNewSessionCreation(makeParams('s1', maker, {+ draft: { ...DRAFT, workingDir: '/repo/.cindy-worktrees/a' },+ precreatedWorktree: { path: '/repo/.cindy-worktrees/a', recoveryKey: 'cleanup-a', originalWorkingDir: '/repo' },+ confirmUnauthenticated: async () => ({ unauthenticated: true, fresh: null }),+ }));+ await flushPipeline();+ if (fails) maker.worktree.discardPrecreated.mockRejectedValueOnce(new Error('cleanup refused'));+ const remove = vi.fn();+ const removal = withNewSessionCreationRemoval('s1', 'dev-1', 'deleted', remove);+ if (fails) {+ await expect(removal).rejects.toThrow('cleanup refused');+ expect(getNewSessionCreationTask('s1')).toMatchObject({ status: 'create-failed', returningToEdit: false });+ expect(remoteSessionStore.getSessions().some(row => row.id === 's1')).toBe(true);+ } else {+ await removal;+ expect(getNewSessionCreationTask('s1')).toBeNull();+ expect(remoteSessionStore.getSessions()).toEqual([]);+ }+ expect(maker.worktree.discardPrecreated).toHaveBeenCalledOnce();+ expect(remove).not.toHaveBeenCalled();+ });+beforeEach(async () => {persistCancelledDraft.mockReset();editOutbox.records.mockReset().mockReturnValue([]);@@@ -648,54 -637,58 +608,6 @@@expect(record.item.text).toBe(DRAFT.firstMessage);});- it.each(['matching', 'matching-no-error', 'device', 'account', 'not-ready', 'switched-owner'])('only acknowledges durable edit recovery after the matching form restores it: %s', async scope => {- it.each(['matching', 'device', 'account', 'not-ready', 'switched-owner'])('only acknowledges durable edit recovery after the matching form restores it: %s', async scope => {-- const maker = makeMaker({ createSession: vi.fn(async () => { throw new Error('[MODEL_UNAVAILABLE] unavailable'); }) });-- startNewSessionCreation(makeParams('s1', maker));-- await flushPipeline();-- const record = { ...recoveryOutboxRecord('s1'), accountId: getMobileAuthOwner().accountKey };-- editOutbox.records.mockReturnValue([record]);-- await returnNewSessionToEdit({ sessionId: 's1', deviceId: 'dev-1', isCurrent: () => true, onReady: vi.fn() });-- const owner = getMobileAuthOwner();- record.error = scope === 'matching-no-error' ? undefined : 'saved creation failure';- const matching = scope === 'matching' || scope === 'matching-no-error';-- // Model the persisted edit-ready patch so the real form acquires a releaseable claim.-- record.suspended = true;-- record.creation!.editReady = true;-- if (scope === 'account') record.accountId = 'foreign-owner';-- if (scope === 'not-ready') editOutbox.records.mockReturnValue([]);-- if (scope === 'switched-owner') setMobileAuthOwner('owner-b');-- // Execute the real form effect, including readiness and ownership guards.- const page = ts.createSourceFile('new.tsx', readFileSync(resolve(process.cwd(), 'app/sessions/new.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);- let effect = '';- function findEffect(node: ts.Node) {- if (ts.isCallExpression(node) && node.expression.getText(page) === 'useEffect'- && node.arguments[0]?.getText(page).includes('completeNewSessionDurableEdit(')) effect = node.arguments[0].getText(page);- ts.forEachChild(node, findEffect);- }- findEffect(page);- if (!effect) throw new Error('Missing production creation recovery effect');-- const restore = vi.fn(() => expect(getNewSessionCreationTask('s1')?.readyForEdit).toBe('durable'));-- const bindings = {-- outboxOwner: owner, params: { recoverySessionId: 's1' }, routeDeviceId: scope === 'device' ? 'dev-2' : 'dev-1',-- leaveForeignOutboxRecovery: () => false, isMobileAuthOwnerCurrent,-- getCurrentMobileOutboxRecords: editOutbox.records, outboxRecoveryRef: { current: null },-- userTouchedDeviceRef: { current: false }, restoreCreationDraft: restore,-- setSelectedDeviceId: vi.fn(), setSelectedDeviceName: vi.fn(), completeNewSessionDurableEdit,- setError: vi.fn(), t: (_key: string, values: { message: string }) => `创建失败:${values.message}`,-- mobileDurableOutbox: { subscribe: () => () => {}, ready: async () => {} },-- };- const cleanup = runRecoveryEffect('completeNewSessionDurableEdit(', bindings)!;- const compiled = ts.transpileModule(`function run(bindings) { const { ${Object.keys(bindings).join(', ')} } = bindings; return (${effect})(); }`,- { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;- const cleanup = (new Function(`${compiled}; return run;`)() as (b: typeof bindings) => () => void)(bindings);-- await flushPipeline();- if (matching) {- if (scope === 'matching') {-- expect(restore).toHaveBeenCalledWith(DRAFT, [], { enabled: false, restorePermissionMode: null }, 'dev-1');-- expect(getNewSessionCreationTask('s1')).toBeNull();-- } else {-- expect(restore).not.toHaveBeenCalled();-- if (scope === 'switched-owner') expect(getNewSessionCreationTask('s1')).toBeNull();-- else expect(getNewSessionCreationTask('s1')?.readyForEdit).toBe('durable');-- }- // Cold/blank-form recovery has no creationError route parameter. Restore- // the saved reason only with its matching draft; old records keep any live error.- if (scope === 'matching') expect(bindings.setError).toHaveBeenCalledWith('创建失败:saved creation failure');- else expect(bindings.setError).not.toHaveBeenCalled();-- cleanup();- if (matching) {- if (scope === 'matching') {-- expect(getNewSessionCreationTask('s1')?.readyForEdit).toBe('durable');- expect(remoteSessionStore.getSessions()).toEqual([]);- expect(remoteSessionStore.getSessions().some(row => row.id === 's1')).toBe(true);-- }-- });--it.each([false, true])('isolates a late background edit draft from another task (other form already claimed: %s)', async claimed => {let finishCleanup!: (value: { discarded: boolean }) => void;const makerA = makeMaker({ worktree: { discardPrecreated: vi.fn(() => new Promise(resolve => { finishCleanup = resolve; })) } });diff --cc apps/mobile/src/__tests__/useNewSessionDraftRecovery.test.tsxindex 0000000000,0000000000..de2f02edadnew file mode 100644--- /dev/null+++ b/apps/mobile/src/__tests__/useNewSessionDraftRecovery.test.tsx@@@ -1,0 -1,0 +1,169 @@@++// @vitest-environment jsdom++import { act, useState } from 'react';++import { createRoot, type Root } from 'react-dom/client';++import { afterEach, beforeEach, expect, it, vi } from 'vitest';++import { getMobileAuthOwner, setMobileAuthOwner } from '@/auth/authOwnerGeneration';++import type { DurableOutboxRecord } from '@/session/durableOutbox';++import { useAutoResumeNewSessionDraft, useNewSessionDurableEdit } from '@/session/useNewSessionDraftRecovery';++++const outbox = vi.hoisted(() => ({++ records: [] as DurableOutboxRecord[], listeners: new Set<() => void>(),++ ready: vi.fn(), claim: vi.fn(), release: vi.fn(), find: vi.fn(),++}));++vi.mock('@/session/mobileDurableOutbox', () => ({++ getCurrentMobileOutboxRecords: () => outbox.records,++ mobileDurableOutbox: {++ ready: outbox.ready,++ subscribe: (listener: () => void) => {++ outbox.listeners.add(listener);++ return () => outbox.listeners.delete(listener);++ },++ },++}));++vi.mock('@/session/newSessionCreation', () => ({++ completeNewSessionDurableEdit: outbox.claim,++ findNewSessionEditDraft: outbox.find,++}));++type EditProps = Omit<Parameters<typeof useNewSessionDurableEdit>[0], 'onRestore'>;++type ResumeProps = Omit<Parameters<typeof useAutoResumeNewSessionDraft>[0], 'onResume'>;++function Editor(props: EditProps) {++ const [record, setRecord] = useState<DurableOutboxRecord>();++ const [text, setText] = useState('');++ useNewSessionDurableEdit({ ...props, onRestore: saved => {++ setRecord(saved); setText(saved.creation.draft.firstMessage);++ } });++ return <><span>{text}</span><span>{record?.error}</span>++ <button onClick={() => setText('New input')}>Edit</button></>;++}++function BlankForm(props: ResumeProps) {++ const [route, setRoute] = useState('');++ useAutoResumeNewSessionDraft({ ...props, onResume: params => setRoute(`${params.deviceId}/${params.recoverySessionId}`) });++ return <span>{route}</span>;++}++let root: Root;++let container: HTMLDivElement;++let edit: EditProps;++let resume: ResumeProps;++let ready: () => void;++let hasInput: boolean;++const actEnvironment = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };++let previousActEnvironment: boolean | undefined;++const renderEdit = () => act(async () => root.render(<Editor {...edit} />));++const renderBlank = () => act(async () => root.render(<BlankForm {...resume} />));++const notify = () => act(async () => { for (const listener of outbox.listeners) listener(); });++beforeEach(() => {++ previousActEnvironment = actEnvironment.IS_REACT_ACT_ENVIRONMENT;++ actEnvironment.IS_REACT_ACT_ENVIRONMENT = true;++ setMobileAuthOwner('account');++ const owner = getMobileAuthOwner();++ outbox.listeners.clear();++ outbox.release.mockReset();++ outbox.claim.mockReset().mockReturnValue(outbox.release);++ outbox.ready.mockReset().mockReturnValue(new Promise<void>(resolve => { ready = resolve; }));++ outbox.records = [{++ version: 1, accountId: owner.accountKey, deviceId: 'device', state: 'failed', createdAt: 1,++ uploads: [], error: 'Model unavailable',++ item: { sessionId: 'task', clientId: 'first', text: 'Saved draft', attachmentSlots: [],++ quotesEncoded: false, agentReferences: [], pastedTextRanges: [], slashCommandRanges: [],++ permissionModeAtSend: 'auto', slotMeta: [], slotByLocalId: {}, waitingIds: [],++ failedIds: [], enqueueError: null, phase: 'failed' },++ creation: { deviceName: 'PC', planModeArm: false, restorePermissionMode: null,++ draft: { agentKind: 'codex', workspaceKind: 'dialogue', model: 'model', effort: 'medium',++ permissionMode: 'auto', workingDir: '', providerId: 'openai', fastMode: false, firstMessage: 'Saved draft' } },++ }];++ outbox.find.mockReset().mockImplementation(() => outbox.records[0]);++ edit = { sessionId: 'task', deviceId: 'device', owner, leaveForeignRecovery: () => false };++ hasInput = false;++ resume = { enabled: true, deviceId: 'device', workingDir: '/repo', owner, hasInput: () => hasInput };++ container = document.createElement('div');++ document.body.append(container);++ root = createRoot(container);++});++afterEach(() => {++ act(() => root.unmount());++ container.remove();++ setMobileAuthOwner(null);++ actEnvironment.IS_REACT_ACT_ENVIRONMENT = previousActEnvironment;++});++++it('restores text and the saved failure once, preserving edits across renders and notifications', async () => {++ await renderEdit();++ expect(container.textContent).toBe('Edit');++ await act(async () => ready());++ expect(container.textContent).toBe('Saved draftModel unavailableEdit');++ expect(outbox.claim).toHaveBeenCalledExactlyOnceWith('task', 'device');++ act(() => container.querySelector('button')!.click());++ await renderEdit();++ await notify();++ expect(container.textContent).toBe('New inputModel unavailableEdit');++ expect(outbox.claim).toHaveBeenCalledOnce();++ expect(outbox.release).not.toHaveBeenCalled();++ await act(async () => root.render(null));++ expect(outbox.release).toHaveBeenCalledOnce();++ expect(outbox.listeners.size).toBe(0);++});++++it.each(['account', 'device', 'prepared', 'foreign-route', 'unmount', 'owner-switch'] as const)(++ 'ignores ineligible or late durable recovery: %s', async change => {++ if (change === 'account') outbox.records[0].accountId = 'other';++ if (change === 'device') outbox.records[0].deviceId = 'other';++ if (change === 'prepared') outbox.records[0].prepared = {} as NonNullable<DurableOutboxRecord['prepared']>;++ if (change === 'foreign-route') edit.leaveForeignRecovery = () => true;++ await renderEdit();++ if (change === 'unmount') await act(async () => root.render(null));++ if (change === 'owner-switch') setMobileAuthOwner('other');++ await act(async () => ready());++ await notify();++ expect(outbox.claim).not.toHaveBeenCalled();++ expect(container.textContent).not.toContain('Saved draft');++ },++);++++it('releases the old claim when the route changes and waits for the matching record', async () => {++ await renderEdit();++ await act(async () => ready());++ edit = { ...edit, sessionId: 'next' };++ await renderEdit();++ expect(outbox.release).toHaveBeenCalledOnce();++ outbox.records[0] = { ...outbox.records[0], item: { ...outbox.records[0].item, sessionId: 'next' } };++ await notify();++ expect(outbox.claim).toHaveBeenLastCalledWith('next', 'device');++ expect(outbox.claim).toHaveBeenCalledTimes(2);++});++++it('resumes one draft in the selected device and project, without repeating on render or notification', async () => {++ await renderBlank();++ await act(async () => ready());++ expect(container.textContent).toBe('device/task');++ expect(outbox.find).toHaveBeenCalledExactlyOnceWith('device', '/repo');++ await renderBlank();++ await notify();++ expect(outbox.find).toHaveBeenCalledOnce();++});++++it.each(['disabled', 'input', 'late-input', 'unmount', 'owner-switch'] as const)(++ 'does not resume over a protected or stale form: %s', async change => {++ if (change === 'disabled') resume.enabled = false;++ if (change === 'input') hasInput = true;++ await renderBlank();++ if (change === 'late-input') { hasInput = true; await renderBlank(); }++ if (change === 'unmount') await act(async () => root.render(null));++ if (change === 'owner-switch') setMobileAuthOwner('other');++ await act(async () => ready());++ await notify();++ expect(outbox.find).not.toHaveBeenCalled();++ expect(container.textContent).toBe('');++ },++);++++it('uses the latest device after a route change while storage is pending', async () => {++ await renderBlank();++ resume = { ...resume, deviceId: 'other-device' };++ outbox.records[0].deviceId = 'other-device';++ await renderBlank();++ await act(async () => ready());++ expect(outbox.find).toHaveBeenCalledExactlyOnceWith('other-device', '/repo');++ expect(container.textContent).toBe('other-device/task');++ await act(async () => root.render(null));++ expect(outbox.listeners.size).toBe(0);++});diff --cc apps/mobile/src/session/useNewSessionDraftRecovery.tsindex 0000000000,0000000000..0faeb618f8new file mode 100644--- /dev/null+++ b/apps/mobile/src/session/useNewSessionDraftRecovery.ts@@@ -1,0 -1,0 +1,64 @@@++import { useEffect, useRef } from 'react';++import { isMobileAuthOwnerCurrent, type MobileAuthOwnerGeneration } from '@/auth/authOwnerGeneration';++import type { DurableOutboxRecord } from './durableOutbox';++import { getCurrentMobileOutboxRecords, mobileDurableOutbox } from './mobileDurableOutbox';++import { completeNewSessionDurableEdit, findNewSessionEditDraft } from './newSessionCreation';++++type CreationRecord = DurableOutboxRecord & { creation: NonNullable<DurableOutboxRecord['creation']> };++++/** The form owns one edit claim until its recovery route changes or unmounts. */++export function useNewSessionDurableEdit({ sessionId, deviceId, owner, leaveForeignRecovery, onRestore }: {++ sessionId: string;++ deviceId: string;++ owner: MobileAuthOwnerGeneration;++ leaveForeignRecovery: () => boolean;++ onRestore: (record: CreationRecord) => void;++}) {++ const callbacks = useRef({ leaveForeignRecovery, onRestore });++ callbacks.current = { leaveForeignRecovery, onRestore };++ useEffect(() => {++ if (callbacks.current.leaveForeignRecovery() || !sessionId) return;++ let active = true;++ let restored = false;++ let releaseEditClaim: (() => void) | undefined;++ const restore = () => {++ if (!active || restored || !isMobileAuthOwnerCurrent(owner)) return;++ const record = getCurrentMobileOutboxRecords().find(r => r.item.sessionId === sessionId && r.creation++ && r.accountId === owner.accountKey && r.deviceId === deviceId);++ if (!record?.creation || record.prepared) return;++ restored = true;++ callbacks.current.onRestore(record as CreationRecord);++ releaseEditClaim = completeNewSessionDurableEdit(sessionId, record.deviceId);++ };++ const unsubscribe = mobileDurableOutbox.subscribe(restore);++ void mobileDurableOutbox.ready().then(restore);++ return () => { active = false; unsubscribe(); releaseEditClaim?.(); };++ }, [sessionId, deviceId, owner]);++}++++/** Resume only while this form is still blank when asynchronous storage becomes ready. */++export function useAutoResumeNewSessionDraft({ enabled, deviceId, workingDir, owner, hasInput, onResume }: {++ enabled: boolean;++ deviceId: string;++ workingDir: string | null;++ owner: MobileAuthOwnerGeneration;++ hasInput: () => boolean;++ onResume: (params: { recoverySessionId: string; deviceId: string }) => void;++}) {++ const callbacks = useRef({ hasInput, onResume });++ callbacks.current = { hasInput, onResume };++ useEffect(() => {++ if (!enabled || !deviceId) return;++ let active = true;++ const resume = () => {++ if (!active || !isMobileAuthOwnerCurrent(owner) || callbacks.current.hasInput()) return;++ const saved = findNewSessionEditDraft(deviceId, workingDir);++ if (!saved) return;++ active = false;++ callbacks.current.onResume({ recoverySessionId: saved.item.sessionId, deviceId: saved.deviceId });++ };++ const unsubscribe = mobileDurableOutbox.subscribe(resume);++ void mobileDurableOutbox.ready().then(resume);++ return () => { active = false; unsubscribe(); };++ }, [enabled, deviceId, workingDir, owner]);++}