Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 等待恢复草稿编辑结算并回收超限上传
Dash43d34dc656c8
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex 94262141c5..18f0b6506d 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -4104,6 +4104,7 @@ function SessionScreenContent() {// (新桌面有 clientId 幂等去重,重复风险已兜)。const creationScreenFocused = useIsFocused();useFailedCreationReturnToEdit({+ getToken: auth.getAccessToken,task: creationTask?.deviceId === deviceId ? creationTask : null,focused: creationScreenFocused,sending,diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsxindex 170f9e1f94..9967ee3bdf 100644--- a/apps/mobile/app/sessions/new.tsx+++ b/apps/mobile/app/sessions/new.tsx@@ -857,6 +857,7 @@ export default function NewRemoteSessionScreen() {}, [router]);const { edit: editRecoveredDraft, flush: flushRecoveredDraft } = useNewSessionDurableEdit({sessionId: String(params.recoverySessionId ?? ''), deviceId: routeDeviceId, owner: outboxOwner,+ getToken: auth.getAccessToken,leaveForeignRecovery: leaveForeignOutboxRecovery,onError: error => setError(formatRemoteError(error)),onEdited: record => { outboxRecoveryRef.current = record; },diff --git a/apps/mobile/src/__tests__/newSessionCreationPersistence.test.ts b/apps/mobile/src/__tests__/newSessionCreationPersistence.test.tsindex 027227dabe..4d50d65972 100644--- a/apps/mobile/src/__tests__/newSessionCreationPersistence.test.ts+++ b/apps/mobile/src/__tests__/newSessionCreationPersistence.test.ts@@ -12,6 +12,7 @@ import { buildOutboxItem } from '../session/sessionOutbox';import { persistNewSessionCreationDraft, persistNewSessionDraftEdit } from '../session/persistNewSessionCreationDraft';import { returnNewSessionToEdit } from '../session/returnNewSessionToEdit';import { mergeNewSessionEditFollowUps } from '../session/mergeNewSessionEditFollowUps';+import { discardMobileUploadedAttachment } from '../session/mobileAttachmentUpload';import { createDurableOutboxDelivery } from '../session/durableOutboxDelivery';import type { InputProjection, QueuedRemoteMessage } from '../session/types';@@ -81,6 +82,7 @@ beforeEach(async () => {await mobileDurableOutbox.activate('');disk.data.clear();disk.fail = false;+ vi.mocked(discardMobileUploadedAttachment).mockClear();disk.failRemove = false;files.retained.clear();files.sequence = 0;@@ -773,19 +775,33 @@ it('finishes interrupted source removal after reload without duplicating mergedexpect(getCurrentMobileOutboxRecords()).toEqual([saved]);});-it('reports overflow from multiple messages and refuses records with delivery evidence', async () => {+it.each([false, true])('reclaims only unretained overflow uploads after commit (interrupted: %s)', async interrupted => {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` })) } };+ id: `file-${i}`, path: i === 20 ? first.item.attachmentSlots[0]!.path+ : i === 19 ? 'cindy-oss-attach://unused-overflow' : `/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');+ disk.fail = true;+ await expect(mergeNewSessionEditFollowUps(first.item.sessionId, 'pc', async () => 'test-token')).rejects.toThrow('disk unavailable');+ expect(discardMobileUploadedAttachment).not.toHaveBeenCalled();+ disk.fail = false;+ if (interrupted) {+ disk.failRemove = true;+ await expect(mergeNewSessionEditFollowUps(first.item.sessionId, 'pc', async () => 'test-token')).rejects.toThrow('remove unavailable');+ expect(discardMobileUploadedAttachment).not.toHaveBeenCalled();+ disk.failRemove = false;+ await mobileDurableOutbox.activate('');+ await mobileDurableOutbox.activate(getMobileAuthOwner().accountKey);+ }+ const saved = await mergeNewSessionEditFollowUps(first.item.sessionId, 'pc', async () => 'test-token');expect(saved?.item.attachmentSlots).toHaveLength(20);+ expect(vi.mocked(discardMobileUploadedAttachment).mock.calls.map(([a]) => a.path)).toEqual(['cindy-oss-attach://unused-overflow']);expect(saved?.creation?.notice).toBeTruthy();expect(saved?.creation?.draft.firstMessage).toBe('keep my input\n\nkeep all text');});diff --git a/apps/mobile/src/__tests__/newSessionWorkspaceEffects.test.tsx b/apps/mobile/src/__tests__/newSessionWorkspaceEffects.test.tsxindex 4032ae2376..85d58a0b14 100644--- a/apps/mobile/src/__tests__/newSessionWorkspaceEffects.test.tsx+++ b/apps/mobile/src/__tests__/newSessionWorkspaceEffects.test.tsx@@ -87,6 +87,7 @@ const bindingNames = ['saveNewSessionPreferences', 'drainStashedNewSessionDraft', 'loadBrowsePath', 'setDevicePickerOpen','setAttachmentError', 'setBrowseOpen', 'setBrowseError','setShowHiddenDirectories', 'setWorkspacePickerOpen',+ 'editRecoveredDraft', 'creatingRef', 'voiceDictionaryLearningTrackerRef',];const readRouteString = source.statements.find((node): node is ts.FunctionDeclaration =>ts.isFunctionDeclaration(node) && node.name?.text === 'readRouteString');@@ -117,6 +118,7 @@ function mountWorkspace(options: { initialWorkingDir?: string; restoredKind?: Neconst deviceOptions = [{ deviceId: 'a', name: 'A' }, { deviceId: 'b', name: 'B' }];const initialWorkingDir = options.initialWorkingDir ?? null;const bindings = {+ editRecoveredDraft: vi.fn(), creatingRef: { current: false }, voiceDictionaryLearningTrackerRef: { current: null },isRemoteTaskSuggestionId, params: { suggestion: options.suggestion, draft: options.routeDraft, editSessionId: options.restoredKind ? 'failed-task' : undefined }, t: i18n.getFixedT('zh-CN'),useState, useRef, useMemo, useEffect, useCallback, DEFAULT_NEW_SESSION_DRAFT,pickNewSessionDefaultDevice, buildRecentWorkspaceOptions,diff --git a/apps/mobile/src/__tests__/useNewSessionDraftRecovery.test.tsx b/apps/mobile/src/__tests__/useNewSessionDraftRecovery.test.tsxindex 27595ebd3f..94de55fdb7 100644--- a/apps/mobile/src/__tests__/useNewSessionDraftRecovery.test.tsx+++ b/apps/mobile/src/__tests__/useNewSessionDraftRecovery.test.tsx@@ -24,6 +24,10 @@ vi.mock('@/session/mobileDurableOutbox', () => ({vi.mock('@/session/newSessionCreation', () => ({completeNewSessionDurableEdit: outbox.claim,findNewSessionEditDraft: outbox.find,+ subscribeNewSessionCreationTasks: (listener: () => void) => {+ outbox.listeners.add(listener);+ return () => outbox.listeners.delete(listener);+ },}));vi.mock('@/session/mergeNewSessionEditFollowUps', () => ({ mergeNewSessionEditFollowUps: outbox.merge }));vi.mock('@/session/persistNewSessionCreationDraft', () => ({ persistNewSessionDraftEdit: outbox.saveEdit }));@@ -244,3 +248,37 @@ it.each(['complete', 'unmount', 'owner-switch', 'save-fails', 'prepared'] as conelse expect(container.textContent).not.toContain('Saved draft');},);++// #6281: leaving during a delete must not let a blank form claim the old revision.+it.each(['edited', 'cleared', 'failed'] as const)('keeps the edit claim through pending persistence: %s', async outcome => {+ let claimed = false;+ outbox.claim.mockImplementation(() => {+ claimed = true;+ return () => { claimed = false; outbox.release(); for (const listener of outbox.listeners) listener(); };+ });+ outbox.find.mockImplementation(() => claimed ? undefined : outbox.records[0]);+ await renderEdit();+ await act(async () => ready());+ let finish!: (record: DurableOutboxRecord | null) => void;+ let fail!: (error: Error) => void;+ outbox.saveEdit.mockReturnValueOnce(new Promise((resolve, reject) => { finish = resolve; fail = reject; }));+ editorActions.edit({ firstMessage: 'remaining text' });+ await renderBlank();+ expect(outbox.release).not.toHaveBeenCalled();+ expect(container.textContent).toBe('');+ await act(async () => {+ if (outcome === 'failed') { fail(new Error('disk unavailable')); return; }+ const record = outbox.records[0];+ outbox.records = outcome === 'cleared' ? [] : [{ ...record, creation: { ...record.creation!,+ draft: { ...record.creation!.draft, firstMessage: 'remaining text' } } }];+ for (const listener of outbox.listeners) listener();+ expect(container.textContent).toBe('');+ finish(outbox.records[0] ?? null);+ });+ expect(outbox.release).toHaveBeenCalledOnce();+ expect(container.textContent).toBe(outcome === 'cleared' ? '' : 'device/task');+ if (outcome === 'edited') {+ await renderEdit();+ expect(container.textContent).toBe('remaining textModel unavailableEdit');+ }+});diff --git a/apps/mobile/src/session/mergeNewSessionEditFollowUps.ts b/apps/mobile/src/session/mergeNewSessionEditFollowUps.tsindex 627233d5f4..521a2d5201 100644--- a/apps/mobile/src/session/mergeNewSessionEditFollowUps.ts+++ b/apps/mobile/src/session/mergeNewSessionEditFollowUps.ts@@ -3,11 +3,11 @@ import { getMobileAuthOwner, isMobileAuthOwnerCurrent } from '@/auth/authOwnerGeimport { i18n } from '@/i18n';import { categorizeMobileAttachment, extractRemoteFileExt, mergeAttachmentsWithinLimit, mimeTypeForMobileAttachment } from './attachments';import { isDurableOutboxUnsent, type DurableOutboxRecord } from './durableOutbox';-import { getCurrentMobileOutboxRecords, mobileDurableOutbox } from './mobileDurableOutbox';+import { discardOutboxUploads, 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> {+export async function mergeNewSessionEditFollowUps(sessionId: string, deviceId: string, getToken: () => Promise<string | null> = async () => null): 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.@@ -84,7 +84,13 @@ export async function mergeNewSessionEditFollowUps(sessionId: string, deviceId: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.+ // Only references retained by the committed parent changed ownership.+ // Derive unused references from both records so interrupted cleanup can+ // finish on cold recovery without another ledger or a dropped-ID list.+ discardOutboxUploads(record, owner, getToken, record.item.attachmentSlots.filter(+ (attachment): attachment is RemoteSerializedAttachment => attachment !== null+ && !first!.item.attachmentSlots.some(kept => kept?.path === attachment.path),+ ));await removeOutboxFiles(record).catch(() => undefined);}return first;diff --git a/apps/mobile/src/session/newSessionCreation.ts b/apps/mobile/src/session/newSessionCreation.tsindex fa3005ed2b..0470a89c3a 100644--- a/apps/mobile/src/session/newSessionCreation.ts+++ b/apps/mobile/src/session/newSessionCreation.ts@@ -704,7 +704,7 @@ export function shouldBlockSessionSync(sessionId: string): boolean {return status === 'running' || status === 'create-failed';}-function subscribeTasks(callback: () => void): () => void {+export function subscribeNewSessionCreationTasks(callback: () => void): () => void {subs.add(callback);const offOutbox = mobileDurableOutbox.subscribe(callback);return () => {@@ -726,7 +726,7 @@ function getTaskSnapshot(sessionId: string): NewSessionCreationTask | null {/** 会话页订阅本会话的创建 task(null = 无 task / 已完成)。 */export function useNewSessionCreationTask(sessionId: string): NewSessionCreationTask | null {- return useSyncExternalStore(subscribeTasks, () => getTaskSnapshot(sessionId));+ return useSyncExternalStore(subscribeNewSessionCreationTasks, () => getTaskSnapshot(sessionId));}// ---------------------------------------------------------------------------diff --git a/apps/mobile/src/session/returnNewSessionToEdit.ts b/apps/mobile/src/session/returnNewSessionToEdit.tsindex cfbb90bee2..6f8cbc8400 100644--- a/apps/mobile/src/session/returnNewSessionToEdit.ts+++ b/apps/mobile/src/session/returnNewSessionToEdit.ts@@ -8,9 +8,10 @@ import {} from './newSessionCreation';/** Shared by both entry screens; finish recovery even if the initiating screen leaves. */-export async function returnNewSessionToEdit({ sessionId, deviceId, isCurrent, onReady, stashDraft = stashNewSessionDraftForEdit }: {+export async function returnNewSessionToEdit({ sessionId, deviceId, isCurrent, onReady, getToken, stashDraft = stashNewSessionDraftForEdit }: {sessionId: string;deviceId: string;+ getToken?: () => Promise<string | null>;isCurrent: () => boolean;onReady: (params: { deviceId: string; deviceName: string; recoverySessionId?: string; editSessionId?: string }) => void | Promise<void>;stashDraft?: (task: NewSessionCreationTask) => void;@@ -20,7 +21,7 @@ export async function returnNewSessionToEdit({ sessionId, deviceId, isCurrent, oconst task = getNewSessionCreationTask(sessionId);if (!ownerCurrent() || !isCurrent() || task?.deviceId !== deviceId) return;if (task.readyForEdit && !task.returningToEdit) {- if (task.readyForEdit === 'durable') await mergeNewSessionEditFollowUps(sessionId, deviceId);+ if (task.readyForEdit === 'durable') await mergeNewSessionEditFollowUps(sessionId, deviceId, getToken);if (!ownerCurrent() || !isCurrent() || getNewSessionCreationTask(sessionId)?.deviceId !== deviceId) return;await onReady({ deviceId, deviceName: task.deviceName,...(task.readyForEdit === 'durable' ? { recoverySessionId: sessionId } : { editSessionId: sessionId }) });@@ -43,7 +44,7 @@ export async function returnNewSessionToEdit({ sessionId, deviceId, isCurrent, oerror: prepared.error || durableFirst.error || i18n.t('session.screen.firstMessageNotSent'),creation: { ...durableFirst.creation!, editReady: true },});- await mergeNewSessionEditFollowUps(sessionId, deviceId);+ await mergeNewSessionEditFollowUps(sessionId, deviceId, getToken);if (!taskCurrent()) return;markNewSessionDurableEditReady(sessionId, deviceId);if (isCurrent()) await onReady({ deviceId, deviceName: prepared.deviceName, recoverySessionId: sessionId });diff --git a/apps/mobile/src/session/useFailedCreationReturnToEdit.ts b/apps/mobile/src/session/useFailedCreationReturnToEdit.tsindex 7efa0158dd..d9124b3c7f 100644--- a/apps/mobile/src/session/useFailedCreationReturnToEdit.ts+++ b/apps/mobile/src/session/useFailedCreationReturnToEdit.ts@@ -6,19 +6,20 @@ 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, sending = false, connectionEpoch, stashDraft, beforeNavigate, onReady, onError }: {+export function useFailedCreationReturnToEdit({ task, focused, sending = false, connectionEpoch, getToken, 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;+ getToken?: RecoveryOptions['getToken'];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 callbacks = useRef({ getToken, stashDraft, beforeNavigate, onReady, onError });+ callbacks.current = { getToken, stashDraft, beforeNavigate, onReady, onError };const navigated = useRef<string | null>(null);const sessionId = task?.sessionId;const deviceId = task?.deviceId;@@ -41,7 +42,7 @@ export function useFailedCreationReturnToEdit({ task, focused, sending = false,&& current.current.sessionId === sessionId && current.current.deviceId === deviceId&& current.current.startedAt === startedAt && isMobileAuthOwnerCurrent(owner);void returnNewSessionToEdit({- sessionId, deviceId, isCurrent,+ sessionId, deviceId, isCurrent, getToken: callbacks.current.getToken,stashDraft: callbacks.current.stashDraft,onReady: async params => {if (!isCurrent() || navigated.current === identity) return;diff --git a/apps/mobile/src/session/useNewSessionDraftRecovery.ts b/apps/mobile/src/session/useNewSessionDraftRecovery.tsindex d98c2c9dbb..bc75776af2 100644--- a/apps/mobile/src/session/useNewSessionDraftRecovery.ts+++ b/apps/mobile/src/session/useNewSessionDraftRecovery.ts@@ -2,24 +2,25 @@ import { useCallback, 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 { completeNewSessionDurableEdit, findNewSessionEditDraft, subscribeNewSessionCreationTasks } from './newSessionCreation';import { mergeNewSessionEditFollowUps } from './mergeNewSessionEditFollowUps';import { persistNewSessionDraftEdit, type NewSessionDraftEdit } from './persistNewSessionCreationDraft';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, onEdited, onError }: {+export function useNewSessionDurableEdit({ sessionId, deviceId, owner, getToken, leaveForeignRecovery, onRestore, onEdited, onError }: {sessionId: string;deviceId: string;owner: MobileAuthOwnerGeneration;+ getToken?: () => Promise<string | null>;leaveForeignRecovery: () => boolean;onRestore: (record: CreationRecord) => void;onEdited?: (record: DurableOutboxRecord | null) => void;onError?: (error: unknown) => void;}) {- const callbacks = useRef({ leaveForeignRecovery, onRestore, onEdited, onError });- callbacks.current = { leaveForeignRecovery, onRestore, onEdited, onError };+ const callbacks = useRef({ getToken, leaveForeignRecovery, onRestore, onEdited, onError });+ callbacks.current = { getToken, leaveForeignRecovery, onRestore, onEdited, onError };const editingRecord = useRef<DurableOutboxRecord | null>(null);const pendingEdit = useRef<Promise<unknown>>(Promise.resolve());const edit = useCallback((change: NewSessionDraftEdit) => {@@ -48,7 +49,7 @@ export function useNewSessionDurableEdit({ sessionId, deviceId, owner, leaveFore&& r.accountId === owner.accountKey && r.deviceId === deviceId);if (!record?.creation || record.prepared) return;merging = true;- void mergeNewSessionEditFollowUps(sessionId, deviceId).then(saved => {+ void mergeNewSessionEditFollowUps(sessionId, deviceId, callbacks.current.getToken).then(saved => {if (!active || !isMobileAuthOwnerCurrent(owner) || !saved?.creation || saved.prepared|| !getCurrentMobileOutboxRecords().includes(saved)) return;restored = true;@@ -61,7 +62,16 @@ export function useNewSessionDurableEdit({ sessionId, deviceId, owner, leaveFore};const unsubscribe = mobileDurableOutbox.subscribe(restore);void mobileDurableOutbox.ready().then(restore);- return () => { active = false; editingRecord.current = null; pendingEdit.current = Promise.resolve(); unsubscribe(); releaseEditClaim?.(); };+ return () => {+ active = false;+ editingRecord.current = null;+ const pending = pendingEdit.current;+ pendingEdit.current = Promise.resolve();+ unsubscribe();+ // Keep the existing claim until the last serialized edit settles. A new+ // blank form must not restore a revision the user has just deleted.+ void pending.then(() => releaseEditClaim?.(), () => releaseEditClaim?.());+ };}, [sessionId, deviceId, owner]);return { edit, flush };}@@ -87,7 +97,7 @@ export function useAutoResumeNewSessionDraft({ enabled, deviceId, workingDir, owactive = false;callbacks.current.onResume({ recoverySessionId: saved.item.sessionId, deviceId: saved.deviceId });};- const unsubscribe = mobileDurableOutbox.subscribe(resume);+ const unsubscribe = subscribeNewSessionCreationTasks(resume);void mobileDurableOutbox.ready().then(resume);return () => { active = false; unsubscribe(); };}, [enabled, deviceId, workingDir, owner]);diff --git a/docs/dev-rules/mobile-development.md b/docs/dev-rules/mobile-development.mdindex dd2a114aa4..52665a4994 100644--- a/docs/dev-rules/mobile-development.md+++ b/docs/dev-rules/mobile-development.md@@ -126,7 +126,10 @@ iOS 的系统选图器在确认后立即把选中项交给现有附件队列。表单实际恢复内容才清理任务;离页重进不重复回收或保存,也不解除暂停自动发送。返回编辑意图写入持久发件箱;退出编辑或应用重启后保留草稿,不重建任务列表行,不启动创建管线。恢复后用户修改文字或移除附件,同步更新原恢复记录;文字和附件清空后删除记录及其附件副本,- 离页、重启和迟到的旧编辑不得恢复已删除内容。再次提交先等待这些编辑落盘。+ 离页、重启和迟到的旧编辑不得恢复已删除内容。再次提交先等待这些编辑落盘;离页也须等+ 已发起的编辑结算后才释放原领取,空白页监听同一领取与发件箱通知,只恢复已提交版本。+ 后续消息合并超出附件上限时,父草稿提交并移除源记录后,仅回收父草稿未引用的上传对象;+ 清理中断重进沿原记录推导待回收引用,保留已承接和同路径引用,不新增回收账本。空白新建页自动恢复当前设备(项目入口还须匹配目录)的最新未领取草稿;不覆盖用户已输入的文字、附件、模型或目录选择,也不覆盖带预设内容的新建入口。文件选择器、上传和粘贴占位按同步状态判定已有输入;接收到系统分享的表单不再自动领取旧草稿。