Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 统一失败创建草稿的恢复与编辑判据
Dashb2e6369f8e7b
diff --git a/apps/mobile/src/__tests__/newSessionCreationPersistence.test.ts b/apps/mobile/src/__tests__/newSessionCreationPersistence.test.tsindex 4d50d65972..0bed19146c 100644--- a/apps/mobile/src/__tests__/newSessionCreationPersistence.test.ts+++ b/apps/mobile/src/__tests__/newSessionCreationPersistence.test.ts@@ -701,6 +701,45 @@ async function saveFollowUpFixture(first: DurableOutboxRecord, pendingUpload = freturn record;}+// #6281 unit: retry-opened background failures lack editReady/cancelled.+// Existing recovery cases start with cancelledCreationDraft and miss this input.+// Exercise the shared production recovery + editing + cold reload, not a route copy.+it.each([false, true])('persists edits to a retry-opened creation (follow-up: %s)', async followUp => {+ const original = await saveDraftFixture();+ const first = await mobileDurableOutbox.update(original, { state: 'failed', suspended: true });+ if (followUp) await saveFollowUpFixture(first);+ const recovered = (await mergeNewSessionEditFollowUps(first.item.sessionId, 'pc'))!;+ expect(recovered.creation?.draft.firstMessage).toBe(followUp ? 'keep my input\n\nsecond message' : 'keep my input');+ const leave = completeNewSessionDurableEdit(first.item.sessionId, 'pc');+ expect(leave).toBeTypeOf('function');+ const edited = (await persistNewSessionDraftEdit(recovered, { firstMessage: 'remaining' }))!;+ await persistNewSessionDraftEdit(edited, { removeAttachmentId: 'photo' });+ leave!();+ await mobileDurableOutbox.activate('');+ await mobileDurableOutbox.activate(getMobileAuthOwner().accountKey);+ const restored = findNewSessionEditDraft('pc')!;+ expect(restored.creation?.draft.firstMessage).toBe('remaining');+ expect(restored.item.attachmentSlots.map(a => a?.id)).toEqual(followUp ? ['second-photo'] : []);+ if (followUp) await persistNewSessionDraftEdit(restored, { removeAttachmentId: 'second-photo' });+ await persistNewSessionDraftEdit(restored, { firstMessage: '' });+ await mobileDurableOutbox.activate('');+ await mobileDurableOutbox.activate(getMobileAuthOwner().accountKey);+ expect(findNewSessionEditDraft('pc')).toBeUndefined();+ expect(getCurrentMobileOutboxRecords()).toEqual([]);+});++it.each([+ { suspended: false }, { state: 'queued' as const }, { enqueueStarted: true },+ { prepared: {} as QueuedRemoteMessage }, { template: {} as QueuedRemoteMessage },+ { cancelRequested: true }, { cleanupOutcome: 'cancelled' as const }, { sendAtMs: 1 },+])('does not turn a non-editable creation into a recovery draft: %j', async patch => {+ const original = await saveDraftFixture();+ const first = await mobileDurableOutbox.update(original, { state: 'failed', suspended: true, ...patch });+ await expect(mergeNewSessionEditFollowUps(first.item.sessionId, 'pc')).resolves.toBeUndefined();+ expect(mobileDurableOutbox.getSnapshot()).toEqual([first]);+ expect(first.creation?.editReady).toBeUndefined();+});+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));diff --git a/apps/mobile/src/__tests__/useNewSessionDraftRecovery.test.tsx b/apps/mobile/src/__tests__/useNewSessionDraftRecovery.test.tsxindex 94de55fdb7..731e728185 100644--- a/apps/mobile/src/__tests__/useNewSessionDraftRecovery.test.tsx+++ b/apps/mobile/src/__tests__/useNewSessionDraftRecovery.test.tsx@@ -71,12 +71,12 @@ beforeEach(() => {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',+ uploads: [], error: 'Model unavailable', suspended: true,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,+ creation: { deviceName: 'PC', planModeArm: false, restorePermissionMode: null, editReady: true,draft: { agentKind: 'codex', workspaceKind: 'dialogue', model: 'model', effort: 'medium',permissionMode: 'auto', workingDir: '', providerId: 'openai', fastMode: false, firstMessage: 'Saved draft' } },}];@@ -224,7 +224,7 @@ it('uses the latest device after a route change while storage is pending', async// 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)(+it.each(['complete', 'unmount', 'owner-switch', 'save-fails', 'prepared', 'resumed', 'cancel-requested', 'unmarked'] as const)('settles follow-up consolidation before restoring the editor: %s', async outcome => {let resolve!: (record: DurableOutboxRecord) => void;let reject!: (error: Error) => void;@@ -238,6 +238,9 @@ it.each(['complete', 'unmount', 'owner-switch', 'save-fails', 'prepared'] as conif (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']>;+ if (outcome === 'resumed') outbox.records[0].suspended = false;+ if (outcome === 'cancel-requested') outbox.records[0].cancelRequested = true;+ if (outcome === 'unmarked') outbox.records[0].creation!.editReady = undefined;await act(async () => {if (outcome === 'save-fails') reject(new Error('save failed'));else resolve(outbox.records[0]);diff --git a/apps/mobile/src/session/durableOutbox.ts b/apps/mobile/src/session/durableOutbox.tsindex 71d4a090f7..83b01053fe 100644--- a/apps/mobile/src/session/durableOutbox.ts+++ b/apps/mobile/src/session/durableOutbox.ts@@ -77,7 +77,7 @@ export function isDurableOutboxSettled(record: DurableOutboxRecord): boolean {export function isDurableCreationDraft(record: DurableOutboxRecord): boolean {return record.suspended === true && record.state === 'failed'&& !!(record.creation?.editReady || record.creation?.cancelled)- && !record.prepared && !record.enqueueStarted && record.sendAtMs === undefined+ && !record.prepared && !record.template && !record.enqueueStarted && record.sendAtMs === undefined&& !record.cancelRequested && !isDurableOutboxSettled(record);}diff --git a/apps/mobile/src/session/mergeNewSessionEditFollowUps.ts b/apps/mobile/src/session/mergeNewSessionEditFollowUps.tsindex 521a2d5201..4e8737e814 100644--- a/apps/mobile/src/session/mergeNewSessionEditFollowUps.ts+++ b/apps/mobile/src/session/mergeNewSessionEditFollowUps.ts@@ -2,7 +2,7 @@ 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 { isDurableCreationDraft, isDurableOutboxUnsent, type DurableOutboxRecord } from './durableOutbox';import { discardOutboxUploads, getCurrentMobileOutboxRecords, mobileDurableOutbox } from './mobileDurableOutbox';import type { RemoteSerializedAttachment } from './types';@@ -18,11 +18,21 @@ export async function mergeNewSessionEditFollowUps(sessionId: string, deviceId: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;+ if (!first?.creation) return;+ let creation = first.creation;+ // Every editor entry, including retry after background recovery, must own a+ // writable draft before exposing content. Normalize the existing marker here;+ // presentation, claims and subsequent edits use the same store predicate.+ if (!isDurableCreationDraft(first)) {+ creation = { ...creation, editReady: true };+ if (!isDurableCreationDraft({ ...first, creation })) return;+ first = await mobileDurableOutbox.update(first, { creation });+ guard();+ }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 copied = new Set(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: [] };@@ -30,7 +40,7 @@ export async function mergeNewSessionEditFollowUps(sessionId: string, deviceId:try {const attachments = [...first.item.attachmentSlots];const slotMeta = [...first.item.slotMeta];- const text = [first.creation.draft.firstMessage];+ const text = [creation.draft.firstMessage];let omitted = 0;for (const record of pending) {text.push(record.item.quotesEncoded ? stripChatQuoteMarkerLines(record.item.text) : record.item.text);@@ -68,9 +78,9 @@ export async function mergeNewSessionEditFollowUps(sessionId: string, deviceId:guard();const firstMessage = text.filter(Boolean).join('\n\n');first = await mobileDurableOutbox.update(first, {- creation: { ...first.creation, draft: { ...first.creation.draft, firstMessage },+ creation: { ...creation, draft: { ...creation.draft, firstMessage },mergedFollowUpClientIds: [...copied, ...pending.map(r => r.item.clientId)],- notice: [first.creation.notice, omitted ? i18n.t('session.screen.attachmentsNotCarriedBack', { count: omitted }) : null]+ notice: [creation.notice, omitted ? i18n.t('session.screen.attachmentsNotCarriedBack', { count: omitted }) : null].filter(Boolean).join('\n') || undefined,},uploads: [...first.uploads, ...copies.uploads],diff --git a/apps/mobile/src/session/useNewSessionDraftRecovery.ts b/apps/mobile/src/session/useNewSessionDraftRecovery.tsindex bc75776af2..71dc14be7b 100644--- a/apps/mobile/src/session/useNewSessionDraftRecovery.ts+++ b/apps/mobile/src/session/useNewSessionDraftRecovery.ts@@ -1,6 +1,6 @@import { useCallback, useEffect, useRef } from 'react';import { isMobileAuthOwnerCurrent, type MobileAuthOwnerGeneration } from '@/auth/authOwnerGeneration';-import type { DurableOutboxRecord } from './durableOutbox';+import { isDurableCreationDraft, type DurableOutboxRecord } from './durableOutbox';import { getCurrentMobileOutboxRecords, mobileDurableOutbox } from './mobileDurableOutbox';import { completeNewSessionDurableEdit, findNewSessionEditDraft, subscribeNewSessionCreationTasks } from './newSessionCreation';import { mergeNewSessionEditFollowUps } from './mergeNewSessionEditFollowUps';@@ -50,7 +50,7 @@ export function useNewSessionDurableEdit({ sessionId, deviceId, owner, getToken,if (!record?.creation || record.prepared) return;merging = true;void mergeNewSessionEditFollowUps(sessionId, deviceId, callbacks.current.getToken).then(saved => {- if (!active || !isMobileAuthOwnerCurrent(owner) || !saved?.creation || saved.prepared+ if (!active || !isMobileAuthOwnerCurrent(owner) || !saved?.creation || !isDurableCreationDraft(saved)|| !getCurrentMobileOutboxRecords().includes(saved)) return;restored = true;editingRecord.current = saved;diff --git a/docs/dev-rules/mobile-development.md b/docs/dev-rules/mobile-development.mdindex 52665a4994..cb7e903586 100644--- a/docs/dev-rules/mobile-development.md+++ b/docs/dev-rules/mobile-development.md@@ -125,6 +125,8 @@ iOS 的系统选图器在确认后立即把选中项交给现有附件队列。持久发件箱保存完成后同样保留失败任务与恢复入口,直到匹配账号、设备和任务的新建表单实际恢复内容才清理任务;离页重进不重复回收或保存,也不解除暂停自动发送。返回编辑意图写入持久发件箱;退出编辑或应用重启后保留草稿,不重建任务列表行,不启动创建管线。+ 即时返回、冷恢复和任务内重试进入表单共用发件箱的可编辑判据;后台失败记录缺少编辑标记时,+ 由共享恢复入口先持久补齐,再展示内容。投递中、已投递、取消或清理中的记录不能转成编辑草稿。恢复后用户修改文字或移除附件,同步更新原恢复记录;文字和附件清空后删除记录及其附件副本,离页、重启和迟到的旧编辑不得恢复已删除内容。再次提交先等待这些编辑落盘;离页也须等已发起的编辑结算后才释放原领取,空白页监听同一领取与发件箱通知,只恢复已提交版本。