Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 补齐选择器恢复提示并同步主干附件流程
Dash6ff6a08326d3
diff --cc apps/mobile/app/sessions/[sessionId].tsxindex bcf9c625ab,c89cc3f98f..0535cb5575--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@@ -1419,6 -1418,6 +1419,7 @@@ function SessionScreenContent()waitForPastePlaceholdersSettled,hasPastePlaceholders,getPendingUploadCount,++ hasAttachmentInput,} = useMobileLocalAttachments({attachmentScopeKey: sessionId,deviceId,@@@ -4098,77 -4093,11 +4099,76 @@@// 新建会话乐观管线的收口响应:// - 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 pendingCount = getPendingUploadCount();- const notice = pendingCount > 0- ? t('session.screen.attachmentsNotCarriedBack', { count: pendingCount })++ 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 });+ 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__/optimisticSessionComposer.test.tsindex 5f97194053,e6d535d6d3..6066cb63e8--- a/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts+++ b/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts@@@ -308,7 -308,7 +308,7 @@@ describe('mobile optimistic composer whexpect(branch).toContain('handoff.release(committed)');});-- it('carries follow-ups back to the new-session screen when creation itself failed', () => {++ it('carries follow-ups and a pending picker warning back when creation itself failed', async () => {// create-failed 的「返回编辑」会连合成会话行一起删掉:不把 outbox 一并 stash,// unmount cleanup 会把那些消息写进一个即将消失的会话草稿,用户再也找不回(review P1)。const source = readSource(SCREEN);@@@ -334,6 -332,6 +334,41 @@@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,++ 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',++ });++ expect(warning).toHaveBeenCalledWith('session.screen.pendingAttachmentsNotCarriedBack');});it('never silently drops recovered attachments, and never discards live tray ones', () => {diff --cc apps/mobile/src/__tests__/useMobileLocalAttachmentsAbandon.test.tsxindex 0fb39a0a4a,56faea3a6c..7a1afe5e91--- a/apps/mobile/src/__tests__/useMobileLocalAttachmentsAbandon.test.tsx+++ b/apps/mobile/src/__tests__/useMobileLocalAttachmentsAbandon.test.tsx@@@ -12,6 -12,7 +12,9 @@@ importconst runtime = vi.hoisted(() => ({uploads: [] as Array<{ name: string; resolve: () => void }>,discarded: [] as unknown[],+ pickPhotos: vi.fn(),++ pickCamera: vi.fn(),++ pickDocument: vi.fn(),}));vi.mock('react-native', () => ({ Platform: { OS: 'ios' } }));@@@ -19,8 -20,9 +22,13 @@@ vi.mock('react-i18next', async (importOconst t = (key: string) => key;return { ...await importOriginal<typeof import('react-i18next')>(), useTranslation: () => ({ t }) };});--vi.mock('expo-document-picker', () => ({}));- vi.mock('expo-image-picker', () => ({}));-vi.mock('expo-image-picker', () => ({ requestMediaLibraryPermissionsAsync: async () => ({ granted: true }) }));++vi.mock('expo-document-picker', () => ({ getDocumentAsync: runtime.pickDocument }));++vi.mock('expo-image-picker', () => ({++ requestMediaLibraryPermissionsAsync: async () => ({ granted: true }),++ requestCameraPermissionsAsync: async () => ({ granted: true }),++ launchCameraAsync: runtime.pickCamera,++}));+ vi.mock('@/session/deferredPhotoLibrary', () => ({ pickDeferredLibraryPhotos: runtime.pickPhotos }));vi.mock('expo-file-system/legacy', () => ({documentDirectory: 'file:///docs/',deleteAsync: async () => undefined,@@@ -56,6 -58,7 +64,9 @@@ beforeEach(() =>Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });runtime.uploads = [];runtime.discarded = [];+ runtime.pickPhotos.mockReset();++ runtime.pickCamera.mockReset();++ runtime.pickDocument.mockReset();root = createRoot(document.createElement('div'));});afterEach(() => act(() => root.unmount()));@@@ -92,17 -97,34 +105,55 @@@ const imageCandidate = (name: string, oconst 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('puts selected photos in the tray and closes the context panel before their originals load', async () => {+ const harness = mount('session-a');+ runtime.pickPhotos.mockResolvedValue([{+ ...imageCandidate('cloud.jpg', vi.fn()),+ uri: 'data:image/jpeg;base64,preview',+ resolve: () => new Promise(() => {}),+ }]);+ await act(async () => { await harness.first.addImages('library'); });+ expect(harness.latest().pendingUploads).toHaveLength(1);+ expect(harness.latest().pendingUploads[0].previewUri).toBe('data:image/jpeg;base64,preview');+ expect(harness.options.onPicked).toHaveBeenCalledOnce();+ expect(runtime.uploads).toHaveLength(0);+ });+- it('releases native selections returned after a scope change instead of attaching them to another task', async () => {++ it.each(['library', 'camera', 'document'] as const)('reports %s input before a slot exists and ignores late selections after scope exit', async source => {+ const harness = mount('session-a');- let finish!: (value: MobileLocalAttachmentUploadCandidate[]) => void;- runtime.pickPhotos.mockReturnValue(new Promise((resolve) => { finish = resolve; }));++ let finish!: (value: unknown) => void;++ const picker = source === 'library' ? runtime.pickPhotos : source === 'camera' ? runtime.pickCamera : runtime.pickDocument;++ picker.mockReturnValue(new Promise((resolve) => { finish = resolve; }));+ let picking!: Promise<void>;- await act(async () => { picking = harness.first.addImages('library'); });++ await act(async () => { picking = source === 'document' ? harness.first.addDocument() : harness.first.addImages(source); });++ expect(harness.first.getPendingUploadCount()).toBe(0);++ expect(harness.first.hasAttachmentInput()).toBe(true);+ act(() => harness.first.discardAllPendingUploadsForScopeChange());++ expect(harness.first.hasAttachmentInput()).toBe(false);+ const abandoned = vi.fn();- await act(async () => { finish([imageCandidate('late.jpg', abandoned)]); await picking; });- expect(abandoned).toHaveBeenCalledOnce();++ await act(async () => {++ finish(source === 'library' ? [imageCandidate('late.jpg', abandoned)] : {++ canceled: false, assets: [{ uri: 'file:///late.jpg', name: 'late.jpg', fileName: 'late.jpg' }],++ });++ await picking;++ });++ if (source === 'library') expect(abandoned).toHaveBeenCalledOnce();+ expect(harness.latest().pendingUploads).toEqual([]);+ expect(harness.options.onPicked).not.toHaveBeenCalled();++ expect(runtime.uploads).toHaveLength(0);+ });+it('abandons a candidate enqueued from a stale scope without starting an upload', async () => {const harness = mount('session-a');act(() => harness.first.discardAllPendingUploadsForScopeChange());diff --cc apps/mobile/src/__tests__/useRemoteResourceSession.test.tsxindex 4123499cca,4123499cca..cfb83de22e--- a/apps/mobile/src/__tests__/useRemoteResourceSession.test.tsx+++ b/apps/mobile/src/__tests__/useRemoteResourceSession.test.tsx@@@ -248,7 -248,7 +248,8 @@@ it('drops a late response when switchinawait render(true); expect(result.ready).toBe(false);});--it.each([false, true])('keeps local composing available while dispatch readiness=%s', ready => {++it.each([false, true].flatMap(ready => [undefined, 'running', 'create-failed'].map(status => ({ ready, status }))))(++ 'keeps composing for dispatch readiness=$ready except during failed creation handoff ($status)', ({ ready, status }) => {const expressions = new Map<string, string>();const visit = (node: ts.Node) => {if (ts.isVariableDeclaration(node) && node.initializer) expressions.set(node.name.getText(screen), node.initializer.getText(screen));@@@ -257,13 -257,13 +258,13 @@@visit(screen);const names = ['canUseComposer', 'remoteRealtimeControlsUnavailable', 'outboxConnectionState'];const code = names.map(name => `const ${name} = ${expressions.get(name)};`).join('\n');-- const gates = new Function('ready', `++ const gates = new Function('ready', 'creationTask', `const companionEntry = { ready, canCompose: true }, sessionOperationLayout = { canUseComposer: true }, sessionResourceCards = { blocked: false };const status = 'online', targetAvailableForDispatch = true, isDeviceUnresponsive = false, outboxRecoverySyncHeld = false, loading = false;${code}return { canUseComposer, remoteRealtimeControlsUnavailable, outboxConnectionState };-- `)(ready);-- expect(gates.canUseComposer).toBe(true);++ `)(ready, status ? { status } : undefined);++ expect(gates.canUseComposer).toBe(status !== 'create-failed');expect(gates.remoteRealtimeControlsUnavailable).toBe(!ready);expect(gates.outboxConnectionState.autoRecoveringError).toBe(!ready);});diff --cc apps/mobile/src/i18n/locales/en/session.jsonindex 58ed4b858d,58ed4b858d..89c0a3cb3e--- a/apps/mobile/src/i18n/locales/en/session.json+++ b/apps/mobile/src/i18n/locales/en/session.json@@@ -215,6 -215,6 +215,7 @@@"retry": "Retry","firstMessageNotSent": "The first message wasn't sent; its content has been restored to the input box.","attachmentsNotCarriedBack": "{{count}} attachment(s) couldn't be brought back — please add them again.",++ "pendingAttachmentsNotCarriedBack": "Attachments still being selected or uploaded couldn't be brought back. Please add them again.","localStorageFull": "Cindy's local storage on this phone is full, so the message couldn't be saved. Please try again.","commandWaitsForSession": "The session is still being created — this command needs the session to be ready. Please try again shortly.","locateMessageNotFound": "Couldn't find the message to jump to.",diff --cc apps/mobile/src/i18n/locales/ja/session.jsonindex 55c05775ac,55c05775ac..86c501232e--- a/apps/mobile/src/i18n/locales/ja/session.json+++ b/apps/mobile/src/i18n/locales/ja/session.json@@@ -215,6 -215,6 +215,7 @@@"retry": "再試行","firstMessageNotSent": "最初のメッセージは送信されませんでした。内容は入力欄に復元されました。","attachmentsNotCarriedBack": "{{count}} 件の添付は復元できませんでした。もう一度追加してください。",++ "pendingAttachmentsNotCarriedBack": "選択中またはアップロード中の添付は復元できませんでした。もう一度追加してください。","localStorageFull": "このスマートフォン上の Cindy のローカルストレージがいっぱいのため、メッセージを保存できませんでした。もう一度お試しください。","commandWaitsForSession": "セッションの作成中です。このコマンドはセッションの準備が必要なため、少し待ってから送信してください。","locateMessageNotFound": "移動先のメッセージが見つかりませんでした。",diff --cc apps/mobile/src/i18n/locales/ko/session.jsonindex c202b3a8f4,c202b3a8f4..40e6e69c57--- a/apps/mobile/src/i18n/locales/ko/session.json+++ b/apps/mobile/src/i18n/locales/ko/session.json@@@ -211,6 -211,6 +211,7 @@@"retry": "다시 시도","firstMessageNotSent": "첫 메시지가 전송되지 않았습니다. 내용이 입력창에 복원되었습니다.","attachmentsNotCarriedBack": "첨부 {{count}}개는 되돌리지 못했습니다. 다시 추가해 주세요.",++ "pendingAttachmentsNotCarriedBack": "선택 또는 업로드 중인 첨부 파일은 되돌리지 못했습니다. 다시 추가해 주세요.","localStorageFull": "이 휴대폰에서 Cindy 로컬 저장 공간이 가득 차 메시지를 저장하지 못했습니다. 다시 시도해 주세요.","commandWaitsForSession": "세션을 만들고 있습니다. 이 명령은 세션이 준비된 뒤에 사용할 수 있습니다. 잠시 후 다시 보내 주세요.","locateMessageNotFound": "이동할 메시지를 찾을 수 없습니다.",diff --cc apps/mobile/src/i18n/locales/zh-CN/session.jsonindex 0226e1cc10,0226e1cc10..7e56ba332c--- a/apps/mobile/src/i18n/locales/zh-CN/session.json+++ b/apps/mobile/src/i18n/locales/zh-CN/session.json@@@ -211,6 -211,6 +211,7 @@@"retry": "重试","firstMessageNotSent": "首条消息没有发出,内容已还原到输入框。","attachmentsNotCarriedBack": "有 {{count}} 个附件没能一起带回,需要重新添加。",++ "pendingAttachmentsNotCarriedBack": "尚未完成选择或上传的附件没能一起带回,请重新添加。","localStorageFull": "Cindy 在手机上的本地存储已满,消息没能保存,请稍后重试。","commandWaitsForSession": "任务还在创建中,这个命令要等任务就绪后才能用,请稍后再发。","locateMessageNotFound": "未找到要定位的消息。",diff --cc apps/mobile/src/i18n/locales/zh-TW/session.jsonindex f12f61956c,f12f61956c..1258d29107--- a/apps/mobile/src/i18n/locales/zh-TW/session.json+++ b/apps/mobile/src/i18n/locales/zh-TW/session.json@@@ -215,6 -215,6 +215,7 @@@"retry": "重試","firstMessageNotSent": "首條訊息沒有發出,內容已還原到輸入框。","attachmentsNotCarriedBack": "有 {{count}} 個附件沒能一起帶回,需要重新新增。",++ "pendingAttachmentsNotCarriedBack": "尚未完成選取或上傳的附件沒能一起帶回,請重新新增。","localStorageFull": "Cindy 在手機上的本機儲存空間已滿,訊息沒能儲存,請稍後重試。","commandWaitsForSession": "任務還在建立中,這個命令要等任務就緒後才能用,請稍後再發。","locateMessageNotFound": "未找到要定位的訊息。",diff --cc docs/dev-rules/mobile-development.mdindex 7bfca999b6,93acfb078d..9146b4194c--- a/docs/dev-rules/mobile-development.md+++ b/docs/dev-rules/mobile-development.md@@@ -81,17 -81,27 +81,34 @@@ pnpm --filter mobile test:smok## 专项入口+ ### 相册选图与 iCloud 原图++ iOS 的系统选图器在确认后立即把选中项交给现有附件队列。预览只读取本机小缩略图,+ 不等待 iCloud 原图;受限照片权限下拿不到缩略图时保留附件占位,不扩大照片库权限。+ 原图由选图器授予的 `NSItemProvider` 在队列的 `resolve` 阶段读取,随后沿用格式转换、+ 压缩、上传和持久发件箱交接。发送自动等待原图就绪,不要求用户另行下载或再次发送。+ 失败保留选中项供重试,移除/换任务/成功交付后释放原生句柄;取消后的迟到文件只清理不回填。+ 临时副本使用 App 私有 `Caches/ImagePicker`,由现有附件生命周期回收。++ 实现:`modules/cindy-photo-picker/`、`src/session/deferredPhotoLibrary.ts` 与+ `useMobileLocalAttachments.ts`;回归:`deferredPhotoLibrary.test.ts`、+ `useMobileLocalAttachmentsAbandon.test.tsx`。新增原生模块需要冷更,不能作为旧安装包的 OTA+ 独立交付;旧原生包缺模块时继续使用 Expo 选图入口。首次发布应随下一次 iOS 原生包交付,+ 指纹与存量装机影响仍须按下文冷更门确认。Android 保持系统选图器和既有附件队列。+### 任务入口与创建失败恢复-- 来源未确认时不挂载远端任务内容,但必须显示读取状态和返回入口;读取失败、空记录或+- 非本机发起的任务来源未确认时不挂载远端任务内容,但必须显示读取状态和返回入口;读取失败、空记录或超时允许手动重读当前任务,不重置共享设备连接。账号或设备切换后忽略旧读取结果。-- 本地创建进行中或失败时,来源门禁显示创建进度或失败原因;失败时直接提供重试和返回编辑,- 不依赖尚不存在的远端任务记录。返回编辑复用 worktree 补偿和持久草稿恢复流程;+- 本地新建任务立即显示乐观消息与输入框,不因远端来源尚未返回而显示整页等待卡。+ 仅创建失败时自动带回草稿与附件并返回编辑,不提供重试、返回编辑等选择菜单;+ 已建成任务的首条消息发送失败仍在原任务内恢复,不退回新建页。失败原因带到编辑页。+ 自动跳转前同时保存当前输入框的未发送文字和已上传附件,保存成功才移交附件并清空旧输入框,+ 避免卸载清理删除已交给草稿的文件;失败后的移交期间停止继续编辑,正常创建期间仍可输入。- 未完成上传、粘贴占位和超出托盘上限的附件须明确告知,持久恢复同时保存这条告知。++ 尚未关闭的相册、相机或文件选择器、未完成上传及粘贴占位统一通过附件 hook 的++ `hasAttachmentInput()` 判断并告知,不把上传槽位数当作完整输入状态;选择器内数量未知,++ 提示不猜测附件数量。超出托盘上限的附件也须告知,持久恢复同时保存这些告知。+ 返回编辑复用 worktree 补偿和持久草稿恢复流程;回收或保存失败保留原任务与草稿。回收开始后离页仍完成同账号的草稿恢复,仅取消跳转;账号切换后停止旧账号操作,并移除旧代次的内存创建记录及同步阻挡,避免切回原账号后阻塞发件箱恢复;保留持久发件箱草稿,不执行远端删除。