Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(mobile): 创建失败时带回已排队的后续消息

Dash79893e46f115
diff --cc apps/mobile/app/sessions/[sessionId].tsx
index 38def4b351,c89cc3f98f..54239ce63d
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@@ -4099,76 -4093,11 +4099,77 @@@ function SessionScreenContent()
// 新建会话乐观管线的收口响应:
// - running → task 移除(成功):守卫解除,补一轮完整同步(权威 meta / 交互 / projection);
- // - create-failed:Alert 重试面(重试 = 同 id 重跑管线,幂等安全;返回编辑 = 草稿
- // stash 回新建页并移除合成行)+ 常驻错误条兜底(Alert 被系统关掉时仍有指引);
+ // - create-failed:带回草稿与附件并自动返回编辑,不要求用户选择恢复方式;
// - enqueue-failed:会话已建成,首条消息文本 / 附件回填 composer,用户走正常发送
// (新桌面有 clientId 幂等去重,重复风险已兜)。
- const creationTask = useNewSessionCreationTask(sessionId);
+ const creationScreenFocused = useIsFocused();
+ useFailedCreationReturnToEdit({
+ task: creationTask?.deviceId === deviceId ? creationTask : null,
+ focused: creationScreenFocused,
++ sending,
+ connectionEpoch,
+ onReady: params => router.replace({ pathname: '/sessions/new', params: {
+ ...params,
+ creationError: creationTask?.error ?? t('session.screen.createFailedDefault'),
+ } }),
+ onError: err => setError(t('session.screen.createFailedNotice', { message: formatRemoteError(err) })),
+ beforeNavigate: async () => {
+ const owner = getMobileAuthOwner();
+ if (outboxSessionAliveRef.current !== sessionId) return;
+ const notice = hasAttachmentInput()
+ ? t('session.screen.pendingAttachmentsNotCarriedBack')
+ : attachmentError;
+ // Seal native picker/paste callbacks as well as queued uploads. Keep the
+ // warning in the existing error state if durable saving needs another try.
+ if (notice) setAttachmentError(notice);
+ discardAllPendingUploadsForScopeChange();
+ const text = draftRef.current;
+ const files = [...attachmentsRef.current];
+ if (!text && files.length === 0 && !notice) return;
+ const dropped = await appendNewSessionEditComposer(sessionId, deviceId, { text, attachments: files, notice, getUploadedSource });
+ if (!isMobileAuthOwnerCurrent(owner) || outboxSessionAliveRef.current !== sessionId) return;
+ // Ownership changed only after the save succeeded. Unmount cleanup must
+ // not delete attachments now owned by the recovered new-task draft.
+ releaseUploadedSources(files.map(file => file.id));
+ attachmentsRef.current = [];
+ setAttachments([]);
+ replaceComposerDraft('');
+ discardRecoveredAttachments(dropped);
+ },
+ stashDraft: prepared => {
+ // 创建期间发出的后续消息必须一起带回新建页(review P1):它们此刻在 outbox 里,
+ // 而下一行 dismiss 会连同合成会话行一起删掉——会话页 unmount 时 cleanup 会把它们
+ // 写进那个已经不存在的会话的草稿,用户在新建页看不到、也再也找不回来。
+ // 新建页只有一个首条消息输入框,所以按序拼成文本、附件按 id 去重合并后一起 stash。
+ // 上传任务保不住:本页(连同 upload controller)马上要销毁,只能取消
+ // 并回收,再把「没能带回多少」告知用户(review P1:静默丢等于偷走内容)。
+ const { items: followUps, cancelledUploadCount } = takeOutboxForSession(sessionId, 'cancel');
+ if (followUps.length > 0) {
+ const { merged, dropped } = mergeAttachmentsWithinLimit(
+ prepared.attachments,
+ followUps.flatMap(outboxItemAttachments),
+ );
+ // 装不下的中转对象在这里回收:草稿带不走它们,留着就是没人认领的垃圾。
+ discardRecoveredAttachments(dropped);
+ const unrecoveredCount = dropped.length + cancelledUploadCount;
+ stashNewSessionDraftForEdit(prepared, {
+ draft: {
+ ...prepared.draft,
+ firstMessage: [
+ prepared.draft.firstMessage,
+ ...followUps.map(outboxItemDraftText),
+ ].filter(Boolean).join('\n\n'),
+ },
+ attachments: merged,
+ notice: unrecoveredCount > 0
+ ? t('session.screen.attachmentsNotCarriedBack', { count: unrecoveredCount })
+ : null,
+ });
+ } else {
+ stashNewSessionDraftForEdit(prepared);
+ }
+ },
+ });
const prevCreationStatusRef = useRef<string | null>(null);
useEffect(() => {
const prev = prevCreationStatusRef.current;
diff --cc apps/mobile/app/sessions/new.tsx
index 0c0ad46184,ec19ed5f79..1a6c274c00
--- a/apps/mobile/app/sessions/new.tsx
+++ b/apps/mobile/app/sessions/new.tsx
@@@ -855,10 -851,20 +855,11 @@@ export default function NewRemoteSessio
router.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,
++ onError: error => setError(formatRemoteError(error)),
+ onRestore: record => {
outboxRecoveryRef.current = record;
userTouchedDeviceRef.current = true;
restoreCreationDraft(record.creation.draft,
diff --cc apps/mobile/src/__tests__/newSessionCreation.test.ts
index 27eebe6ffd,bcebea61b1..2cfc20f07a
--- a/apps/mobile/src/__tests__/newSessionCreation.test.ts
+++ b/apps/mobile/src/__tests__/newSessionCreation.test.ts
@@@ -25,9 -24,9 +25,9 @@@ vi.mock('@/session/mobileDurableOutbox'
suspendCreationDraftForCleanup: vi.fn(async () => {}),
getCurrentMobileOutboxRecords: editOutbox.records,
isDurableOutboxCreationHeld: () => false,
-- mobileDurableOutbox: { update: editOutbox.update, subscribe: () => () => {} },
++ mobileDurableOutbox: { update: editOutbox.update, subscribe: () => () => {}, reconcileDrafts: async () => {} },
}));
-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),
diff --cc apps/mobile/src/__tests__/newSessionCreationPersistence.test.ts
index af253893bd,34facd3ae5..f062eade7a
--- a/apps/mobile/src/__tests__/newSessionCreationPersistence.test.ts
+++ b/apps/mobile/src/__tests__/newSessionCreationPersistence.test.ts
@@@ -5,14 -5,10 +5,17 @@@ import { beforeEach, expect, it, vi } f
import { getMobileAuthOwner, setMobileAuthOwner } from '../auth/authOwnerGeneration';
import type { MobileMakerTransport } from '../device-link/mobileMakerTransport';
import type { DurableOutboxRecord } from '../session/durableOutbox';
+import type { MobileLocalAttachmentUploadCandidate } from '../session/mobileLocalAttachmentUpload';
+import { retainOutboxFile, durableOutboxUploadUri, removeRetainedOutboxFiles } from '../session/durableOutboxFiles';
import { cancelledCreationDraft, outboxCreationRetryIdentity } from '../session/cancelledCreationDraft';
import { buildOutboxItem } from '../session/sessionOutbox';
+import { persistNewSessionCreationDraft } from '../session/persistNewSessionCreationDraft';
+import { returnNewSessionToEdit } from '../session/returnNewSessionToEdit';
++import { mergeNewSessionEditFollowUps } from '../session/mergeNewSessionEditFollowUps';
++import { createDurableOutboxDelivery } from '../session/durableOutboxDelivery';
++import type { InputProjection, QueuedRemoteMessage } from '../session/types';
--const disk = vi.hoisted(() => ({ data: new Map<string, string>(), fail: false }));
++const disk = vi.hoisted(() => ({ data: new Map<string, string>(), fail: false, failRemove: false }));
vi.mock('@react-native-async-storage/async-storage', () => ({ default: {
getAllKeys: async () => [...disk.data.keys()],
getItem: async (key: string) => disk.data.get(key) ?? null,
@@@ -20,25 -16,9 +23,28 @@@
if (disk.fail) throw new Error('disk unavailable');
disk.data.set(key, value);
},
-- removeItem: async (key: string) => { disk.data.delete(key); },
++ removeItem: async (key: string) => {
++ if (disk.failRemove) throw new Error('remove unavailable');
++ disk.data.delete(key);
++ },
} }));
-vi.mock('../session/durableOutboxFiles', () => ({ durableOutboxUploadUri: vi.fn(), removeOutboxFiles: vi.fn() }));
+const files = vi.hoisted(() => ({ retained: new Map<string, string>(), sequence: 0, beforeCopy: async () => {} }));
+vi.mock('../session/durableOutboxFiles', () => {
+ const uri = (record: DurableOutboxRecord, upload: { fileName: string }) => `file:///outbox/${record.item.clientId}/${upload.fileName}`;
+ return {
- durableOutboxUploadUri: uri, removeOutboxFiles: vi.fn(),
++ durableOutboxUploadUri: uri, removeOutboxFiles: vi.fn(async () => {}),
+ outboxAttachmentNeedsLocalBytes: (file: { path: string }) => file.path.startsWith('cindy-oss-attach://') || file.path.startsWith('cindy-peer-attach://'),
+ retainOutboxFile: vi.fn(async (record: DurableOutboxRecord, slot: number, source: MobileLocalAttachmentUploadCandidate) => {
+ await files.beforeCopy();
+ const upload = { slot, fileName: `slot-${slot}-${++files.sequence}.png`, name: source.name, size: source.size, kind: source.kind };
+ files.retained.set(uri(record, upload), source.uri);
+ return upload;
+ }),
+ removeRetainedOutboxFiles: vi.fn(async (record: DurableOutboxRecord) => {
+ for (const upload of record.uploads) files.retained.delete(uri(record, upload));
+ }),
+ };
+});
vi.mock('../session/mobileAttachmentUpload', () => ({ discardMobileUploadedAttachment: vi.fn() }));
vi.mock('expo-crypto', () => ({ getRandomBytes: (n: number) => new Uint8Array(n).fill(7) }));
import { getCurrentMobileOutboxRecords, mobileDurableOutbox, persistCancelledCreationDraft } from '../session/mobileDurableOutbox';
@@@ -75,9 -54,6 +81,10 @@@ beforeEach(async () =>
await mobileDurableOutbox.activate('');
disk.data.clear();
disk.fail = false;
++ disk.failRemove = false;
+ files.retained.clear();
+ files.sequence = 0;
+ files.beforeCopy = async () => {};
setMobileAuthOwner('alice', 'global');
await mobileDurableOutbox.activate(getMobileAuthOwner().accountKey);
});
@@@ -403,176 -378,3 +410,303 @@@ it('preserves a directory explicitly se
}));
expect(getCurrentMobileOutboxRecords()[0].creation?.originalWorkingDir).toBe('/other-repo');
});
+
+// Regression: deleting only the mirror let the durable bridge recreate an
+// undeletable task. Exercise the production removal with real persisted bytes.
+async function saveDraftFixture() {
+ const draft = { agentKind: 'codex' as const, workspaceKind: 'project' as const,
+ workingDir: '/repo', model: 'model', providerId: null, effort: 'high',
+ permissionMode: 'ask', fastMode: false, firstMessage: 'keep my input' };
+ return (await persistNewSessionCreationDraft({
+ record: { version: 1, accountId: getMobileAuthOwner().accountKey, deviceId: 'pc', createdAt: 1,
+ state: 'queued', uploads: [], creation: { draft, originalWorkingDir: '/repo', deviceName: 'PC', planModeArm: false, restorePermissionMode: null },
+ item: buildOutboxItem({ clientId: 'message', sessionId: 'session-1', text: draft.firstMessage,
+ permissionModeAtSend: 'ask', quotesEncoded: false, agentReferences: [], pastedTextRanges: [], slashCommandRanges: [],
+ readyAttachments: [{ id: 'photo', path: 'cindy-oss-attach://photo', name: 'photo.png', ext: 'png', size: 3, category: 'image', mimeType: 'image/png' }],
+ readyPreviews: [], claimedUploads: [] }),
+ },
+ recovering: null, isCurrent: () => true,
+ getUploadedSource: () => ({ uri: 'file:///photo.png', name: 'photo.png', size: 3, kind: 'image' }),
+ }))!;
+}
+
+it.each(['deleted', 'archived'])('retires saved recovery on %s, including editor release and cold reload', async status => {
+ const original = await saveDraftFixture();
+ const saved = await mobileDurableOutbox.update(original, cancelledCreationDraft(original));
+ expect(findNewSessionEditDraft('pc', '/repo')).toEqual(saved);
+ expect(findNewSessionEditDraft('other-pc')).toBeUndefined();
+ expect(findNewSessionEditDraft('pc', '/other-repo')).toBeUndefined();
+ const leave = completeNewSessionDurableEdit(saved.item.sessionId, 'pc')!;
+ expect(findNewSessionEditDraft('pc')).toBeUndefined();
+ const remote = vi.fn();
+ await withNewSessionCreationRemoval(saved.item.sessionId, 'pc', status, remote);
+ leave();
+ expect(remote).not.toHaveBeenCalled();
+ expect(getCurrentMobileOutboxRecords()).toEqual([]);
+ expect(mobileDurableOutbox.getSnapshot()[0].cleanupOutcome).toBe('cancelled');
+ await mobileDurableOutbox.activate('');
+ await mobileDurableOutbox.activate(getMobileAuthOwner().accountKey);
+ expect(restoreNewSessionDurableEdit(mobileDurableOutbox.getSnapshot()[0])).toBe(false);
+ expect(findNewSessionEditDraft('pc')).toBeUndefined();
+ expect(remoteSessionStore.getSessions()).toEqual([]);
+});
+
+it('keeps a saved draft if durable deletion fails', async () => {
+ const original = await saveDraftFixture();
+ const saved = await mobileDurableOutbox.update(original, cancelledCreationDraft(original));
+ disk.fail = true;
+ await expect(withNewSessionCreationRemoval(saved.item.sessionId, 'pc', 'deleted', vi.fn())).rejects.toThrow('disk unavailable');
+ disk.fail = false;
+ expect(findNewSessionEditDraft('pc')).toEqual(saved);
+});
+
+it.each([false, true])('preserves the current composer in the durable recovery before handoff (save fails: %s)', async fails => {
+ const original = await saveDraftFixture();
+ const saved = await mobileDurableOutbox.update(original, cancelledCreationDraft(original));
+ const file = { ...saved.item.attachmentSlots[0]!, id: 'new-file', name: 'new.png', path: 'cindy-oss-attach://new' };
+ disk.fail = fails;
+ const transfer = appendNewSessionEditComposer(saved.item.sessionId, 'pc', {
+ text: 'also keep my unsent input', attachments: [file], notice: 'one upload needs to be selected again',
+ getUploadedSource: () => ({ uri: 'file:///composer/new.png', name: 'new.png', size: 3, kind: 'image' }),
+ });
+ if (fails) {
+ await expect(transfer).rejects.toThrow('disk unavailable');
+ expect(getCurrentMobileOutboxRecords()[0]).toEqual(saved);
+ expect(files.retained.size).toBe(1); // Only the pre-existing first attachment survives rollback.
+ disk.fail = false;
+ return;
+ }
+ expect(await transfer).toEqual([]);
+ await mobileDurableOutbox.activate('');
+ await mobileDurableOutbox.activate(getMobileAuthOwner().accountKey);
+ const restored = findNewSessionEditDraft('pc')!;
+ expect(restored.creation?.draft.firstMessage).toBe('keep my input\n\nalso keep my unsent input');
+ expect(restored.creation?.notice).toBe('one upload needs to be selected again');
+ expect(restored.item.attachmentSlots.map(file => file?.id)).toEqual(['photo', 'new-file']);
+ expect(restored.uploads[0]).toEqual(saved.uploads[0]);
+ expect(restored.uploads[1]).toMatchObject({ slot: 1, name: 'new.png', size: 3, kind: 'image' });
+ expect(restored.item.slotMeta).toHaveLength(2);
+ const resubmitted = await persistNewSessionCreationDraft({
+ record: { ...restored, item: { ...restored.item, sessionId: 'resubmitted' }, storageSessionId: restored.item.sessionId },
+ recovering: restored, isCurrent: () => true,
+ getUploadedSource: () => undefined, // Old chat has unmounted; only durable bytes remain.
+ });
+ expect(getCurrentMobileOutboxRecords()).toEqual([resubmitted]);
+ expect(resubmitted?.uploads).toHaveLength(2);
+ expect(resubmitted?.item.text).toBe(restored.item.text);
+ expect(retainOutboxFile).toHaveBeenCalledWith(expect.anything(), 1, expect.objectContaining({
+ uri: durableOutboxUploadUri(restored, restored.uploads[1]), name: 'new.png',
+ }));
+});
+
+// Regression: incomplete/late attachment transfers must not replace recovery or
+// leak newly retained copies. The original draft and its bytes stay intact.
+it.each(['copy-fails', 'missing-source', 'deleted', 'account-change'] as const)(
+ 'rolls back only new attachment copies when composer transfer cannot finish: %s', async outcome => {
+ const original = await saveDraftFixture();
+ const saved = await mobileDurableOutbox.update(original, cancelledCreationDraft(original));
+ const retainedBefore = new Map(files.retained);
+ const attachments = ['one', 'two'].map(id => ({ ...saved.item.attachmentSlots[0]!, id,
+ path: `cindy-peer-attach://${id}` }));
+ let copies = 0;
+ files.beforeCopy = async () => {
+ if (++copies !== 2) return;
+ if (outcome === 'copy-fails') throw new Error('copy unavailable');
+ if (outcome === 'deleted') {
+ await withNewSessionCreationRemoval(saved.item.sessionId, 'pc', 'deleted', vi.fn());
+ }
+ if (outcome === 'account-change') {
+ setMobileAuthOwner('bob', 'global');
+ await mobileDurableOutbox.activate(getMobileAuthOwner().accountKey);
+ }
+ };
+ const transfer = appendNewSessionEditComposer(saved.item.sessionId, 'pc', {
+ text: 'unsent', attachments,
+ getUploadedSource: id => outcome === 'missing-source' && id === 'two' ? undefined
+ : { uri: `file:///composer/${id}.png`, name: `${id}.png`, size: 3, kind: 'image' },
+ });
+ await expect(transfer).rejects.toThrow();
+ expect(files.retained).toEqual(retainedBefore);
+ if (outcome === 'account-change') {
+ expect(getCurrentMobileOutboxRecords()).toEqual([]);
+ setMobileAuthOwner('alice', 'global');
+ await mobileDurableOutbox.activate(getMobileAuthOwner().accountKey);
+ }
+ if (outcome === 'deleted') {
+ expect(findNewSessionEditDraft('pc')).toBeUndefined();
+ expect(mobileDurableOutbox.getSnapshot()[0].cleanupOutcome).toBe('cancelled');
+ } else {
+ expect(getCurrentMobileOutboxRecords()).toEqual([saved]);
+ }
+ });
+
+it.each(['success', 'not-found', 'network-error', 'superseded', 'account-change'] as const)(
+ 'retires outbox recovery only after authoritative removal: %s', async outcome => {
+ await saveDraftFixture();
+ const saved = await mobileDurableOutbox.update(getCurrentMobileOutboxRecords()[0], { state: 'failed' });
+ let current = true;
+ const remove = vi.fn(async () => {
+ if (outcome === 'superseded') current = false;
+ if (outcome === 'account-change') setMobileAuthOwner('bob', 'global');
+ if (outcome === 'not-found') throw new Error('[NOT_FOUND] missing');
+ if (outcome === 'network-error') throw new Error('offline');
+ return { id: saved.item.sessionId };
+ });
+ const result = withNewSessionCreationRemoval(saved.item.sessionId, 'pc', 'deleted', remove, () => current);
+ if (outcome === 'not-found') await expect(result).rejects.toThrow('NOT_FOUND');
+ else if (outcome === 'network-error') await expect(result).rejects.toThrow('offline');
+ else if (outcome === 'account-change') await expect(result).rejects.toThrow('STALE_AUTH_OWNER');
+ else await result;
+ expect(remove).toHaveBeenCalledOnce();
+ expect(mobileDurableOutbox.getSnapshot()[0].cleanupOutcome).toBe(
+ outcome === 'success' || outcome === 'not-found' ? 'cancelled' : undefined);
+ });
+
+it('persists the real creation error through return to edit and cold recovery', async () => {
+ const record = await saveDraftFixture();
++ // P1 #6281: a second send used a separate ledger row which recovery ignored.
++ // Unit: actual return-to-edit must preserve that message before navigation.
++ await mobileDurableOutbox.add({ ...record, creation: undefined, uploads: [], createdAt: 2,
++ item: { ...record.item, clientId: 'follow-up', text: 'second message', attachmentSlots: [], slotMeta: [] } });
+ startNewSessionCreation({
+ sessionId: record.item.sessionId, firstMessageClientId: record.item.clientId,
+ deviceId: record.deviceId, deviceName: 'PC', draft: record.creation!.draft,
+ attachments: [], planModeArm: false, legacyPlanRestore: null,
+ confirmUnauthenticated: async () => ({ unauthenticated: true, fresh: null }),
+ authGateHint: 'Provider setup required', onUnauthenticated: () => {},
+ transport: { openLink: async () => {}, subscribe: async () => {}, handoffFirstMessage: async () => {},
+ maker: {} as MobileMakerTransport },
+ });
+ await vi.waitFor(() => expect(getNewSessionCreationTask(record.item.sessionId)?.status).toBe('create-failed'));
+ await returnNewSessionToEdit({ sessionId: record.item.sessionId, deviceId: record.deviceId,
+ isCurrent: () => true, onReady: () => {} });
+ expect(getCurrentMobileOutboxRecords()[0].error).toBe('Provider setup required');
++ expect(getCurrentMobileOutboxRecords()[0].creation?.draft.firstMessage).toBe('keep my input\n\nsecond message');
++ expect(getCurrentMobileOutboxRecords()).toHaveLength(1);
+ setMobileAuthOwner(null);
+ await mobileDurableOutbox.activate('');
+ setMobileAuthOwner('alice', 'global');
+ await mobileDurableOutbox.activate(getMobileAuthOwner().accountKey);
+ expect(findNewSessionEditDraft('pc')?.error).toBe('Provider setup required');
+});
++
++// P1 #6281: previous tests covered only unsent composer input, not independently
++// queued messages. Unit production consolidation checks order, byte ownership,
++// interrupted writes and deletion/account races with the real durable store.
++async function saveFollowUpFixture(first: DurableOutboxRecord, pendingUpload = false) {
++ const record: DurableOutboxRecord = { ...first, createdAt: 2, creation: undefined,
++ item: { ...first.item, clientId: 'follow-up', text: 'second message',
++ attachmentSlots: [pendingUpload ? null : { ...first.item.attachmentSlots[0]!, id: 'second-photo' }] }, uploads: [] };
++ record.uploads.push(await retainOutboxFile(record, 0, { uri: 'file:///second.png', name: 'second.png', kind: 'image', size: 3 }));
++ await mobileDurableOutbox.add(record);
++ return record;
++}
++
++it.each([false, true])('recovers sent follow-ups before composer input, retaining upload bytes (pending: %s)', async pendingUpload => {
++ const original = await saveDraftFixture();
++ const first = await mobileDurableOutbox.update(original, cancelledCreationDraft(original));
++ const second = await saveFollowUpFixture(first, pendingUpload);
++ const other = { ...second, deviceId: 'other-pc', item: { ...second.item, clientId: 'other-device' } };
++ await mobileDurableOutbox.add(other);
++ await mobileDurableOutbox.add({ ...second, createdAt: 3, uploads: [], item: { ...second.item,
++ clientId: 'third', text: 'third message', attachmentSlots: [], slotMeta: [] } });
++ const saved = (await mergeNewSessionEditFollowUps(first.item.sessionId, 'pc'))!;
++ expect(saved.creation?.draft.firstMessage).toBe('keep my input\n\nsecond message\n\nthird message');
++ expect(saved.uploads).toHaveLength(2);
++ expect(files.retained.get(durableOutboxUploadUri(saved, saved.uploads[1]))).toBe(durableOutboxUploadUri(second, second.uploads[0]));
++ if (pendingUpload) expect(saved.item.attachmentSlots[1]?.path).toBe(durableOutboxUploadUri(saved, saved.uploads[1]));
++ await appendNewSessionEditComposer(first.item.sessionId, 'pc', { text: 'still typing', attachments: [] });
++ await mobileDurableOutbox.activate('');
++ await mobileDurableOutbox.activate(getMobileAuthOwner().accountKey);
++ const restored = (await mergeNewSessionEditFollowUps(first.item.sessionId, 'pc'))!;
++ expect(restored.creation?.draft.firstMessage).toBe('keep my input\n\nsecond message\n\nthird message\n\nstill typing');
++ expect(getCurrentMobileOutboxRecords().filter(r => r.deviceId === 'pc')).toEqual([restored]);
++ expect(getCurrentMobileOutboxRecords().find(r => r.deviceId === 'other-pc')).toEqual(other);
++ const resent = await persistNewSessionCreationDraft({ record: { ...restored, storageSessionId: first.item.sessionId,
++ item: { ...restored.item, sessionId: 'replacement' } }, recovering: restored, isCurrent: () => true,
++ getUploadedSource: () => undefined });
++ expect(resent?.uploads).toHaveLength(2);
++ // Exercise delivery, not just the copied files: local-only recovered slots
++ // must be uploaded before the new task receives its message.
++ await mobileDurableOutbox.update(resent!, { state: 'queued', suspended: false, error: undefined,
++ creation: { ...resent!.creation!, cancelled: undefined, editReady: undefined } });
++ const projection = { sessionId: 'replacement', pendingQueue: [] } as unknown as InputProjection;
++ const enqueue = vi.fn(async (_record: DurableOutboxRecord) => projection);
++ const upload = vi.fn(async (_record: DurableOutboxRecord, retained: { slot: number }) => ({
++ ...first.item.attachmentSlots[0]!, id: `fresh-${retained.slot}`, path: `cindy-oss-attach://fresh-${retained.slot}`,
++ }));
++ await createDurableOutboxDelivery({ store: mobileDurableOutbox, isCurrent: () => true,
++ canRun: r => r.deviceId === 'pc', projection: async () => projection,
++ session: async () => ({ id: 'replacement', status: 'active' }),
++ prepare: async r => ({ clientId: r.item.clientId } as QueuedRemoteMessage), upload, enqueue,
++ cancel: async () => true, history: async () => false, applyProjection: () => {}, cleanup: async () => {},
++ discardUploads: () => {}, retryable: () => false, describe: String, confirmationMessage: 'confirm', clearedMessage: 'cleared',
++ }).run();
++ expect(upload).toHaveBeenCalledTimes(2);
++ expect(enqueue).toHaveBeenCalledOnce();
++ expect(enqueue.mock.calls[0][0].item.attachmentSlots.map(a => a?.path)).toEqual([
++ 'cindy-oss-attach://fresh-0', 'cindy-oss-attach://fresh-1',
++ ]);
++});
++
++it('finishes interrupted source removal after reload without duplicating merged content', async () => {
++ const original = await saveDraftFixture();
++ const first = await mobileDurableOutbox.update(original, cancelledCreationDraft(original));
++ await saveFollowUpFixture(first);
++ disk.failRemove = true;
++ await expect(mergeNewSessionEditFollowUps(first.item.sessionId, 'pc')).rejects.toThrow('remove unavailable');
++ expect(getCurrentMobileOutboxRecords()).toHaveLength(2);
++ disk.failRemove = false;
++ await mobileDurableOutbox.activate('');
++ await mobileDurableOutbox.activate(getMobileAuthOwner().accountKey);
++ const saved = await mergeNewSessionEditFollowUps(first.item.sessionId, 'pc');
++ expect(saved?.creation?.draft.firstMessage).toBe('keep my input\n\nsecond message');
++ expect(saved?.uploads).toHaveLength(2);
++ expect(getCurrentMobileOutboxRecords()).toEqual([saved]);
++});
++
++it('reports overflow from multiple messages and refuses records with delivery evidence', async () => {
++ const original = await saveDraftFixture();
++ const first = await mobileDurableOutbox.update(original, cancelledCreationDraft(original));
++ const followUp: DurableOutboxRecord = { ...first, creation: undefined, uploads: [], createdAt: 2,
++ enqueueStarted: true, item: { ...first.item, clientId: 'many-files', text: 'keep all text',
++ attachmentSlots: Array.from({ length: 21 }, (_, i) => ({ ...first.item.attachmentSlots[0]!,
++ id: `file-${i}`, path: `/repo/file-${i}.png` })) } };
++ await mobileDurableOutbox.add(followUp);
++ await expect(mergeNewSessionEditFollowUps(first.item.sessionId, 'pc')).rejects.toThrow('OUTBOX_CREATION_OWNERSHIP_UNRESOLVED');
++ expect(getCurrentMobileOutboxRecords()).toHaveLength(2);
++ await mobileDurableOutbox.update(followUp, { enqueueStarted: false });
++ const saved = await mergeNewSessionEditFollowUps(first.item.sessionId, 'pc');
++ expect(saved?.item.attachmentSlots).toHaveLength(20);
++ expect(saved?.creation?.notice).toBeTruthy();
++ expect(saved?.creation?.draft.firstMessage).toBe('keep my input\n\nkeep all text');
++});
++
++it.each(['copy-fails', 'save-fails', 'source-edited', 'deleted', 'account-change'] as const)(
++ 'keeps source messages and rejects stale consolidation: %s', async outcome => {
++ const original = await saveDraftFixture();
++ const first = await mobileDurableOutbox.update(original, cancelledCreationDraft(original));
++ const second = await saveFollowUpFixture(first);
++ const before = new Map(files.retained);
++ files.beforeCopy = async () => {
++ if (outcome === 'copy-fails') throw new Error('copy unavailable');
++ if (outcome === 'save-fails') disk.fail = true;
++ if (outcome === 'source-edited') await mobileDurableOutbox.update(second, { item: { ...second.item, text: 'edited' } });
++ if (outcome === 'deleted') await withNewSessionCreationRemoval(first.item.sessionId, 'pc', 'deleted', vi.fn());
++ if (outcome === 'account-change') { setMobileAuthOwner('bob', 'global'); await mobileDurableOutbox.activate(getMobileAuthOwner().accountKey); }
++ };
++ await expect(mergeNewSessionEditFollowUps(first.item.sessionId, 'pc')).rejects.toThrow();
++ expect(files.retained).toEqual(before);
++ disk.fail = false;
++ setMobileAuthOwner('alice', 'global');
++ await mobileDurableOutbox.activate('');
++ await mobileDurableOutbox.activate(getMobileAuthOwner().accountKey);
++ if (outcome === 'deleted') {
++ expect(getCurrentMobileOutboxRecords()).toEqual([]);
++ expect(findNewSessionEditDraft('pc')).toBeUndefined();
++ } else {
++ expect(getCurrentMobileOutboxRecords()).toHaveLength(2);
++ expect(findNewSessionEditDraft('pc')?.creation?.draft.firstMessage).toBe('keep my input');
++ }
++ },
++);
diff --cc apps/mobile/src/__tests__/useFailedCreationReturnToEdit.test.tsx
index 65dc0e0a4a,0000000000..e8e28c6add
mode 100644,000000..100644
--- a/apps/mobile/src/__tests__/useFailedCreationReturnToEdit.test.tsx
+++ b/apps/mobile/src/__tests__/useFailedCreationReturnToEdit.test.tsx
@@@ -1,181 -1,0 +1,194 @@@
+// @vitest-environment jsdom
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { useFailedCreationReturnToEdit } from '@/session/useFailedCreationReturnToEdit';
+import type { NewSessionCreationTask } from '@/session/newSessionCreation';
+import type { returnNewSessionToEdit } from '@/session/returnNewSessionToEdit';
+
+const state = vi.hoisted(() => ({ recover: vi.fn(), owner: 1 }));
+vi.mock('@/session/returnNewSessionToEdit', () => ({ returnNewSessionToEdit: state.recover }));
+vi.mock('@/auth/authOwnerGeneration', () => ({
+ getMobileAuthOwner: () => state.owner,
+ isMobileAuthOwnerCurrent: (owner: number) => owner === state.owner,
+}));
+const failedTask = (): NewSessionCreationTask => ({
+ sessionId: 'task', deviceId: 'device', deviceName: 'PC', status: 'create-failed',
+ startedAt: 1, phase: 'creating', error: 'Model unavailable',
+ firstMessageClientId: 'first', attachments: [],
+ draft: { agentKind: 'codex', workspaceKind: 'dialogue', model: 'model', effort: 'medium',
+ permissionMode: 'auto', workingDir: '', providerId: 'openai', fastMode: false, firstMessage: 'My draft' },
+});
+type Props = Parameters<typeof useFailedCreationReturnToEdit>[0];
+type Recovery = Parameters<typeof returnNewSessionToEdit>[0];
+function Screen(props: Props) {
+ useFailedCreationReturnToEdit(props);
+ return <span>Chat</span>;
+}
+let root: Root;
+let container: HTMLDivElement;
+let props: Props;
+let pending: Recovery;
+let finish: () => void;
+const actEnvironment = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
+let previousActEnvironment: boolean | undefined;
+const render = () => act(async () => root.render(<Screen {...props} />));
+beforeEach(() => {
+ previousActEnvironment = actEnvironment.IS_REACT_ACT_ENVIRONMENT;
+ actEnvironment.IS_REACT_ACT_ENVIRONMENT = true;
+ state.owner = 1;
+ state.recover.mockReset().mockImplementation((options: Recovery) => {
+ pending = options;
+ return new Promise<void>(resolve => { finish = resolve; });
+ });
+ props = { task: failedTask(), focused: true, connectionEpoch: 1,
+ stashDraft: vi.fn(), onReady: vi.fn(), onError: vi.fn() };
+ container = document.createElement('div');
+ document.body.append(container);
+ root = createRoot(container);
+});
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ actEnvironment.IS_REACT_ACT_ENVIRONMENT = previousActEnvironment;
+});
+
+it.each(['running', 'enqueue-failed'] as const)('keeps %s in chat without returning to edit', async status => {
+ props.task = { ...failedTask(), status };
+ await render();
+ expect(container.textContent).toBe('Chat');
+ expect(state.recover).not.toHaveBeenCalled();
+});
+
+it('automatically recovers creation failure once and hands the saved draft to the form', async () => {
+ await render();
+ props.task = { ...props.task!, returningToEdit: true };
+ await render();
+ expect(state.recover).toHaveBeenCalledTimes(1);
+ expect(pending.stashDraft).toBe(props.stashDraft);
+ const params = { deviceId: 'device', deviceName: 'PC', recoverySessionId: 'task' };
+ await act(async () => { pending.onReady(params); finish(); });
+ expect(props.onReady).toHaveBeenCalledExactlyOnceWith(params);
+ props.task = { ...props.task!, readyForEdit: 'durable', returningToEdit: false };
+ await render();
+ expect(state.recover).toHaveBeenCalledTimes(1);
+});
+
+it.each(['leave', 'blur', 'account', 'task'] as const)('ignores late navigation after %s', async change => {
+ await render();
+ const old = pending;
+ if (change === 'leave') await act(async () => root.render(null));
+ if (change === 'blur') { props.focused = false; await render(); }
+ if (change === 'account') state.owner += 1;
+ if (change === 'task') { props.task = { ...failedTask(), sessionId: 'other' }; await render(); }
+ expect(old.isCurrent()).toBe(false);
+ old.onReady({ deviceId: 'device', deviceName: 'PC', editSessionId: 'task' });
+ expect(props.onReady).not.toHaveBeenCalled();
+});
+
+it('starts recovery only when the failed task is focused', async () => {
+ props.focused = false;
+ await render();
+ expect(state.recover).not.toHaveBeenCalled();
+ props.focused = true;
+ await render();
+ expect(state.recover).toHaveBeenCalledTimes(1);
+});
+
++// A failure can arrive while the second send is retaining bytes. Navigation
++// must wait for that send's durable handoff, not strand it under the old task.
++it('waits for an in-progress send before recovering the failed creation', async () => {
++ props.sending = true;
++ await render();
++ expect(state.recover).not.toHaveBeenCalled();
++ props.sending = false;
++ await render();
++ expect(state.recover).toHaveBeenCalledOnce();
++ await act(async () => { await pending.onReady({ deviceId: 'device', deviceName: 'PC', recoverySessionId: 'task' }); finish(); });
++ expect(props.onReady).toHaveBeenCalledOnce();
++});
++
+it('resumes a prepared draft after recovery started on an earlier mount', async () => {
+ props.task = { ...failedTask(), returningToEdit: true };
+ state.recover.mockResolvedValue(undefined);
+ await render();
+ props.task = { ...failedTask(), readyForEdit: 'memory' };
+ state.recover.mockImplementation(async (options: Recovery) => {
+ options.onReady({ deviceId: 'device', deviceName: 'PC', editSessionId: 'task' });
+ });
+ await render();
+ expect(props.onReady).toHaveBeenCalledExactlyOnceWith({
+ deviceId: 'device', deviceName: 'PC', editSessionId: 'task',
+ });
+});
+
+it('reports cleanup failure without a retry loop and resumes after reconnect', async () => {
+ const error = new Error('cleanup pending');
+ state.recover.mockRejectedValue(error);
+ await render();
+ expect(props.onError).toHaveBeenCalledExactlyOnceWith(error);
+ expect(props.onReady).not.toHaveBeenCalled();
+ props.task = { ...failedTask(), returningToEdit: true };
+ await render();
+ props.task = { ...failedTask(), returningToEdit: false };
+ await render();
+ expect(state.recover).toHaveBeenCalledTimes(1);
+ props.connectionEpoch += 1;
+ await render();
+ expect(state.recover).toHaveBeenCalledTimes(2);
+});
+
+// Replaces the former Alert-action lifecycle cases: recovery now starts automatically.
+it.each(['current', 'leave', 'blur', 'account', 'task'] as const)('reports a delayed recovery error only on its current page: %s', async change => {
+ let reject!: (error: Error) => void;
+ state.recover.mockImplementationOnce(() => new Promise((_resolve, fail) => { reject = fail; }));
+ await render();
+ if (change === 'leave') await act(async () => root.render(null));
+ if (change === 'blur') { props.focused = false; await render(); }
+ if (change === 'account') state.owner += 1;
+ if (change === 'task') { props.task = { ...failedTask(), sessionId: 'other' }; await render(); }
+ await act(async () => reject(new Error('cleanup pending')));
+ expect(props.onError).toHaveBeenCalledTimes(change === 'current' ? 1 : 0);
+ expect(props.onReady).not.toHaveBeenCalled();
+});
+
+it('does not lose an in-flight recovery result when the connection changes', async () => {
+ let reject!: (error: Error) => void;
+ state.recover.mockImplementationOnce(() => new Promise((_resolve, fail) => { reject = fail; }));
+ await render();
+ state.recover.mockResolvedValue(undefined); // the shared helper holds the existing recovery
+ props.connectionEpoch += 1;
+ await render();
+ const error = new Error('disk full');
+ await act(async () => reject(error));
+ expect(props.onError).toHaveBeenCalledExactlyOnceWith(error);
+});
+
+it('waits for current composer ownership to transfer before automatic navigation', async () => {
+ let saved!: () => void;
+ const preserve = vi.fn(() => new Promise<void>(resolve => { saved = resolve; }));
+ props = { ...props, beforeNavigate: preserve } as Props;
+ state.recover.mockImplementation(async (options: Recovery) => {
+ await options.onReady({ deviceId: 'device', deviceName: 'PC', recoverySessionId: 'task' });
+ });
+ await render();
+ expect(props.onReady).not.toHaveBeenCalled();
+ expect(preserve).toHaveBeenCalledOnce();
+ await act(async () => saved());
+ expect(props.onReady).toHaveBeenCalledOnce();
+});
+
+it.each(['save-fails', 'leaves'])('does not navigate after composer handoff %s', async outcome => {
+ let finishSave!: () => void;
+ props.beforeNavigate = () => new Promise<void>((resolve, reject) => {
+ finishSave = () => outcome === 'save-fails' ? reject(new Error('disk full')) : resolve();
+ });
+ state.recover.mockImplementation(async (options: Recovery) => {
+ await options.onReady({ deviceId: 'device', deviceName: 'PC', recoverySessionId: 'task' });
+ });
+ await render();
+ if (outcome === 'leaves') { props.focused = false; await render(); }
+ await act(async () => finishSave());
+ expect(props.onReady).not.toHaveBeenCalled();
+ expect(props.onError).toHaveBeenCalledTimes(outcome === 'save-fails' ? 1 : 0);
+});
diff --cc apps/mobile/src/__tests__/useNewSessionDraftRecovery.test.tsx
index de2f02edad,0000000000..74da5a8ddc
mode 100644,000000..100644
--- a/apps/mobile/src/__tests__/useNewSessionDraftRecovery.test.tsx
+++ b/apps/mobile/src/__tests__/useNewSessionDraftRecovery.test.tsx
@@@ -1,169 -1,0 +1,198 @@@
+// @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(),
++ ready: vi.fn(), claim: vi.fn(), release: vi.fn(), find: vi.fn(), merge: 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,
+}));
++vi.mock('@/session/mergeNewSessionEditFollowUps', () => ({ mergeNewSessionEditFollowUps: outbox.merge }));
+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]);
++ outbox.merge.mockReset().mockImplementation(async () => 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);
+});
++
++// Cold recovery now waits for queued messages to join the draft. That await
++// must not restore stale content, swallow a write failure, or claim twice.
++it.each(['complete', 'unmount', 'owner-switch', 'save-fails', 'prepared'] as const)(
++ 'settles follow-up consolidation before restoring the editor: %s', async outcome => {
++ let resolve!: (record: DurableOutboxRecord) => void;
++ let reject!: (error: Error) => void;
++ outbox.merge.mockReturnValue(new Promise((yes, no) => { resolve = yes; reject = no; }));
++ edit.onError = vi.fn();
++ await renderEdit();
++ await act(async () => ready());
++ await notify();
++ expect(outbox.merge).toHaveBeenCalledOnce();
++ expect(outbox.claim).not.toHaveBeenCalled();
++ if (outcome === 'unmount') await act(async () => root.render(null));
++ if (outcome === 'owner-switch') setMobileAuthOwner('other');
++ if (outcome === 'prepared') outbox.records[0].prepared = {} as NonNullable<DurableOutboxRecord['prepared']>;
++ await act(async () => {
++ if (outcome === 'save-fails') reject(new Error('save failed'));
++ else resolve(outbox.records[0]);
++ });
++ expect(outbox.claim).toHaveBeenCalledTimes(outcome === 'complete' ? 1 : 0);
++ expect(edit.onError).toHaveBeenCalledTimes(outcome === 'save-fails' ? 1 : 0);
++ if (outcome === 'complete') expect(container.textContent).toContain('Saved draft');
++ else expect(container.textContent).not.toContain('Saved draft');
++ },
++);
diff --cc apps/mobile/src/session/durableOutbox.ts
index d468974cc8,c443d278d1..4f2cff41a6
--- a/apps/mobile/src/session/durableOutbox.ts
+++ b/apps/mobile/src/session/durableOutbox.ts
@@@ -52,8 -52,6 +52,10 @@@ export interface DurableOutboxRecord
cancelled?: true;
/** Creation was handed back to the editor; restore its entry after restart. */
editReady?: true;
+ /** Content that could not be carried back, shown beside the restored attachments. */
+ notice?: string;
++ /** Messages already copied into this draft; makes interrupted consolidation idempotent. */
++ mergedFollowUpClientIds?: string[];
deviceName: string;
planModeArm: boolean;
restorePermissionMode: string | null;
@@@ -126,6 -124,6 +128,7 @@@ export function createDurableOutbox(sto
record: DurableOutboxRecord,
next: DurableOutboxRecord | null,
adding = false,
++ expectedRecords: readonly DurableOutboxRecord[] = [],
): Promise<DurableOutboxRecord | null> => {
const epoch = generation;
await store.ready();
@@@ -134,6 -132,6 +137,8 @@@
const current = records.find((r) => keyFor(r) === keyFor(record));
if (adding ? current !== undefined : current !== record)
throw new Error("OUTBOX_STALE_WRITE");
++ if (expectedRecords.some((expected) => !records.includes(expected)))
++ throw new Error("OUTBOX_STALE_WRITE");
if (next && keyFor(next) !== keyFor(record)) throw new Error("OUTBOX_IDENTITY_CHANGED");
if (next && next.item.sessionId !== record.item.sessionId
&& (!record.creation?.cancelled || !next.creation || record.prepared)) {
@@@ -233,13 -231,13 +238,14 @@@
update: (
record: DurableOutboxRecord,
patch: Partial<DurableOutboxRecord>,
++ expectedRecords: readonly DurableOutboxRecord[] = [],
) =>
mutate(record, {
...record,
...patch,
accountId: record.accountId,
deviceId: record.deviceId,
-- }) as Promise<DurableOutboxRecord>,
++ }, false, expectedRecords) as Promise<DurableOutboxRecord>,
remove: (record: DurableOutboxRecord) => mutate(record, null),
ready: (): Promise<void> => store.activate(accountId),
};
diff --cc apps/mobile/src/session/mergeNewSessionEditFollowUps.ts
index 0000000000,0000000000..afe400a63d
new file mode 100644
--- /dev/null
+++ b/apps/mobile/src/session/mergeNewSessionEditFollowUps.ts
@@@ -1,0 -1,0 +1,94 @@@
++import { stripChatQuoteMarkerLines } from '@cindy/maker-shared/chat-quotes';
++import { getMobileAuthOwner, isMobileAuthOwnerCurrent } from '@/auth/authOwnerGeneration';
++import { i18n } from '@/i18n';
++import { categorizeMobileAttachment, extractRemoteFileExt, mergeAttachmentsWithinLimit, mimeTypeForMobileAttachment } from './attachments';
++import { isDurableOutboxUnsent, type DurableOutboxRecord } from './durableOutbox';
++import { getCurrentMobileOutboxRecords, mobileDurableOutbox } from './mobileDurableOutbox';
++import type { RemoteSerializedAttachment } from './types';
++
++/** Consolidate unsent messages before either warm navigation or cold editor recovery. */
++export async function mergeNewSessionEditFollowUps(sessionId: string, deviceId: string): Promise<DurableOutboxRecord | undefined> {
++ const owner = getMobileAuthOwner();
++ // Drain committed send handoffs before reading the group, including a send
++ // whose disk write was still queued when its chat unmounted.
++ await mobileDurableOutbox.reconcileDrafts(sessionId);
++ const guard = () => {
++ if (!isMobileAuthOwnerCurrent(owner)) throw new Error('OUTBOX_OWNER_CHANGED');
++ };
++ guard();
++ const group = getCurrentMobileOutboxRecords().filter(r => r.deviceId === deviceId && r.item.sessionId === sessionId);
++ let first = group.find(r => r.creation);
++ if (!first?.creation || first.prepared || !first.suspended) return first;
++ const followUps = group.filter(r => r !== first && !r.creation);
++ if (!followUps.length) return first;
++ if (followUps.some(r => !isDurableOutboxUnsent(r))) throw new Error('OUTBOX_CREATION_OWNERSHIP_UNRESOLVED');
++ const copied = new Set(first.creation.mergedFollowUpClientIds ?? []);
++ const pending = followUps.filter(r => !copied.has(r.item.clientId));
++ const { durableOutboxUploadUri, outboxAttachmentNeedsLocalBytes, removeOutboxFiles, removeRetainedOutboxFiles, retainOutboxFile } = await import('./durableOutboxFiles');
++ const copies: DurableOutboxRecord = { ...first, uploads: [] };
++ let committed = false;
++ try {
++ const attachments = [...first.item.attachmentSlots];
++ const slotMeta = [...first.item.slotMeta];
++ const text = [first.creation.draft.firstMessage];
++ let omitted = 0;
++ for (const record of pending) {
++ text.push(stripChatQuoteMarkerLines(record.item.text));
++ for (let slot = 0; slot < record.item.attachmentSlots.length; slot++) {
++ const upload = record.uploads.find(u => u.slot === slot);
++ // Queued uploads already own durable bytes even before receiving a remote reference.
++ const attachment: RemoteSerializedAttachment | null = record.item.attachmentSlots[slot] ?? (upload ? {
++ id: `${record.item.clientId}-slot-${slot}`, path: durableOutboxUploadUri(record, upload),
++ name: upload.name, ext: extractRemoteFileExt(upload.name), size: upload.size,
++ category: categorizeMobileAttachment(upload.name),
++ mimeType: upload.mimeType ?? mimeTypeForMobileAttachment(extractRemoteFileExt(upload.name), categorizeMobileAttachment(upload.name)),
++ annotated: upload.annotated, annotationRegions: upload.annotationRegions,
++ } : null);
++ if (!attachment) { omitted++; continue; }
++ if (attachments.some(a => a?.id === attachment.id)) continue;
++ const { dropped } = mergeAttachmentsWithinLimit(attachments.filter((a): a is RemoteSerializedAttachment => a !== null), [attachment]);
++ if (dropped.length) { omitted++; continue; }
++ guard();
++ if (upload) {
++ const retained = await retainOutboxFile(first, attachments.length, {
++ ...upload, uri: durableOutboxUploadUri(record, upload),
++ });
++ copies.uploads.push(retained);
++ if (!record.item.attachmentSlots[slot]) {
++ attachment.path = durableOutboxUploadUri(first, retained);
++ if (attachment.category === 'image') attachment.url = attachment.path;
++ }
++ }
++ else if (outboxAttachmentNeedsLocalBytes(attachment)) throw new Error(i18n.t('session.outbox.restoreFailed'));
++ attachments.push(attachment);
++ slotMeta.push({ kind: attachment.category === 'image' ? 'image' : 'file', previewUri: null });
++ }
++ }
++ if (pending.length) {
++ guard();
++ const firstMessage = text.filter(Boolean).join('\n\n');
++ first = await mobileDurableOutbox.update(first, {
++ creation: { ...first.creation, draft: { ...first.creation.draft, firstMessage },
++ mergedFollowUpClientIds: [...copied, ...pending.map(r => r.item.clientId)],
++ notice: [first.creation.notice, omitted ? i18n.t('session.screen.attachmentsNotCarriedBack', { count: omitted }) : null]
++ .filter(Boolean).join('\n') || undefined,
++ },
++ uploads: [...first.uploads, ...copies.uploads],
++ item: { ...first.item, text: firstMessage, attachmentSlots: attachments, slotMeta },
++ }, followUps);
++ }
++ committed = true;
++ // The single parent write owns both content and receipt IDs before any
++ // source is removed. A restart can finish removal without appending twice.
++ for (const record of followUps) {
++ guard();
++ if (!getCurrentMobileOutboxRecords().includes(first)) throw new Error('OUTBOX_STALE_WRITE');
++ await mobileDurableOutbox.remove(record);
++ // Remote references now belong to the parent; only remove local copies.
++ await removeOutboxFiles(record).catch(() => undefined);
++ }
++ return first;
++ } finally {
++ if (!committed) await removeRetainedOutboxFiles(copies).catch(() => undefined);
++ }
++}
diff --cc apps/mobile/src/session/persistNewSessionCreationDraft.ts
index 8ca449363c,0000000000..9c9b778e1f
mode 100644,000000..100644
--- a/apps/mobile/src/session/persistNewSessionCreationDraft.ts
+++ b/apps/mobile/src/session/persistNewSessionCreationDraft.ts
@@@ -1,43 -1,0 +1,45 @@@
+import { i18n } from '@/i18n';
+import type { DurableOutboxRecord } from './durableOutbox';
+import type { MobileLocalAttachmentUploadCandidate } from './mobileLocalAttachmentUpload';
+import { durableOutboxUploadUri, outboxAttachmentNeedsLocalBytes, removeRetainedOutboxFiles, retainOutboxFile } from './durableOutboxFiles';
+import { getCurrentMobileOutboxRecords, mobileDurableOutbox } from './mobileDurableOutbox';
+
+/** Save attachment bytes before the form reserves a worktree or hands off creation. */
+export async function persistNewSessionCreationDraft({ record, recovering, getUploadedSource, isCurrent }: {
+ record: DurableOutboxRecord;
+ recovering: DurableOutboxRecord | null | undefined;
+ getUploadedSource: (id: string) => MobileLocalAttachmentUploadCandidate | undefined;
+ isCurrent: () => boolean;
+}): Promise<DurableOutboxRecord | null> {
- let saved = { ...record, uploads: [] as DurableOutboxRecord['uploads'] };
++ // Recovery may carry local-only slots or expired remote references. Delivery
++ // must materialize the retained bytes again after the new task is created.
++ let saved: DurableOutboxRecord = { ...record, refreshUploads: !!recovering, uploads: [] };
+ let committed = false;
+ try {
+ for (let slot = 0; slot < saved.item.attachmentSlots.length; slot++) {
+ const attachment = saved.item.attachmentSlots[slot];
+ if (!attachment) continue;
+ const source = getUploadedSource(attachment.id);
+ const oldSlot = recovering?.item.attachmentSlots.findIndex(a => a?.id === attachment.id);
+ const oldUpload = recovering?.uploads.find(u => u.slot === oldSlot);
+ if (source) saved.uploads.push(await retainOutboxFile(saved, slot, source));
+ else if (recovering && oldUpload) saved.uploads.push(await retainOutboxFile(saved, slot, {
+ ...oldUpload, uri: durableOutboxUploadUri(recovering, oldUpload),
+ }));
+ else if (outboxAttachmentNeedsLocalBytes(attachment)) {
+ throw new Error(i18n.t('session.screen.attachmentsNotCarriedBack', { count: 1 }));
+ }
+ }
+ if (!isCurrent()) return null;
+ if (recovering) {
+ const latest = getCurrentMobileOutboxRecords().find(r => r.item.clientId === saved.item.clientId
+ && r.item.sessionId === recovering.item.sessionId);
+ if (latest !== recovering || latest.prepared) throw new Error('OUTBOX_STALE_WRITE');
+ saved = await mobileDurableOutbox.update(latest, saved);
+ } else await mobileDurableOutbox.add(saved);
+ committed = true;
+ return saved;
+ } finally {
+ if (!committed) await removeRetainedOutboxFiles(saved).catch(() => undefined);
+ }
+}
diff --cc apps/mobile/src/session/returnNewSessionToEdit.ts
index 9e95270e5a,6123e259c9..cfbb90bee2
--- a/apps/mobile/src/session/returnNewSessionToEdit.ts
+++ b/apps/mobile/src/session/returnNewSessionToEdit.ts
@@@ -1,6 -1,6 +1,7 @@@
import { getMobileAuthOwner, isMobileAuthOwnerCurrent } from '@/auth/authOwnerGeneration';
import { i18n } from '@/i18n';
import { getCurrentMobileOutboxRecords, mobileDurableOutbox } from './mobileDurableOutbox';
++import { mergeNewSessionEditFollowUps } from './mergeNewSessionEditFollowUps';
import {
beginNewSessionReturnToEdit, markNewSessionDurableEditReady, getNewSessionCreationTask, prepareNewSessionCreationForEdit,
stashNewSessionDraftForEdit, type NewSessionCreationTask,
@@@ -19,7 -19,7 +20,9 @@@ export async function returnNewSessionT
const task = getNewSessionCreationTask(sessionId);
if (!ownerCurrent() || !isCurrent() || task?.deviceId !== deviceId) return;
if (task.readyForEdit && !task.returningToEdit) {
- onReady({ deviceId, deviceName: task.deviceName,
++ if (task.readyForEdit === 'durable') await mergeNewSessionEditFollowUps(sessionId, deviceId);
++ if (!ownerCurrent() || !isCurrent() || getNewSessionCreationTask(sessionId)?.deviceId !== deviceId) return;
+ await onReady({ deviceId, deviceName: task.deviceName,
...(task.readyForEdit === 'durable' ? { recoverySessionId: sessionId } : { editSessionId: sessionId }) });
return;
}
@@@ -36,13 -36,12 +39,14 @@@
&& record.item.sessionId === sessionId && record.creation);
if (durableFirst) {
await mobileDurableOutbox.update(durableFirst, {
- suspended: true, state: 'failed', error: i18n.t('session.screen.firstMessageNotSent'),
+ suspended: true, state: 'failed',
+ error: prepared.error || durableFirst.error || i18n.t('session.screen.firstMessageNotSent'),
creation: { ...durableFirst.creation!, editReady: true },
});
++ await mergeNewSessionEditFollowUps(sessionId, deviceId);
if (!taskCurrent()) return;
markNewSessionDurableEditReady(sessionId, deviceId);
- if (isCurrent()) onReady({ deviceId, deviceName: prepared.deviceName, recoverySessionId: sessionId });
+ if (isCurrent()) await onReady({ deviceId, deviceName: prepared.deviceName, recoverySessionId: sessionId });
return;
}
stashDraft(prepared);
diff --cc apps/mobile/src/session/useFailedCreationReturnToEdit.ts
index 0bf57df45f,0000000000..7efa0158dd
mode 100644,000000..100644
--- a/apps/mobile/src/session/useFailedCreationReturnToEdit.ts
+++ b/apps/mobile/src/session/useFailedCreationReturnToEdit.ts
@@@ -1,62 -1,0 +1,64 @@@
+import { useEffect, useRef } from 'react';
+import { getMobileAuthOwner, isMobileAuthOwnerCurrent } from '@/auth/authOwnerGeneration';
+import type { NewSessionCreationTask } from './newSessionCreation';
+import { returnNewSessionToEdit } from './returnNewSessionToEdit';
+
+type RecoveryOptions = Parameters<typeof returnNewSessionToEdit>[0];
+
+/** A failed creation has one next step: restore its draft in the new-task form. */
- export function useFailedCreationReturnToEdit({ task, focused, connectionEpoch, stashDraft, beforeNavigate, onReady, onError }: {
++export function useFailedCreationReturnToEdit({ task, focused, sending = false, connectionEpoch, stashDraft, beforeNavigate, onReady, onError }: {
+ task: NewSessionCreationTask | null;
+ focused: boolean;
++ /** A send already retaining/writing its bytes must settle before recovery reads the outbox. */
++ sending?: boolean;
+ connectionEpoch: number;
+ stashDraft: RecoveryOptions['stashDraft'];
+ beforeNavigate?: () => Promise<void>;
+ onReady: RecoveryOptions['onReady'];
+ onError: (error: unknown) => void;
+}) {
+ const callbacks = useRef({ stashDraft, beforeNavigate, onReady, onError });
+ callbacks.current = { stashDraft, beforeNavigate, onReady, onError };
+ const navigated = useRef<string | null>(null);
+ const sessionId = task?.sessionId;
+ const deviceId = task?.deviceId;
+ const failed = task?.status === 'create-failed';
+ const startedAt = task?.startedAt;
+ const readyForEdit = task?.readyForEdit;
+ const current = useRef({ sessionId, deviceId, startedAt, focused });
+ current.current = { sessionId, deviceId, startedAt, focused };
+ const mounted = useRef(false);
+ useEffect(() => {
+ mounted.current = true;
+ return () => { mounted.current = false; };
+ }, []);
+ useEffect(() => {
- if (!failed || !focused || !sessionId || !deviceId) return;
++ if (!failed || !focused || sending || !sessionId || !deviceId) return;
+ const identity = JSON.stringify([deviceId, sessionId, startedAt]);
+ if (navigated.current === identity) return;
+ const owner = getMobileAuthOwner();
+ const isCurrent = () => mounted.current && current.current.focused
+ && current.current.sessionId === sessionId && current.current.deviceId === deviceId
+ && current.current.startedAt === startedAt && isMobileAuthOwnerCurrent(owner);
+ void returnNewSessionToEdit({
+ sessionId, deviceId, isCurrent,
+ stashDraft: callbacks.current.stashDraft,
+ onReady: async params => {
+ if (!isCurrent() || navigated.current === identity) return;
+ navigated.current = identity;
+ try {
+ await callbacks.current.beforeNavigate?.();
+ if (isCurrent()) await callbacks.current.onReady(params);
+ else if (navigated.current === identity) navigated.current = null;
+ } catch (error) {
+ if (navigated.current === identity) navigated.current = null;
+ throw error;
+ }
+ },
+ }).catch(error => {
+ if (isCurrent()) callbacks.current.onError(error);
+ });
+ // Recovery itself continues after leaving. Re-entry (or restored connection)
+ // can resume the existing recovery; ordinary store updates never retry it.
- }, [sessionId, deviceId, failed, startedAt, focused, connectionEpoch, readyForEdit]);
++ }, [sessionId, deviceId, failed, startedAt, focused, sending, connectionEpoch, readyForEdit]);
+}
diff --cc apps/mobile/src/session/useNewSessionDraftRecovery.ts
index 0faeb618f8,0000000000..4e6a672355
mode 100644,000000..100644
--- a/apps/mobile/src/session/useNewSessionDraftRecovery.ts
+++ b/apps/mobile/src/session/useNewSessionDraftRecovery.ts
@@@ -1,64 -1,0 +1,74 @@@
+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';
++import { mergeNewSessionEditFollowUps } from './mergeNewSessionEditFollowUps';
+
+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 }: {
++export function useNewSessionDurableEdit({ sessionId, deviceId, owner, leaveForeignRecovery, onRestore, onError }: {
+ sessionId: string;
+ deviceId: string;
+ owner: MobileAuthOwnerGeneration;
+ leaveForeignRecovery: () => boolean;
+ onRestore: (record: CreationRecord) => void;
++ onError?: (error: unknown) => void;
+}) {
- const callbacks = useRef({ leaveForeignRecovery, onRestore });
- callbacks.current = { leaveForeignRecovery, onRestore };
++ const callbacks = useRef({ leaveForeignRecovery, onRestore, onError });
++ callbacks.current = { leaveForeignRecovery, onRestore, onError };
+ useEffect(() => {
+ if (callbacks.current.leaveForeignRecovery() || !sessionId) return;
+ let active = true;
+ let restored = false;
++ let merging = false;
+ let releaseEditClaim: (() => void) | undefined;
+ const restore = () => {
- if (!active || restored || !isMobileAuthOwnerCurrent(owner)) return;
++ if (!active || restored || merging || !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);
++ merging = true;
++ void mergeNewSessionEditFollowUps(sessionId, deviceId).then(saved => {
++ if (!active || !isMobileAuthOwnerCurrent(owner) || !saved?.creation || saved.prepared
++ || !getCurrentMobileOutboxRecords().includes(saved)) return;
++ restored = true;
++ callbacks.current.onRestore(saved as CreationRecord);
++ releaseEditClaim = completeNewSessionDurableEdit(sessionId, deviceId);
++ }).catch(error => {
++ if (active && isMobileAuthOwnerCurrent(owner)) callbacks.current.onError?.(error);
++ }).finally(() => { merging = false; });
+ };
+ 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]);
+}
diff --cc docs/dev-rules/mobile-development.md
index 9146b4194c,93acfb078d..e57c159c27
--- a/docs/dev-rules/mobile-development.md
+++ b/docs/dev-rules/mobile-development.md
@@@ -98,17 -98,10 +98,22 @@@ iOS 的系统选图器在确认后立�
### 任务入口与创建失败恢复
-- 来源未确认时不挂载远端任务内容,但必须显示读取状态和返回入口;读取失败、空记录或
+- 非本机发起的任务来源未确认时不挂载远端任务内容,但必须显示读取状态和返回入口;读取失败、空记录或
超时允许手动重读当前任务,不重置共享设备连接。账号或设备切换后忽略旧读取结果。
-- 本地创建进行中或失败时,来源门禁显示创建进度或失败原因;失败时直接提供重试和返回编辑,
- 不依赖尚不存在的远端任务记录。返回编辑复用 worktree 补偿和持久草稿恢复流程;
+- 本地新建任务立即显示乐观消息与输入框,不因远端来源尚未返回而显示整页等待卡。
+ 仅创建失败时自动带回草稿与附件并返回编辑,不提供重试、返回编辑等选择菜单;
+ 已建成任务的首条消息发送失败仍在原任务内恢复,不退回新建页。失败原因带到编辑页。
+ 自动跳转前同时保存当前输入框的未发送文字和已上传附件,保存成功才移交附件并清空旧输入框,
+ 避免卸载清理删除已交给草稿的文件;失败后的移交期间停止继续编辑,正常创建期间仍可输入。
++ 正常创建期间也允许继续发送。创建失败时先等当前发送保存落定,把同一账号、设备和任务的
++ 未投递后续消息按发送顺序合并,再追加输入框文字;后续附件字节经原发件箱留存,冷恢复与
++ 即时返回共用合并入口。合并内容与已纳入的消息 ID 一次保存后才清理原记录,清理中断后不
++ 重复合并;复制或保存失败保留原记录,删除或换账号后的迟到保存不得复活内容。重新提交
++ 沿现有附件刷新路径重新上传,不能将手机本地路径直接交给电脑。
+ 尚未关闭的相册、相机或文件选择器、未完成上传及粘贴占位统一通过附件 hook 的
+ `hasAttachmentInput()` 判断并告知,不把上传槽位数当作完整输入状态;选择器内数量未知,
+ 提示不猜测附件数量。超出托盘上限的附件也须告知,持久恢复同时保存这些告知。
+ 返回编辑复用 worktree 补偿和持久草稿恢复流程;
回收或保存失败保留原任务与草稿。回收开始后离页仍完成同账号的草稿恢复,
仅取消跳转;账号切换后停止旧账号操作,并移除旧代次的内存创建记录及同步阻挡,
避免切回原账号后阻塞发件箱恢复;保留持久发件箱草稿,不执行远端删除。