Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 保留创建失败原因并通过生产入口验证草稿重提
Dash2aefe18736c2
diff --cc apps/mobile/app/sessions/new.tsxindex 7bb6b53b82,ec19ed5f79..0c0ad46184--- a/apps/mobile/app/sessions/new.tsx+++ b/apps/mobile/app/sessions/new.tsx@@@ -5,7 -5,7 +5,7 @@@ import { completePrecreatedWorktreeRecoimport { outboxCreationRetryIdentity } from '@/session/cancelledCreationDraft';import { isRemoteTaskSuggestionId } from '@/session/remoteTaskSuggestionsModel';import { mobileDurableOutbox, getCurrentMobileOutboxRecords } from '@/session/mobileDurableOutbox';--import { retainOutboxFile, durableOutboxUploadUri, removeRetainedOutboxFiles, outboxAttachmentNeedsLocalBytes } from '@/session/durableOutboxFiles';++import { persistNewSessionCreationDraft } from '@/session/persistNewSessionCreationDraft';import { buildOutboxItem, createOutboxClientId } from '@/session/sessionOutbox';import type { DurableOutboxRecord } from '@/session/durableOutbox';import { stripTrailingPathSeparators } from '@cindy/maker-shared/path-text';@@@ -4936,7 -4931,7 +4936,7 @@@ export default function NewRemoteSessioconst useDurableCreation = legacyPlanRestore === null;if (recovering && !useDurableCreation) throw new Error(t('session.outbox.legacyPlanRecovery'));if (useDurableCreation) {-- let firstRecord: DurableOutboxRecord = {++ const firstRecord: DurableOutboxRecord = {version: 1, accountId: authOwnerAtCreate.accountKey, deviceId: deviceIdSnapshot,...(recoveryIdentity ? { storageSessionId: recoveryIdentity.storageSessionId } : {}),createdAt: recovering?.createdAt ?? Date.now(), state: recovering ? 'failed' : 'queued',@@@ -4954,30 -4949,30 +4954,12 @@@readyPreviews: sendAttachments.map((a) => attachmentPreviews[a.id] ?? null), claimedUploads: [],}),};-- let filesCommitted = false;-- try {-- for (let slot = 0; slot < sendAttachments.length; slot++) {-- const attachment = sendAttachments[slot];-- 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) firstRecord.uploads.push(await retainOutboxFile(firstRecord, slot, source));-- else if (recovering && oldUpload) firstRecord.uploads.push(await retainOutboxFile(firstRecord, slot, {-- ...oldUpload, uri: durableOutboxUploadUri(recovering, oldUpload),-- }));-- else if (outboxAttachmentNeedsLocalBytes(attachment)) throw new Error(t('session.screen.attachmentsNotCarriedBack', { count: 1 }));-- }-- if (!isCurrentOwner() || !ensureDeviceAlive()) return;-- if (recovering) {-- const latest = getCurrentMobileOutboxRecords().find((r) => r.item.clientId === firstMessageClientId && r.item.sessionId === recovering.item.sessionId);-- if (latest !== recovering || latest.prepared) throw new Error('OUTBOX_STALE_WRITE');-- firstRecord = await mobileDurableOutbox.update(latest, firstRecord);-- } else await mobileDurableOutbox.add(firstRecord);-- filesCommitted = true;-- } finally {-- if (!filesCommitted) await removeRetainedOutboxFiles(firstRecord).catch(() => undefined);-- }-- outboxRecoveryRef.current = firstRecord;++ const saved = await persistNewSessionCreationDraft({++ record: firstRecord, recovering, getUploadedSource,++ isCurrent: () => isCurrentOwner() && ensureDeviceAlive(),++ });++ if (!saved) return;++ outboxRecoveryRef.current = saved;if (!isCurrentOwner() || !ensureDeviceAlive()) return;releaseUploadedSources(sendAttachments.map((a) => a.id));}diff --cc apps/mobile/src/__tests__/newSessionCreation.test.tsindex daf7876281,bcebea61b1..27eebe6ffd--- a/apps/mobile/src/__tests__/newSessionCreation.test.ts+++ b/apps/mobile/src/__tests__/newSessionCreation.test.ts@@@ -323,7 -283,7 +323,9 @@@ describe('newSessionCreation pipeline'completeNewSessionDurableEdit('s1', 'dev-1');expect(getNewSessionCreationTask('s1')).toBeNull();}-- expect(editOutbox.update).toHaveBeenCalledWith(record, expect.objectContaining({ suspended: true, state: 'failed' }));++ expect(editOutbox.update).toHaveBeenCalledWith(record, expect.objectContaining({++ suspended: true, state: 'failed', error: '[MODEL_UNAVAILABLE] unavailable',++ }));expect(record.item.text).toBe(DRAFT.firstMessage);expect(record.creation?.draft).toEqual(DRAFT);expect(drainStashedNewSessionDraft('s1', 'dev-1')).toBeNull();diff --cc apps/mobile/src/__tests__/newSessionCreationPersistence.test.tsindex b5b1f586e2,34facd3ae5..af253893bd--- a/apps/mobile/src/__tests__/newSessionCreationPersistence.test.ts+++ b/apps/mobile/src/__tests__/newSessionCreationPersistence.test.ts@@@ -5,10 -5,8 +5,12 @@@ import { beforeEach, expect, it, vi } fimport { 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';const disk = vi.hoisted(() => ({ data: new Map<string, string>(), fail: false }));vi.mock('@react-native-async-storage/async-storage', () => ({ default: {@@@ -97,9 -75,9 +99,9 @@@ function harness(previous: DurableOutboplanModeCapability: false, planModeDraftOn: false,holdNewSessionCreationDraft, holdPrecreatedWorktreeRegistration: () => () => {},sendAttachments: [{ id: 'photo', path: 'oss://photo', name: 'photo.png', ext: 'png', size: 3, category: 'image', mimeType: 'image/png' }],- attachmentPreviews: {}, getUploadedSource: () => ({ uri: 'file:///photo.png' }),- retainOutboxFile: vi.fn(async () => ({ slot: 0, fileName: 'slot-0.png', name: 'photo.png', size: 3, kind: 'image' })),- removeRetainedOutboxFiles: vi.fn(async () => {}), releaseUploadedSources: vi.fn(),+ attachmentPreviews: {}, getUploadedSource: (_id: string): MobileLocalAttachmentUploadCandidate | undefined => ({ uri: 'file:///photo.png', name: 'photo.png', size: 3, kind: 'image' }),- retainOutboxFile, durableOutboxUploadUri,++ persistNewSessionCreationDraft,+ removeRetainedOutboxFiles, releaseUploadedSources: vi.fn(),outboxAttachmentNeedsLocalBytes: () => true,registerPendingPrecreatedWorktree: vi.fn(async (..._args: Parameters<typeof registerPendingPrecreatedWorktree>) => true), forgetPendingPrecreatedWorktree: vi.fn(),buildWorktreeCreateRequest: (input: unknown) => input,@@@ -401,137 -378,3 +403,176 @@@ 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 => {- await harness().run();- const original = getCurrentMobileOutboxRecords()[0];++ 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 () => {- await harness().run();- const original = getCurrentMobileOutboxRecords()[0];++ 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 => {- await harness().run();- const original = getCurrentMobileOutboxRecords()[0];++ 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 resubmit = harness(restored);- resubmit.bindings.sendAttachments = [...restored.item.attachmentSlots.filter(file => file !== null)];- resubmit.bindings.getUploadedSource = () => undefined; // Old chat has unmounted.- await expect(resubmit.run()).resolves.toBeDefined();++ 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 => {- await harness().run();- const original = getCurrentMobileOutboxRecords()[0];++ 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 harness().run();++ 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();++ 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');++ setMobileAuthOwner(null);++ await mobileDurableOutbox.activate('');++ setMobileAuthOwner('alice', 'global');++ await mobileDurableOutbox.activate(getMobileAuthOwner().accountKey);++ expect(findNewSessionEditDraft('pc')?.error).toBe('Provider setup required');++});diff --cc apps/mobile/src/session/persistNewSessionCreationDraft.tsindex 0000000000,0000000000..8ca449363cnew file mode 100644--- /dev/null+++ b/apps/mobile/src/session/persistNewSessionCreationDraft.ts@@@ -1,0 -1,0 +1,43 @@@++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'] };++ 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.tsindex 8b0b53f90e,6123e259c9..9e95270e5a--- a/apps/mobile/src/session/returnNewSessionToEdit.ts+++ b/apps/mobile/src/session/returnNewSessionToEdit.ts@@@ -36,7 -36,7 +36,8 @@@ export async function returnNewSessionT&& 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 },});if (!taskCurrent()) return;