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): 留存恢复草稿新增附件的文件副本并同步主干

Dash4f1cb8cf8931
diff --cc apps/mobile/app/sessions/[sessionId].tsx
index 0535cb5575,c89cc3f98f..38def4b351
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@@ -4099,76 -4093,11 +4099,76 @@@ 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,
+ 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 });
++ 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/src/__tests__/newSessionCreationPersistence.test.ts
index 329041de3c,34facd3ae5..b5b1f586e2
--- a/apps/mobile/src/__tests__/newSessionCreationPersistence.test.ts
+++ b/apps/mobile/src/__tests__/newSessionCreationPersistence.test.ts
@@@ -5,6 -5,6 +5,8 @@@ 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';
@@@ -18,7 -18,7 +20,23 @@@ vi.mock('@react-native-async-storage/as
},
removeItem: async (key: string) => { 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(),
++ 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';
@@@ -55,6 -54,6 +73,9 @@@ beforeEach(async () =>
await mobileDurableOutbox.activate('');
disk.data.clear();
disk.fail = false;
++ files.retained.clear();
++ files.sequence = 0;
++ files.beforeCopy = async () => {};
setMobileAuthOwner('alice', 'global');
await mobileDurableOutbox.activate(getMobileAuthOwner().accountKey);
});
@@@ -76,9 -75,9 +97,9 @@@ function harness(previous: DurableOutbo
planModeCapability: 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,
++ removeRetainedOutboxFiles, releaseUploadedSources: vi.fn(),
outboxAttachmentNeedsLocalBytes: () => true,
registerPendingPrecreatedWorktree: vi.fn(async (..._args: Parameters<typeof registerPendingPrecreatedWorktree>) => true), forgetPendingPrecreatedWorktree: vi.fn(),
buildWorktreeCreateRequest: (input: unknown) => input,
@@@ -160,7 -159,7 +181,7 @@@ it.each(['reservation-fails', 'create-r
expect(saved).toMatchObject({ storageSessionId: original.item.sessionId, suspended: true, state: 'failed',
creation: { editReady: true, draft: { firstMessage: 'updated input before retry', workingDir: '/repo' } },
item: { sessionId: 'replacement-session', clientId: original.item.clientId, attachmentSlots: [{ id: 'photo' }] },
-- uploads: [{ fileName: 'slot-0.png' }] });
++ uploads: [{ slot: 0, name: 'photo.png', fileName: expect.stringMatching(/^slot-0-\d+\.png$/) }] });
expect(getNewSessionCreationTask('replacement-session')?.readyForEdit).toBe('durable');
const leaveReopenedForm = completeNewSessionDurableEdit('replacement-session', 'pc');
expect(getNewSessionCreationTask('replacement-session')).toBeNull();
@@@ -243,7 -242,7 +264,7 @@@ it('persists the draft and attachments
const saved = [...disk.data.values()].map((value) => JSON.parse(value) as DurableOutboxRecord)[0];
expect(saved).toMatchObject({ suspended: true, item: { text: 'keep my input' },
creation: { originalWorkingDir: '/repo', draft: { workingDir: '/repo' } },
-- uploads: [{ fileName: 'slot-0.png' }] });
++ uploads: [{ slot: 0, name: 'photo.png', fileName: expect.stringMatching(/^slot-0-\d+\.png$/) }] });
return true;
});
await h.run();
@@@ -263,7 -262,7 +284,8 @@@ it('recovers the input after a lost cre
await mobileDurableOutbox.activate('');
await mobileDurableOutbox.activate(getMobileAuthOwner().accountKey);
expect(getCurrentMobileOutboxRecords()[0]).toMatchObject({ suspended: true, state: 'failed',
-- item: { text: 'keep my input', attachmentSlots: [{ id: 'photo' }] }, uploads: [{ fileName: 'slot-0.png' }],
++ item: { text: 'keep my input', attachmentSlots: [{ id: 'photo' }] },
++ uploads: [{ slot: 0, name: 'photo.png', fileName: expect.stringMatching(/^slot-0-\d+\.png$/) }],
creation: { cancelled: true, draft: { workingDir: '/repo', firstMessage: 'keep my input' } } });
});
@@@ -379,85 -378,3 +401,137 @@@ 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.
+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 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 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 saved = await mobileDurableOutbox.update(original, cancelledCreationDraft(original));
- const file = { ...saved.item.attachmentSlots[0]!, id: 'new-file', name: 'new.png' };
++ 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).toEqual(saved.uploads);
++ 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();
++ 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 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();
+ 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);
+ });
diff --cc apps/mobile/src/__tests__/optimisticSessionComposer.test.ts
index 6066cb63e8,e6d535d6d3..44d354389b
--- a/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts
+++ b/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts
@@@ -334,41 -332,6 +334,43 @@@ describe('mobile optimistic composer wh
expect(branch).toContain('discardRecoveredAttachments(dropped);');
expect(branch).toContain('const unrecoveredCount = dropped.length + cancelledUploadCount;');
expect(branch).toContain("notice: unrecoveredCount > 0");
+
+ // Execute the production handoff with a picker open but no upload slot yet.
+ // The old pending-count guard returned without saving any warning.
+ const ast = ts.createSourceFile(SCREEN, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+ let beforeNavigate: ts.Expression | undefined;
+ const visit = (node: ts.Node) => {
+ if (ts.isCallExpression(node) && node.expression.getText(ast) === 'useFailedCreationReturnToEdit') {
+ const options = node.arguments[0] as ts.ObjectLiteralExpression;
+ beforeNavigate = options.properties.find((p): p is ts.PropertyAssignment =>
+ ts.isPropertyAssignment(p) && p.name.getText(ast) === 'beforeNavigate')?.initializer;
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(ast);
+ expect(beforeNavigate).toBeDefined();
+ const save = vi.fn(async () => []);
+ const warning = vi.fn();
+ const context = {
+ getMobileAuthOwner: () => 'owner', isMobileAuthOwnerCurrent: () => true,
+ outboxSessionAliveRef: { current: 'task' }, sessionId: 'task', deviceId: 'mac',
+ getPendingUploadCount: () => 0, hasAttachmentInput: () => true,
+ t: (key: string) => key, attachmentError: null, setAttachmentError: warning,
+ discardAllPendingUploadsForScopeChange: vi.fn(), draftRef: { current: '' },
+ attachmentsRef: { current: [] }, appendNewSessionEditComposer: save,
++ getUploadedSource: vi.fn(),
+ releaseUploadedSources: vi.fn(), setAttachments: vi.fn(), replaceComposerDraft: vi.fn(),
+ discardRecoveredAttachments: vi.fn(),
+ };
+ const code = ts.transpileModule(`const callback = ${beforeNavigate!.getText(ast)};`, {
+ compilerOptions: { target: ts.ScriptTarget.ES2022 },
+ }).outputText;
+ await new Function(...Object.keys(context), `${code}; return callback();`)(...Object.values(context));
+ expect(save).toHaveBeenCalledWith('task', 'mac', {
+ text: '', attachments: [], notice: 'session.screen.pendingAttachmentsNotCarriedBack',
++ getUploadedSource: context.getUploadedSource,
+ });
+ expect(warning).toHaveBeenCalledWith('session.screen.pendingAttachmentsNotCarriedBack');
});
it('never silently drops recovered attachments, and never discards live tray ones', () => {
diff --cc apps/mobile/src/session/newSessionCreation.ts
index 722366bff3,06e537cd8e..bb2679347d
--- a/apps/mobile/src/session/newSessionCreation.ts
+++ b/apps/mobile/src/session/newSessionCreation.ts
@@@ -52,8 -52,6 +52,9 @@@ import type { DeviceProvidersPayload }
import { remoteSessionStore } from '@/session/remoteSessionStore';
import { getCurrentMobileOutboxRecords, holdDurableOutboxCreation, isDurableOutboxCreationHeld, mobileDurableOutbox, persistCancelledCreationDraft, suspendCreationDraftForCleanup } from './mobileDurableOutbox';
import { isDurableOutboxSettled, type DurableOutboxRecord } from './durableOutbox';
+import { isExplicitRemoteNotFoundError } from './newSessionWorktree';
+import { mergeAttachmentsWithinLimit } from './attachments';
++import type { MobileLocalAttachmentUploadCandidate } from './mobileLocalAttachmentUpload';
import {
forgetPendingPrecreatedWorktree,
parseDiscardPrecreatedAck,
@@@ -800,45 -731,6 +801,68 @@@ export function drainStashedNewSessionD
return value;
}
+/** Save the visible, unsent composer before the failed chat is unmounted. */
+export async function appendNewSessionEditComposer(sessionId: string, deviceId: string, input: {
+ text: string;
+ attachments: readonly RemoteSerializedAttachment[];
+ notice?: string | null;
++ getUploadedSource?: (id: string) => MobileLocalAttachmentUploadCandidate | undefined;
+}): Promise<RemoteSerializedAttachment[]> {
++ const owner = getMobileAuthOwner();
+ const task = tasks.get(sessionId);
+ const memory = task?.deviceId === deviceId && isTaskOwnerCurrent(task) ? task.editDraft?.value : undefined;
+ const record = getCurrentMobileOutboxRecords().find(record => record.deviceId === deviceId
+ && record.item.sessionId === sessionId && isDurableEditRecord(record));
+ const draft = record?.creation?.draft ?? memory?.draft;
+ if (!draft) throw new Error(i18n.t('session.outbox.restoreFailed'));
+ const original = record ? record.item.attachmentSlots.filter(
+ (file): file is RemoteSerializedAttachment => file !== null) : memory!.attachments;
+ const { merged, dropped } = mergeAttachmentsWithinLimit(original, input.attachments);
+ const nextDraft = { ...draft, firstMessage: [draft.firstMessage, input.text].filter(Boolean).join('\n\n') };
+ const notice = [record?.creation?.notice ?? memory?.notice, input.notice,
+ dropped.length ? i18n.t('session.screen.attachmentsNotCarriedBack', { count: dropped.length }) : null,
+ ].filter(Boolean).join('\n') || undefined;
+ if (record?.creation) {
- // Keep existing upload slot numbers and retained bytes intact. New files
- // already have uploaded references; only their ownership moves here.
++ // A serialized OSS/peer reference is not enough to resubmit the recovered
++ // draft. Keep its bytes through the same retention path as initial creation.
+ const added = merged.filter(file => !original.some(existing => existing.id === file.id));
- await mobileDurableOutbox.update(record, {
- creation: { ...record.creation, draft: nextDraft, notice },
- item: { ...record.item,
- text: [record.item.text, input.text].filter(Boolean).join('\n\n'),
- attachmentSlots: [...record.item.attachmentSlots, ...added],
- slotMeta: [...record.item.slotMeta, ...added.map(file => ({
- kind: file.category === 'image' ? 'image' as const : 'file' as const, previewUri: null,
- }))],
- },
- });
++ const sources = added.map(file => input.getUploadedSource?.(file.id));
++ const copies: DurableOutboxRecord = { ...record, uploads: [] };
++ const { retainOutboxFile, removeRetainedOutboxFiles, outboxAttachmentNeedsLocalBytes } = await import('./durableOutboxFiles');
++ try {
++ for (let index = 0; index < added.length; index++) {
++ if (!isMobileAuthOwnerCurrent(owner)) throw new Error('OUTBOX_STALE_WRITE');
++ const source = sources[index];
++ if (source) copies.uploads.push(await retainOutboxFile(record, record.item.attachmentSlots.length + index, source));
++ else if (outboxAttachmentNeedsLocalBytes(added[index])) {
++ throw new Error(i18n.t('session.screen.attachmentsNotCarriedBack', { count: 1 }));
++ }
++ }
++ if (!isMobileAuthOwnerCurrent(owner) || !getCurrentMobileOutboxRecords().includes(record)) {
++ throw new Error('OUTBOX_STALE_WRITE');
++ }
++ await mobileDurableOutbox.update(record, {
++ creation: { ...record.creation, draft: nextDraft, notice },
++ uploads: [...record.uploads, ...copies.uploads],
++ item: { ...record.item,
++ text: [record.item.text, input.text].filter(Boolean).join('\n\n'),
++ attachmentSlots: [...record.item.attachmentSlots, ...added],
++ slotMeta: [...record.item.slotMeta, ...added.map(file => ({
++ kind: file.category === 'image' ? 'image' as const : 'file' as const, previewUri: null,
++ }))],
++ },
++ });
++ } catch (error) {
++ // Never remove old recovery bytes or composer sources on a failed save.
++ await removeRetainedOutboxFiles(copies).catch(() => undefined);
++ throw error;
++ }
+ } else {
+ stashNewSessionDraftForEdit(task!, { draft: nextDraft, attachments: merged, notice });
+ }
+ return dropped;
+}
+
/** Saving the durable draft does not transfer ownership to a form that has left. */
export function markNewSessionDurableEditReady(sessionId: string, deviceId: string): void {
const task = tasks.get(sessionId);