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): 自动恢复时保留当前输入并避开新附件输入

Dash18d14a382630
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index adb266f47f..bcf9c625ab 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -294,6 +294,7 @@ import {
stashNewSessionDraftForEdit,
useNewSessionCreationTask,
withNewSessionCreationRemoval,
+ appendNewSessionEditComposer,
} from '@/session/newSessionCreation';
import {
useComposerImageAnnotations,
@@ -2587,7 +2588,11 @@ function SessionScreenContent() {
setPendingPlanViewerState('half');
}
}, [activePendingKind, activePendingRequestId, sessionOperationLayout.composerSlot]);
- const canUseComposer = sessionOperationLayout.canUseComposer && !sessionResourceCards.blocked && companionEntry.canCompose;
+ const creationTask = useNewSessionCreationTask(sessionId);
+ // A failed chat is handing its composer to the editor. Running creation still
+ // keeps the normal composer; stop further edits only during this handoff.
+ const canUseComposer = sessionOperationLayout.canUseComposer && !sessionResourceCards.blocked && companionEntry.canCompose
+ && creationTask?.status !== 'create-failed';
const canUseRemoteSessionControls = canUseComposer
&& !sessionSettingsLocked
&& !remoteRealtimeControlsUnavailable;
@@ -4096,7 +4101,6 @@ function SessionScreenContent() {
// - create-failed:带回草稿与附件并自动返回编辑,不要求用户选择恢复方式;
// - enqueue-failed:会话已建成,首条消息文本 / 附件回填 composer,用户走正常发送
// (新桌面有 clientId 幂等去重,重复风险已兜)。
- const creationTask = useNewSessionCreationTask(sessionId);
const creationScreenFocused = useIsFocused();
useFailedCreationReturnToEdit({
task: creationTask?.deviceId === deviceId ? creationTask : null,
@@ -4107,6 +4111,30 @@ function SessionScreenContent() {
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 pendingCount = getPendingUploadCount();
+ const notice = pendingCount > 0
+ ? t('session.screen.attachmentsNotCarriedBack', { count: pendingCount })
+ : 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 });
+ 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 会把它们
diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsx
index d0305974a0..708b2087ad 100644
--- a/apps/mobile/app/sessions/new.tsx
+++ b/apps/mobile/app/sessions/new.tsx
@@ -856,25 +856,6 @@ export default function NewRemoteSessionScreen() {
router.replace('/devices');
return true;
}, [router]);
- useEffect(() => {
- if (params.recoverySessionId || params.editSessionId || params.draft || params.suggestion
- || visualInitialDraft || !newSessionPreferencesLoaded || !selectedDeviceId) return;
- const owner = outboxOwner;
- let active = true;
- const resume = () => {
- if (!active || !isMobileAuthOwnerCurrent(owner) || outboxRecoveryRef.current
- || firstMessageRef.current || attachmentsRef.current.length
- || userTouchedRuntimeRef.current || userTouchedWorkspaceRef.current) return;
- const saved = findNewSessionEditDraft(selectedDeviceId, initialWorkingDir);
- if (!saved) return;
- active = false;
- router.setParams({ recoverySessionId: saved.item.sessionId, deviceId: saved.deviceId });
- };
- const unsubscribe = mobileDurableOutbox.subscribe(resume);
- void mobileDurableOutbox.ready().then(resume);
- return () => { active = false; unsubscribe(); };
- }, [params.recoverySessionId, params.editSessionId, params.draft, params.suggestion, visualInitialDraft,
- newSessionPreferencesLoaded, selectedDeviceId, initialWorkingDir, outboxOwner, router]);
useEffect(() => {
const owner = outboxOwner;
if (leaveForeignOutboxRecovery()) return;
@@ -895,6 +876,7 @@ export default function NewRemoteSessionScreen() {
record.item.attachmentSlots.filter((a): a is RemoteSerializedAttachment => a !== null),
{ enabled: record.creation.planModeArm, restorePermissionMode: record.creation.restorePermissionMode },
record.deviceId);
+ if (record.creation.notice) setAttachmentError(record.creation.notice);
setSelectedDeviceId(record.deviceId);
setSelectedDeviceName(record.creation.deviceName);
releaseEditClaim = completeNewSessionDurableEdit(sid, record.deviceId);
@@ -940,6 +922,7 @@ export default function NewRemoteSessionScreen() {
discardAllPendingUploads,
waitForPendingUploads,
getPendingUploadCount,
+ hasAttachmentInput,
getUploadedSource,
releaseUploadedSources,
} = useMobileLocalAttachments({
@@ -977,7 +960,29 @@ export default function NewRemoteSessionScreen() {
setAttachmentError(null);
}), [auth.getAccessToken, discardAllPendingUploads]);
const incomingShareBatch = useIncomingShareBatch();
+ const incomingShareReceivedRef = useRef(false);
+ if (incomingShareBatch) incomingShareReceivedRef.current = true;
const isShareTargetFocused = useIsFocused();
+ useEffect(() => {
+ if (params.recoverySessionId || params.editSessionId || params.draft || params.suggestion
+ || visualInitialDraft || !newSessionPreferencesLoaded || !selectedDeviceId) return;
+ const owner = outboxOwner;
+ let active = true;
+ const resume = () => {
+ if (!active || !isMobileAuthOwnerCurrent(owner) || outboxRecoveryRef.current
+ || firstMessageRef.current || attachmentsRef.current.length || hasAttachmentInput()
+ || incomingShareReceivedRef.current
+ || userTouchedRuntimeRef.current || userTouchedWorkspaceRef.current) return;
+ const saved = findNewSessionEditDraft(selectedDeviceId, initialWorkingDir);
+ if (!saved) return;
+ active = false;
+ router.setParams({ recoverySessionId: saved.item.sessionId, deviceId: saved.deviceId });
+ };
+ const unsubscribe = mobileDurableOutbox.subscribe(resume);
+ void mobileDurableOutbox.ready().then(resume);
+ return () => { active = false; unsubscribe(); };
+ }, [params.recoverySessionId, params.editSessionId, params.draft, params.suggestion, visualInitialDraft,
+ newSessionPreferencesLoaded, selectedDeviceId, initialWorkingDir, outboxOwner, router, hasAttachmentInput]);
useEffect(() => {
if (!isShareTargetFocused || !auth.isAuthenticated || !incomingShareBatch
|| getMobileAuthOwner().accountId !== auth.user?.id) return;
diff --git a/apps/mobile/src/__tests__/newSessionCreation.test.ts b/apps/mobile/src/__tests__/newSessionCreation.test.ts
index a9df30ef3a..db1b8fdd15 100644
--- a/apps/mobile/src/__tests__/newSessionCreation.test.ts
+++ b/apps/mobile/src/__tests__/newSessionCreation.test.ts
@@ -12,6 +12,7 @@ import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import ts from 'typescript';
import type { MobileMakerTransport } from '@/device-link/mobileMakerTransport';
+import type { RemoteSerializedAttachment } from '@/session/types';
import { createDurableOutbox, isDurableOutboxHandedOff, isDurableOutboxSettled, type DurableOutboxRecord } from '@/session/durableOutbox';
import { buildOutboxItem, outboxItemAttachments } from '@/session/sessionOutbox';
import { CINDY_MAKE_ENABLED, isCindyMakeSource } from '@cindy/maker-shared/cindy-make-feature';
@@ -49,6 +50,8 @@ vi.mock('expo-crypto', () => ({
}));
import {
completeNewSessionDurableEdit,
+ findNewSessionEditDraft,
+ appendNewSessionEditComposer,
dismissNewSessionCreation,
dismissRecoveredPrecreatedSession,
drainStashedNewSessionDraft,
@@ -205,7 +208,59 @@ async function flushPipeline(): Promise<void> {
}
}
+// Reuse the existing native-page effect harness for both explicit recovery and
+// blank-form resume; execute production callbacks, never duplicate their guards.
+const recoveryPage = ts.createSourceFile('new.tsx', readFileSync(resolve(process.cwd(), 'app/sessions/new.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+function runRecoveryEffect(marker: string, bindings: Record<string, unknown>): (() => void) | undefined {
+ let effect = '';
+ function visit(node: ts.Node) {
+ if (ts.isCallExpression(node) && node.expression.getText(recoveryPage) === 'useEffect'
+ && node.arguments[0]?.getText(recoveryPage).includes(marker)) effect = node.arguments[0].getText(recoveryPage);
+ ts.forEachChild(node, visit);
+ }
+ visit(recoveryPage);
+ if (!effect) throw new Error('Missing production creation recovery effect');
+ const compiled = ts.transpileModule(`function run(bindings) { const { ${Object.keys(bindings).join(', ')} } = bindings; return (${effect})(); }`,
+ { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
+ return new Function(`${compiled}; return run;`)()(bindings);
+}
+
describe('newSessionCreation pipeline', () => {
+ it.each(['blank', 'upload', 'paste', 'received-share', 'input-before-ready'])('blank form recovery respects active input: %s', async scenario => {
+ const original = recoveryOutboxRecord('s1');
+ editOutbox.records.mockReturnValue([{ ...original, accountId: getMobileAuthOwner().accountKey,
+ suspended: true, creation: { ...original.creation!, editReady: true } }]);
+ let pendingInput = scenario === 'upload' || scenario === 'paste';
+ let ready!: () => void;
+ const router = { setParams: vi.fn() };
+ const cleanup = runRecoveryEffect('findNewSessionEditDraft(', {
+ params: {}, visualInitialDraft: null, newSessionPreferencesLoaded: true, selectedDeviceId: 'dev-1',
+ outboxOwner: getMobileAuthOwner(), isMobileAuthOwnerCurrent, outboxRecoveryRef: { current: null },
+ firstMessageRef: { current: '' }, attachmentsRef: { current: [] },
+ userTouchedRuntimeRef: { current: false }, userTouchedWorkspaceRef: { current: false },
+ hasAttachmentInput: () => pendingInput, incomingShareReceivedRef: { current: scenario === 'received-share' },
+ findNewSessionEditDraft, initialWorkingDir: null, router,
+ mobileDurableOutbox: { subscribe: () => () => {}, ready: () => new Promise<void>(resolve => { ready = resolve; }) },
+ });
+ if (scenario === 'input-before-ready') pendingInput = true;
+ ready();
+ await flushPipeline();
+ expect(router.setParams).toHaveBeenCalledTimes(scenario === 'blank' ? 1 : 0);
+ cleanup?.();
+ });
+
+ it('carries unsent composer text and files through legacy memory recovery', async () => {
+ const maker = makeMaker({ createSession: vi.fn(async () => { throw new Error('[MODEL_UNAVAILABLE] unavailable'); }) });
+ startNewSessionCreation(makeParams('s1', maker));
+ await flushPipeline();
+ await returnNewSessionToEdit({ sessionId: 's1', deviceId: 'dev-1', isCurrent: () => true, onReady: vi.fn() });
+ const file = { id: 'new-file', path: 'oss://new-file', category: 'image', name: 'new.png', ext: 'png', size: 1 } as RemoteSerializedAttachment;
+ await appendNewSessionEditComposer('s1', 'dev-1', { text: 'unsent addition', attachments: [file], notice: 'one pending upload' });
+ const restored = drainStashedNewSessionDraft('s1', 'dev-1')!;
+ expect(restored.draft.firstMessage).toBe(`${DRAFT.firstMessage}\n\nunsent addition`);
+ expect(restored.attachments).toEqual([file]);
+ expect(restored.notice).toBe('one pending upload');
+ });
it.each([false, true])('deletes a failed local task only after worktree cleanup (cleanup fails: %s)', async fails => {
const maker = makeMaker();
startNewSessionCreation(makeParams('s1', maker, {
@@ -608,15 +663,6 @@ describe('newSessionCreation pipeline', () => {
if (scope === 'not-ready') editOutbox.records.mockReturnValue([]);
if (scope === 'switched-owner') setMobileAuthOwner('owner-b');
// Execute the real form effect, including readiness and ownership guards.
- const page = ts.createSourceFile('new.tsx', readFileSync(resolve(process.cwd(), 'app/sessions/new.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
- let effect = '';
- function findEffect(node: ts.Node) {
- if (ts.isCallExpression(node) && node.expression.getText(page) === 'useEffect'
- && node.arguments[0]?.getText(page).includes('completeNewSessionDurableEdit(')) effect = node.arguments[0].getText(page);
- ts.forEachChild(node, findEffect);
- }
- findEffect(page);
- if (!effect) throw new Error('Missing production creation recovery effect');
const restore = vi.fn(() => expect(getNewSessionCreationTask('s1')?.readyForEdit).toBe('durable'));
const bindings = {
outboxOwner: owner, params: { recoverySessionId: 's1' }, routeDeviceId: scope === 'device' ? 'dev-2' : 'dev-1',
@@ -626,9 +672,7 @@ describe('newSessionCreation pipeline', () => {
setSelectedDeviceId: vi.fn(), setSelectedDeviceName: vi.fn(), completeNewSessionDurableEdit,
mobileDurableOutbox: { subscribe: () => () => {}, ready: async () => {} },
};
- const compiled = ts.transpileModule(`function run(bindings) { const { ${Object.keys(bindings).join(', ')} } = bindings; return (${effect})(); }`,
- { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
- const cleanup = (new Function(`${compiled}; return run;`)() as (b: typeof bindings) => () => void)(bindings);
+ const cleanup = runRecoveryEffect('completeNewSessionDurableEdit(', bindings)!;
await flushPipeline();
if (scope === 'matching') {
expect(restore).toHaveBeenCalledWith(DRAFT, [], { enabled: false, restorePermissionMode: null }, 'dev-1');
diff --git a/apps/mobile/src/__tests__/newSessionCreationPersistence.test.ts b/apps/mobile/src/__tests__/newSessionCreationPersistence.test.ts
index d985cb1069..329041de3c 100644
--- a/apps/mobile/src/__tests__/newSessionCreationPersistence.test.ts
+++ b/apps/mobile/src/__tests__/newSessionCreationPersistence.test.ts
@@ -26,7 +26,7 @@ import { completeNewSessionDurableEdit, getNewSessionCreationTask, hasLiveNewSes
import { remoteSessionStore } from '../session/remoteSessionStore';
import { listPendingPrecreatedWorktrees, recoverPendingPrecreatedWorktrees, registerPendingPrecreatedWorktree } from '../session/precreatedWorktreeRecovery';
import { completePrecreatedWorktreeRecovery } from '../session/completePrecreatedWorktreeRecovery';
-import { findNewSessionEditDraft, withNewSessionCreationRemoval } from '../session/newSessionCreation';
+import { appendNewSessionEditComposer, findNewSessionEditDraft, withNewSessionCreationRemoval } from '../session/newSessionCreation';
// Run the page's actual recovery -> durable save -> worktree creation statements.
// Extract AST nodes, as in newSessionWorktreeSync, so ordering is tested without
@@ -414,6 +414,32 @@ it('keeps a saved draft if durable deletion fails', async () => {
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' };
+ 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',
+ });
+ if (fails) {
+ await expect(transfer).rejects.toThrow('disk unavailable');
+ expect(getCurrentMobileOutboxRecords()[0]).toEqual(saved);
+ 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.item.slotMeta).toHaveLength(2);
+});
+
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();
diff --git a/apps/mobile/src/__tests__/useFailedCreationReturnToEdit.test.tsx b/apps/mobile/src/__tests__/useFailedCreationReturnToEdit.test.tsx
index 32fb83eeda..65dc0e0a4a 100644
--- a/apps/mobile/src/__tests__/useFailedCreationReturnToEdit.test.tsx
+++ b/apps/mobile/src/__tests__/useFailedCreationReturnToEdit.test.tsx
@@ -150,3 +150,32 @@ it('does not lose an in-flight recovery result when the connection changes', asy
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 --git a/apps/mobile/src/__tests__/useMobileLocalAttachmentsAbandon.test.tsx b/apps/mobile/src/__tests__/useMobileLocalAttachmentsAbandon.test.tsx
index fd158c1215..0fb39a0a4a 100644
--- a/apps/mobile/src/__tests__/useMobileLocalAttachmentsAbandon.test.tsx
+++ b/apps/mobile/src/__tests__/useMobileLocalAttachmentsAbandon.test.tsx
@@ -92,6 +92,17 @@ const imageCandidate = (name: string, onAbandoned: () => void): MobileLocalAttac
const flush = () => new Promise((resolve) => { setTimeout(resolve, 0); });
describe('useMobileLocalAttachments abandonment on scope change', () => {
+ it.each(['paste', 'upload'])('reports %s input synchronously before React commits the tray', async kind => {
+ const harness = mount('session-a');
+ expect(harness.first.hasAttachmentInput()).toBe(false);
+ act(() => {
+ if (kind === 'paste') harness.first.beginPastePlaceholders(1);
+ else harness.first.enqueueUploads([imageCandidate('a.png', vi.fn())], { token: 'token' });
+ expect(harness.first.hasAttachmentInput()).toBe(true);
+ });
+ act(() => harness.first.discardAllPendingUploadsForScopeChange());
+ expect(harness.first.hasAttachmentInput()).toBe(false);
+ });
it('abandons a candidate enqueued from a stale scope without starting an upload', async () => {
const harness = mount('session-a');
act(() => harness.first.discardAllPendingUploadsForScopeChange());
diff --git a/apps/mobile/src/session/durableOutbox.ts b/apps/mobile/src/session/durableOutbox.ts
index c443d278d1..d468974cc8 100644
--- a/apps/mobile/src/session/durableOutbox.ts
+++ b/apps/mobile/src/session/durableOutbox.ts
@@ -52,6 +52,8 @@ 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;
deviceName: string;
planModeArm: boolean;
restorePermissionMode: string | null;
diff --git a/apps/mobile/src/session/newSessionCreation.ts b/apps/mobile/src/session/newSessionCreation.ts
index aa0c1a910d..722366bff3 100644
--- a/apps/mobile/src/session/newSessionCreation.ts
+++ b/apps/mobile/src/session/newSessionCreation.ts
@@ -53,6 +53,7 @@ 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 {
forgetPendingPrecreatedWorktree,
parseDiscardPrecreatedAck,
@@ -799,6 +800,45 @@ export function drainStashedNewSessionDraft(sessionId?: string, deviceId?: strin
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;
+}): Promise<RemoteSerializedAttachment[]> {
+ 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.
+ 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,
+ }))],
+ },
+ });
+ } 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);
diff --git a/apps/mobile/src/session/returnNewSessionToEdit.ts b/apps/mobile/src/session/returnNewSessionToEdit.ts
index 6123e259c9..8b0b53f90e 100644
--- a/apps/mobile/src/session/returnNewSessionToEdit.ts
+++ b/apps/mobile/src/session/returnNewSessionToEdit.ts
@@ -11,7 +11,7 @@ export async function returnNewSessionToEdit({ sessionId, deviceId, isCurrent, o
sessionId: string;
deviceId: string;
isCurrent: () => boolean;
- onReady: (params: { deviceId: string; deviceName: string; recoverySessionId?: string; editSessionId?: string }) => void;
+ onReady: (params: { deviceId: string; deviceName: string; recoverySessionId?: string; editSessionId?: string }) => void | Promise<void>;
stashDraft?: (task: NewSessionCreationTask) => void;
}): Promise<void> {
const owner = getMobileAuthOwner();
@@ -19,7 +19,7 @@ export async function returnNewSessionToEdit({ sessionId, deviceId, isCurrent, o
const task = getNewSessionCreationTask(sessionId);
if (!ownerCurrent() || !isCurrent() || task?.deviceId !== deviceId) return;
if (task.readyForEdit && !task.returningToEdit) {
- onReady({ deviceId, deviceName: task.deviceName,
+ await onReady({ deviceId, deviceName: task.deviceName,
...(task.readyForEdit === 'durable' ? { recoverySessionId: sessionId } : { editSessionId: sessionId }) });
return;
}
@@ -41,12 +41,12 @@ export async function returnNewSessionToEdit({ sessionId, deviceId, isCurrent, o
});
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);
// Keep the failed row reachable until the matching form takes ownership.
- if (isCurrent()) onReady({ deviceId, deviceName: prepared.deviceName, editSessionId: sessionId });
+ if (isCurrent()) await onReady({ deviceId, deviceName: prepared.deviceName, editSessionId: sessionId });
} finally {
release();
}
diff --git a/apps/mobile/src/session/useFailedCreationReturnToEdit.ts b/apps/mobile/src/session/useFailedCreationReturnToEdit.ts
index c6af465a65..0bf57df45f 100644
--- a/apps/mobile/src/session/useFailedCreationReturnToEdit.ts
+++ b/apps/mobile/src/session/useFailedCreationReturnToEdit.ts
@@ -6,16 +6,17 @@ 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, onReady, onError }: {
+export function useFailedCreationReturnToEdit({ task, focused, connectionEpoch, stashDraft, beforeNavigate, onReady, onError }: {
task: NewSessionCreationTask | null;
focused: boolean;
connectionEpoch: number;
stashDraft: RecoveryOptions['stashDraft'];
+ beforeNavigate?: () => Promise<void>;
onReady: RecoveryOptions['onReady'];
onError: (error: unknown) => void;
}) {
- const callbacks = useRef({ stashDraft, onReady, onError });
- callbacks.current = { stashDraft, onReady, onError };
+ 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;
@@ -40,10 +41,17 @@ export function useFailedCreationReturnToEdit({ task, focused, connectionEpoch,
void returnNewSessionToEdit({
sessionId, deviceId, isCurrent,
stashDraft: callbacks.current.stashDraft,
- onReady: params => {
+ onReady: async params => {
if (!isCurrent() || navigated.current === identity) return;
navigated.current = identity;
- callbacks.current.onReady(params);
+ 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);
diff --git a/apps/mobile/src/session/useMobileLocalAttachments.ts b/apps/mobile/src/session/useMobileLocalAttachments.ts
index a9addf46af..0d6a8d55fe 100644
--- a/apps/mobile/src/session/useMobileLocalAttachments.ts
+++ b/apps/mobile/src/session/useMobileLocalAttachments.ts
@@ -159,6 +159,8 @@ export interface UseMobileLocalAttachmentsResult {
* 计数会放行超额选图 / 标注,占位兑现时轮到粘贴图自己撞上限被丢(review P2)。
*/
getPendingUploadCount: () => number;
+ /** Synchronous picker, upload and paste activity, including before the first slot exists. */
+ hasAttachmentInput: () => boolean;
}
export function useMobileLocalAttachments(
@@ -647,5 +649,6 @@ export function useMobileLocalAttachments(
),
hasPastePlaceholders: () => isAttachmentScopeActive() && getPastePlaceholderTotal() > 0,
getPendingUploadCount: () => (isAttachmentScopeActive() ? getPendingSlotCount() : 0),
+ hasAttachmentInput: () => isAttachmentScopeActive() && (pickerBusyRef.current || getPendingSlotCount() > 0),
};
}
diff --git a/docs/dev-rules/mobile-development.md b/docs/dev-rules/mobile-development.md
index f7d94f059b..7bfca999b6 100644
--- a/docs/dev-rules/mobile-development.md
+++ b/docs/dev-rules/mobile-development.md
@@ -88,6 +88,9 @@ pnpm --filter mobile test:smoke
- 本地新建任务立即显示乐观消息与输入框,不因远端来源尚未返回而显示整页等待卡。
仅创建失败时自动带回草稿与附件并返回编辑,不提供重试、返回编辑等选择菜单;
已建成任务的首条消息发送失败仍在原任务内恢复,不退回新建页。失败原因带到编辑页。
+ 自动跳转前同时保存当前输入框的未发送文字和已上传附件,保存成功才移交附件并清空旧输入框,
+ 避免卸载清理删除已交给草稿的文件;失败后的移交期间停止继续编辑,正常创建期间仍可输入。
+ 未完成上传、粘贴占位和超出托盘上限的附件须明确告知,持久恢复同时保存这条告知。
返回编辑复用 worktree 补偿和持久草稿恢复流程;
回收或保存失败保留原任务与草稿。回收开始后离页仍完成同账号的草稿恢复,
仅取消跳转;账号切换后停止旧账号操作,并移除旧代次的内存创建记录及同步阻挡,
@@ -100,6 +103,7 @@ pnpm --filter mobile test:smoke
返回编辑意图写入持久发件箱;退出编辑或应用重启后保留草稿,不重建任务列表行,
不启动创建管线。空白新建页自动恢复当前设备(项目入口还须匹配目录)的最新未领取草稿;
不覆盖用户已输入的文字、附件、模型或目录选择,也不覆盖带预设内容的新建入口。
+ 文件选择器、上传和粘贴占位按同步状态判定已有输入;接收到系统分享的表单不再自动领取旧草稿。
明确删除或归档失败任务时复用 worktree 回收,并持久结束发件箱恢复;列表、详情与批量入口一致,
离页、重启和后台恢复均不能复活已删除记录。回收或持久保存失败时保留恢复材料。
认领按持久存储身份跟随草稿更新与取消后的任务 ID