Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 自动恢复发送等待并延后显示阶段提示 (#3966)
Dash70f7a2fcf473
diff --git a/apps/desktop/src/renderer/hooks/__tests__/useAvailableAgents.test.ts b/apps/desktop/src/renderer/hooks/__tests__/useAvailableAgents.test.tsindex fe950c1502..e488acb2e7 100644--- a/apps/desktop/src/renderer/hooks/__tests__/useAvailableAgents.test.ts+++ b/apps/desktop/src/renderer/hooks/__tests__/useAvailableAgents.test.ts@@ -127,6 +127,43 @@ describe('useAvailableAgents roster cache', () => {await waitFor(() => expect(result.current.availableVendors.has('pi')).toBe(true));});+ it('ignores phone presence without disturbing either known computer, and still refreshes a cached computer', async () => {+ const { api, presenceListeners, statusListeners } = installDeviceLinkApi();+ api.invoke.mockResolvedValue(['claude-code', 'codex']);+ const { useAvailableAgents } = await import('../useAvailableAgents');+ const { prefetchDeviceCapabilities } = await import('../useAgentCapabilities');+ const first = renderHook(() => useAvailableAgents('computer-a'));+ const second = renderHook(() => useAvailableAgents('computer-b'));+ await waitFor(() => expect(first.result.current.loaded && second.result.current.loaded).toBe(true));+ first.unmount(); // Cached devices must still invalidate even without a listener.+ api.invoke.mockClear();+ vi.mocked(prefetchDeviceCapabilities).mockClear();++ await act(async () => {+ for (const online of [true, false, true]) {+ for (const listener of presenceListeners) listener({ deviceId: 'iphone', online });+ }+ });+ expect(api.invoke).not.toHaveBeenCalled();+ expect(prefetchDeviceCapabilities).not.toHaveBeenCalled();+ expect(second.result.current.loaded).toBe(true);++ await act(async () => {+ for (const listener of presenceListeners) listener({ deviceId: 'computer-a', online: true });+ });+ expect(prefetchDeviceCapabilities).toHaveBeenCalledExactlyOnceWith('computer-a');+ const remounted = renderHook(() => useAvailableAgents('computer-a'));+ await waitFor(() => expect(remounted.result.current.loaded).toBe(true));+ expect(api.invoke).toHaveBeenCalledExactlyOnceWith('computer-a', 'maker:list-available-agents', []);++ // The ignored phone must not enter the cache-key set and get probed on relay recovery either.+ await act(async () => {+ for (const listener of statusListeners) listener({ status: 'online' });+ });+ expect(vi.mocked(prefetchDeviceCapabilities).mock.calls.every(([id]) => id !== 'iphone')).toBe(true);+ expect(api.invoke.mock.calls.every(([id]) => id !== 'iphone')).toBe(true);+ });+it('shares one invalidation and result across mounted consumers', async () => {const first = deferred<RuntimeAgentKind[]>();const second = deferred<RuntimeAgentKind[]>();diff --git a/apps/desktop/src/renderer/hooks/useAvailableAgents.ts b/apps/desktop/src/renderer/hooks/useAvailableAgents.tsindex a74970aa2b..84886d0653 100644--- a/apps/desktop/src/renderer/hooks/useAvailableAgents.ts+++ b/apps/desktop/src/renderer/hooks/useAvailableAgents.ts@@ -145,6 +145,10 @@ function remoteRosterKeys(): Set<string> {}function notifyRosterChanged(deviceId?: string): void {+ // Presence includes controller-only phones. Only refresh devices whose roster+ // was actually requested; reverse capability invokes to an iPhone are rejected+ // and can tear down the peer link currently serving that phone's requests.+ if (deviceId && !remoteRosterKeys().has(deviceId)) return;const key = cacheKeyOf(deviceId);if (!invalidateAgentsCache(key)) return;if (deviceId) refreshRemoteCapabilitiesOnce(deviceId);diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex fbb89a3f7c..82e8ea2197 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -213,6 +213,7 @@ import { RecentPhotosStrip, ScreenshotsGrid } from '@/session/ContextSheetMediaVimport { ContextSheetGoalView, goalStatusLabel } from '@/session/ContextSheetGoalView';import { parseGoalLimitsRouteParam } from '@/session/goalLimitsRouteParam';import { ComposerAttachmentCollapsedBadge, ComposerAttachmentTray } from '@/session/ComposerAttachmentTray';+import { SlowSendNotice } from '@/session/SlowSendNotice';import { PlanModeChip } from '@/session/PlanModeChip';import { ImageLightbox } from '@/session/ImageLightbox';import { pickWriteFields, retryPatchWhileLatest, writeGuardFields } from '@/session/swipeRowRegistry';@@ -10066,6 +10067,7 @@ function SessionComposerInput({composerSendUnavailableReason, attachmentCount, pendingUploadCount,onPasteImages, onDragActiveChange, renderControls,}: SessionComposerInputProps) {+ const creationTask = useNewSessionCreationTask(sessionId);const { document: composerDocument, draft } = useSyncExternalStore(source.subscribe, source.getSnapshot);const { t, i18n: i18nInstance } = useTranslation();const { colors } = useTheme();@@ -10420,6 +10422,10 @@ function SessionComposerInput({testID="session.composerScroll">+ <SlowSendNotice+ startedAt={creationTask?.status === 'running' ? creationTask.startedAt : null}+ phase={creationTask?.phase ?? 'preparing'}+ />{attachmentError ? (<Text style={styles.attachmentErrorText} testID="session.attachmentStatus">{attachmentError}diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsxindex 007cd824cf..9753fb86e8 100644--- a/apps/mobile/app/sessions/new.tsx+++ b/apps/mobile/app/sessions/new.tsx@@ -118,6 +118,7 @@ import { RecentPhotosStrip, ScreenshotsGrid } from '@/session/ContextSheetMediaVimport { ContextSheetGoalCreateForm } from '@/session/ContextSheetGoalView';import type { MobileGoalLimitsInput } from '@cindy/maker-shared/device-link-contract';import { ComposerAttachmentCollapsedBadge, ComposerAttachmentTray } from '@/session/ComposerAttachmentTray';+import { SlowSendNotice, type SlowSendPhase } from '@/session/SlowSendNotice';import { ImageLightbox } from '@/session/ImageLightbox';import {useComposerImageAnnotations,@@ -487,6 +488,8 @@ export default function NewRemoteSessionScreen() {workingDir: initialWorkingDir ?? '',});const [creating, setCreating] = useState(false);+ const [createStartedAt, setCreateStartedAt] = useState<number | null>(null);+ const [createPhase, setCreatePhase] = useState<SlowSendPhase>('preparing');const [error, setError] = useState<string | null>(null);const [capabilities, setCapabilities] = useState<MobileAgentCapabilities | null>(null);const [capabilitiesLoading, setCapabilitiesLoading] = useState(false);@@ -4032,6 +4035,9 @@ export default function NewRemoteSessionScreen() {return;}creatingRef.current = true;+ const startedAt = Date.now();+ setCreateStartedAt(startedAt);+ setCreatePhase('preparing');setCreating(true);setError(null);// 乐观交接标记:startNewSessionCreation + router.replace 成功后本页即将@@ -4067,10 +4073,12 @@ export default function NewRemoteSessionScreen() {// 拍照 / 选图后立刻点创建是常见路径:等在途图片上传落定(乐观托盘)。// 有失败就中止创建——错误文案已由上传回调写入 attachmentError,让用户处理;// 此时不该带着残缺附件去开新会话。+ setCreatePhase('uploading');const { failedCount } = await waitForPendingUploads();if (!isCurrentOwner()) return;if (!ensureDeviceAlive()) return;if (failedCount > 0) return;+ setCreatePhase('preparing');// await 之后闭包里的 attachments 是旧值,经 ref 拿含刚落定图片的最新列表。const sendAttachments = attachmentsRef.current;const validation = validateNewSessionDraft(effectiveDraft, { attachmentCount: sendAttachments.length });@@ -4078,21 +4086,7 @@ export default function NewRemoteSessionScreen() {setError(validation);return;}- // 鉴权门禁:已知无已连接供应商时不发起创建(创建即失败,还会白跑一个往返)。- // 目录缓存可能过期(用户刚在电脑端配好 key):拦截前现拉一遍确认;确认不了- // (已连接 / 空目录 / 拉失败)时缓存判死已不可信,清掉重取并放行。- if (agentAuthVerdict === 'unauthenticated') {- if ((await confirmAgentUnauthenticated(effectiveDraft.agentKind, selectedDeviceId)).unauthenticated) {- if (!isCurrentOwner()) return;- if (!ensureDeviceAlive()) return;- setError(agentAuthGateHint(effectiveDraft.agentKind));- return;- }- if (!isCurrentOwner()) return;- // 确认期间切设备 → 不再驱逐(驱逐的是旧设备缓存,继续创建也无意义)。- if (!ensureDeviceAlive()) return;- evictDeviceProviders(selectedDeviceId);- }+ // 鉴权和模型的网络终检集中在后台建链后执行,避免表单先等一轮、管线再等一轮。if (!isCurrentOwner()) return;if (!ensureDeviceAlive()) return;void saveNewSessionPreferences({@@ -4337,6 +4331,7 @@ export default function NewRemoteSessionScreen() {providerId: effectiveDraft.providerId,});const runGuard = () => resolveSubmitGuardCatalog({+ deferRefreshToCreation: true,cached: () => getCachedDeviceProviders(guardDeviceId),gen: () => getDeviceProvidersGen(guardDeviceId),// 强制刷新(codex review P2):fetchDeviceProviders 缓存命中直接返回旧目录,@@ -4418,6 +4413,7 @@ export default function NewRemoteSessionScreen() {: null;if (!isCurrentOwner()) return;startNewSessionCreation({+ startedAt,sessionId,deviceId: deviceIdSnapshot,deviceName: selectedDeviceName,@@ -4511,6 +4507,7 @@ export default function NewRemoteSessionScreen() {if (!handedOff) {creatingRef.current = false;setCreating(false);+ setCreateStartedAt(null);}}}, [@@ -5784,6 +5781,7 @@ export default function NewRemoteSessionScreen() {{attachmentError}</Text>) : null}+ <SlowSendNotice startedAt={creating ? createStartedAt : null} phase={createPhase} />{voiceStatusVisible ? (<View style={styles.voiceStatusRow}><Text style={styles.voiceStatusText} testID="newSession.voiceStatus">diff --git a/apps/mobile/src/__tests__/SlowSendNotice.test.tsx b/apps/mobile/src/__tests__/SlowSendNotice.test.tsxnew file mode 100644index 0000000000..dbaad0c691--- /dev/null+++ b/apps/mobile/src/__tests__/SlowSendNotice.test.tsx@@ -0,0 +1,65 @@+// @vitest-environment jsdom+import { act, type ReactNode } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { SlowSendNotice } from '@/session/SlowSendNotice';+import { i18n } from '@/i18n';++vi.mock('@/components/AppText', async () => {+ const { createElement } = await import('react');+ return { Text: ({ children, accessibilityLiveRegion }: { children?: ReactNode; accessibilityLiveRegion?: string }) =>+ createElement('span', { 'aria-live': accessibilityLiveRegion }, children) };+});+vi.mock('@/theme', async () => {+ const tokens = await import('@/theme/tokens');+ return { ...tokens, useTheme: () => ({ colors: tokens.lightColors }) };+});++let root: Root;+let host: HTMLDivElement;+beforeEach(async () => {+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+ await i18n.changeLanguage('zh-CN');+ vi.useFakeTimers();+ vi.setSystemTime(0);+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+});+afterEach(() => {+ act(() => root.unmount());+ host.remove();+ vi.useRealTimers();+});++describe('SlowSendNotice', () => {+ it('adds no text or layout for fast sends, including after completion', async () => {+ act(() => root.render(<SlowSendNotice startedAt={0} phase="uploading" />));+ await act(async () => { await vi.advanceTimersByTimeAsync(7_999); });+ expect(host.childElementCount).toBe(0);+ act(() => root.render(<SlowSendNotice startedAt={null} phase="uploading" />));+ await act(async () => { await vi.advanceTimersByTimeAsync(8_000); });+ expect(host.childElementCount).toBe(0);+ expect(vi.getTimerCount()).toBe(0);+ });++ it('shows the current phase after eight seconds without resetting on phase changes', async () => {+ act(() => root.render(<SlowSendNotice startedAt={0} phase="uploading" />));+ await act(async () => { await vi.advanceTimersByTimeAsync(7_000); });+ act(() => root.render(<SlowSendNotice startedAt={0} phase="connecting" />));+ await act(async () => { await vi.advanceTimersByTimeAsync(1_000); });+ expect(host.textContent).toBe('正在连接电脑…');+ expect(host.querySelector('span')?.getAttribute('aria-live')).toBe('polite');+ act(() => root.render(<SlowSendNotice startedAt={0} phase="sending" />));+ expect(host.textContent).toBe('正在发送消息…');+ act(() => root.render(<SlowSendNotice startedAt={8_000} phase="uploading" />));+ expect(host.childElementCount).toBe(0);+ });++ it('preserves elapsed time when the destination page mounts after handoff', async () => {+ vi.setSystemTime(10_000);+ act(() => root.render(<SlowSendNotice startedAt={0} phase="creating" />));+ await act(async () => { await vi.advanceTimersByTimeAsync(0); });+ expect(host.textContent).toBe('正在创建任务…');+ });+});diff --git a/apps/mobile/src/__tests__/mobileAttachmentUpload.test.ts b/apps/mobile/src/__tests__/mobileAttachmentUpload.test.tsindex 28244e6802..76e3f6ac63 100644--- a/apps/mobile/src/__tests__/mobileAttachmentUpload.test.ts+++ b/apps/mobile/src/__tests__/mobileAttachmentUpload.test.ts@@ -189,7 +189,7 @@ describe('mobileAttachmentUpload', () => {expect(uploadFile).toHaveBeenCalledWith('https://oss.example/upload', 'file:///tmp/photo.png', {'Content-Type': 'image/png','x-oss-object-acl': 'private',- }, { signal: expect.any(AbortSignal) });+ }, { signal: expect.any(AbortSignal), onProgress: expect.any(Function) });});it('returns an OSS-ref attachment after successful native file upload', async () => {@@ -221,7 +221,7 @@ describe('mobileAttachmentUpload', () => {expect(uploadFile).toHaveBeenCalledWith('https://oss.example/upload', 'file:///tmp/photo.png', {'Content-Type': 'image/png','x-oss-object-acl': 'private',- }, { signal: expect.any(AbortSignal) });+ }, { signal: expect.any(AbortSignal), onProgress: expect.any(Function) });expect(attachment).toMatchObject({id: 'mobile-upload-2',name: 'photo.png',@@ -276,7 +276,7 @@ describe('mobileAttachmentUpload', () => {'https://oss.example/upload','file:///cache/upload-snapshot.png',expect.any(Object),- { signal: expect.any(AbortSignal) },+ { signal: expect.any(AbortSignal), onProgress: expect.any(Function) },);expect(cleanup).toHaveBeenCalledTimes(1);});@@ -324,7 +324,7 @@ describe('mobileAttachmentUpload', () => {'Content-Type': 'application/octet-stream','x-oss-object-acl': 'private',},- { signal: expect.any(AbortSignal) },+ { signal: expect.any(AbortSignal), onProgress: expect.any(Function) },);});@@ -399,28 +399,123 @@ describe('mobileAttachmentUpload', () => {expect(uploadFile).toHaveBeenCalledTimes(2);});- it('times out a hung native file PUT (no second 120s round) instead of hanging forever', async () => {- // 回归:iOS 前台 NSURLSession 只在「60s 无字节流动」时自行超时,慢速涓涓细流- // 可以合法挂很多分钟——JS 层必须有自己的超时出口,且超时不进第二轮重试。+ it('settles after bounded automatic recovery even when native upload ignores abort', async () => {vi.useFakeTimers();try {- const uploadFile = vi.fn((_url: string, _fileUri: string, _headers: Record<string, string>, opts?: { signal?: AbortSignal }) =>- new Promise<{ status: number }>((_resolve, reject) => {- opts?.signal?.addEventListener('abort', () => reject(new Error('附件上传已取消。')));- }));+ const uploadFile = vi.fn(() => new Promise<{ status: number }>(() => {}));const pending = putMobileAttachmentUploadFromFile('https://oss.example/upload', 'file:///tmp/x.png', 'image/png', {uploadFile,});const expectation = expect(pending).rejects.toThrow('附件上传超时,请检查网络后重试。');- await vi.advanceTimersByTimeAsync(120_000);+ await vi.advanceTimersByTimeAsync(120_800);await expectation;- expect(uploadFile).toHaveBeenCalledTimes(1);+ expect(uploadFile).toHaveBeenCalledTimes(2);} finally {vi.useRealTimers();}});+ it('automatically recovers a stuck PUT using the same bytes and ignores its late success', async () => {+ vi.useFakeTimers();+ try {+ let resolveFirst!: (value: { status: number }) => void;+ const uploadFile = vi.fn()+ .mockImplementationOnce(() => new Promise((resolve) => { resolveFirst = resolve; }))+ .mockResolvedValueOnce({ status: 200 });+ const onLateSuccess = vi.fn();+ const pending = putMobileAttachmentUploadFromFile('https://oss.example/upload', 'file:///tmp/x.png', 'image/png', { uploadFile }, { onLateSuccess });+ await vi.advanceTimersByTimeAsync(60_800);+ await pending;+ expect(uploadFile).toHaveBeenCalledTimes(2);+ expect(uploadFile.mock.calls[0].slice(0, 3)).toEqual(uploadFile.mock.calls[1].slice(0, 3));+ expect(uploadFile.mock.calls[0][3].signal.aborted).toBe(true);+ resolveFirst({ status: 200 });+ await vi.advanceTimersByTimeAsync(0);+ expect(onLateSuccess).not.toHaveBeenCalled();+ } finally { vi.useRealTimers(); }+ });++ it('reclaims a late native success after all attempts failed', async () => {+ vi.useFakeTimers();+ try {+ let resolveFirst!: (value: { status: number }) => void;+ const uploadFile = vi.fn()+ .mockImplementationOnce(() => new Promise((resolve) => { resolveFirst = resolve; }))+ .mockResolvedValueOnce({ status: 403 });+ const onLateSuccess = vi.fn();+ const pending = putMobileAttachmentUploadFromFile('https://oss.example/upload', 'file:///tmp/x.png', 'image/png', { uploadFile }, { onLateSuccess });+ const failed = expect(pending).rejects.toThrow('HTTP 403');+ await vi.advanceTimersByTimeAsync(60_800);+ await failed;+ resolveFirst({ status: 200 });+ await vi.advanceTimersByTimeAsync(0);+ expect(onLateSuccess).toHaveBeenCalledTimes(1);+ } finally { vi.useRealTimers(); }+ });++ it.each([408, 429, 503])('automatically recovers a temporary HTTP %s failure', async (status) => {+ const uploadFile = vi.fn().mockResolvedValueOnce({ status }).mockResolvedValueOnce({ status: 200 });+ await putMobileAttachmentUploadFromFile('https://oss.example/upload', 'file:///tmp/x.png', 'image/png', { uploadFile });+ expect(uploadFile).toHaveBeenCalledTimes(2);+ });++ it('bounds Blob uploads even when fetch ignores abort', async () => {+ vi.useFakeTimers();+ try {+ const fetchPut = vi.fn(() => new Promise<Response>(() => {}));+ const pending = putMobileAttachmentUpload('https://oss.example/upload', new Blob(['x']), 'text/plain', { fetch: fetchPut });+ const failed = expect(pending).rejects.toThrow('附件上传超时');+ await vi.advanceTimersByTimeAsync(240_800);+ await failed;+ expect(fetchPut).toHaveBeenCalledTimes(2);+ } finally { vi.useRealTimers(); }+ });++ it('lets a slow native upload continue while bytes advance and retires its progress callback', async () => {+ vi.useFakeTimers();+ try {+ let finish!: (value: { status: number }) => void;+ let progress!: (bytes: number) => void;+ let signal!: AbortSignal;+ const uploadFile = vi.fn((_url, _uri, _headers, opts) => {+ progress = opts.onProgress;+ signal = opts.signal;+ return new Promise<{ status: number }>((resolve) => { finish = resolve; });+ });+ const pending = putMobileAttachmentUploadFromFile('https://oss.example/upload', 'file:///tmp/x.png', 'image/png', { uploadFile });+ await vi.advanceTimersByTimeAsync(50_000);+ progress(100);+ await vi.advanceTimersByTimeAsync(40_000);+ expect(signal.aborted).toBe(false);+ expect(uploadFile).toHaveBeenCalledTimes(1);+ finish({ status: 200 });+ await pending;+ progress(200);+ expect(vi.getTimerCount()).toBe(0);+ } finally { vi.useRealTimers(); }+ });++ it('duplicate progress events cannot keep a stalled native upload alive', async () => {+ vi.useFakeTimers();+ try {+ let progress!: (bytes: number) => void;+ const uploadFile = vi.fn()+ .mockImplementationOnce((_url, _uri, _headers, opts) => {+ progress = opts.onProgress;+ return new Promise(() => {});+ })+ .mockResolvedValueOnce({ status: 200 });+ const pending = putMobileAttachmentUploadFromFile('https://oss.example/upload', 'file:///tmp/x.png', 'image/png', { uploadFile });+ progress(100);+ await vi.advanceTimersByTimeAsync(50_000);+ progress(100);+ await vi.advanceTimersByTimeAsync(10_800);+ await pending;+ expect(uploadFile).toHaveBeenCalledTimes(2);+ } finally { vi.useRealTimers(); }+ });+it('propagates external cancellation without retrying', async () => {const outer = new AbortController();const uploadFile = vi.fn((_url: string, _fileUri: string, _headers: Record<string, string>, opts?: { signal?: AbortSignal }) =>diff --git a/apps/mobile/src/__tests__/mobileLocalAttachmentUpload.test.ts b/apps/mobile/src/__tests__/mobileLocalAttachmentUpload.test.tsindex a7688241e5..f4c39a4673 100644--- a/apps/mobile/src/__tests__/mobileLocalAttachmentUpload.test.ts+++ b/apps/mobile/src/__tests__/mobileLocalAttachmentUpload.test.ts@@ -101,6 +101,65 @@ describe('isCameraUnavailableOnSimulator', () => {});describe('createMobileLocalAttachmentUploadController', () => {+ it('releases send waiters when credential preparation never settles and preserves the attachment', async () => {+ vi.useFakeTimers();+ try {+ const { deps, pendingSnapshots, uploaded, failed } = makeDeps();+ const controller = createMobileLocalAttachmentUploadController(deps);+ controller.enqueue([candidate('a.jpg')], { token: new Promise(() => {}) });+ const pending = controller.waitForIdle();+ await vi.advanceTimersByTimeAsync(180_000);+ expect(await pending).toEqual({ failedCount: 1 });+ expect(uploaded).toEqual([]);+ expect(failed).toHaveLength(1);+ expect(pendingSnapshots.at(-1)?.[0]).toMatchObject({ name: 'a.jpg', failed: true });+ controller.dispose();+ } finally { vi.useRealTimers(); }+ });++ it('a timed-out source cannot publish into a subsequent retry and only its temporary result is cleaned', async () => {+ vi.useFakeTimers();+ try {+ let resolveSource!: (value: { uri: string }) => void;+ const cleanupLocalUris = vi.fn(async () => {});+ const source = { ...candidate('a.jpg'), cleanupLocalUris, resolve: vi.fn()+ .mockImplementationOnce(() => new Promise((resolve) => { resolveSource = resolve; }))+ .mockResolvedValueOnce({ uri: 'file:///tmp/retry.jpg' }) };+ const { deps, uploaded, pendingSnapshots } = makeDeps();+ const controller = createMobileLocalAttachmentUploadController(deps);+ controller.enqueue([source], { token: 't' });+ await vi.advanceTimersByTimeAsync(180_000);+ const id = pendingSnapshots.at(-1)![0].localId;+ controller.retry(id, { token: 't' });+ await vi.advanceTimersByTimeAsync(0);+ await controller.waitForIdle();+ resolveSource({ uri: 'file:///tmp/late.jpg' });+ await vi.advanceTimersByTimeAsync(0);+ expect(uploaded).toHaveLength(1);+ expect(uploaded[0].candidate.uri).toBe('file:///tmp/retry.jpg');+ expect(cleanupLocalUris).toHaveBeenCalledWith(['file:///tmp/late.jpg']);+ expect(cleanupLocalUris.mock.calls.flat(2)).not.toContain(source.uri);+ controller.dispose();+ } finally { vi.useRealTimers(); }+ });++ it('reclaims an upload arriving after the total deadline without publishing it', async () => {+ vi.useFakeTimers();+ try {+ const gate = gatedUpload();+ const { deps, uploaded, discarded } = makeDeps({ upload: gate.upload });+ const controller = createMobileLocalAttachmentUploadController(deps);+ controller.enqueue([candidate('a.jpg')], { token: 't' });+ await vi.advanceTimersByTimeAsync(180_000);+ expect(await controller.waitForIdle()).toEqual({ failedCount: 1 });+ gate.release('a.jpg');+ await vi.advanceTimersByTimeAsync(0);+ expect(uploaded).toEqual([]);+ expect(discarded).toEqual([attachmentFor('a.jpg')]);+ controller.dispose();+ } finally { vi.useRealTimers(); }+ });+it('enqueue 后立即出现在 pending,上传成功后回调宿主并清空 pending', async () => {const { deps, pendingSnapshots, uploaded } = makeDeps();const controller = createMobileLocalAttachmentUploadController(deps);diff --git a/apps/mobile/src/__tests__/newSession.test.ts b/apps/mobile/src/__tests__/newSession.test.tsindex 48dfee5969..2db83801fe 100644--- a/apps/mobile/src/__tests__/newSession.test.ts+++ b/apps/mobile/src/__tests__/newSession.test.ts@@ -205,6 +205,22 @@ describe('resolveSubmitGuardCatalog —— 提交终检目录取信(代际安全buildRows: (pl: DeviceProvidersPayload) => rowsOf((pl as TestPayload).id),};+ it('ordinary creation hands off without awaiting a hung catalog refresh', async () => {+ const fetch = vi.fn(() => new Promise<TestPayload>(() => {}));+ const result = await resolveSubmitGuardCatalog({ ...baseArgs, fetch, cached: () => payload('cached'), deferRefreshToCreation: true });+ expect(result).toEqual({ rows: [], catalogKnown: false, genAt: 1 });+ const selected = { model: 'newly-connected-model', providerId: 'newly-connected-provider' };+ expect(resolveRecentModelAndProvider(result.rows, selected, 'codex', result.catalogKnown)).toEqual(selected);+ expect(fetch).not.toHaveBeenCalled();+ });++ it('defers an evicted catalog to the post-link check without trusting stale rows', async () => {+ const fetch = vi.fn(baseArgs.fetch);+ const result = await resolveSubmitGuardCatalog({ ...baseArgs, fetch, deferRefreshToCreation: true });+ expect(result).toEqual({ rows: [], catalogKnown: false, genAt: 1 });+ expect(fetch).not.toHaveBeenCalled();+ });+it('缓存命中 → join fetch revalidate,成功用新目录(工作站已换 provider,codex review P1)', async () => {const fetchSpy = vi.fn(baseArgs.fetch);const res = await resolveSubmitGuardCatalog({diff --git a/apps/mobile/src/__tests__/newSessionCreation.test.ts b/apps/mobile/src/__tests__/newSessionCreation.test.tsindex 1ad5c08d41..9ce6bde956 100644--- a/apps/mobile/src/__tests__/newSessionCreation.test.ts+++ b/apps/mobile/src/__tests__/newSessionCreation.test.ts@@ -626,6 +626,8 @@ describe('newSessionCreation pipeline', () => {},}),status: 'create-failed' as const,+ startedAt: 0,+ phase: 'creating' as const,error: 'create failed',firstMessageClientId: 'client-override',};diff --git a/apps/mobile/src/i18n/locales/en/session.json b/apps/mobile/src/i18n/locales/en/session.jsonindex f902bd31d5..da5e721e80 100644--- a/apps/mobile/src/i18n/locales/en/session.json+++ b/apps/mobile/src/i18n/locales/en/session.json@@ -268,6 +268,14 @@"composerPlaceholder": "What should we work on today?","voiceSelectDeviceFirst": "Select a device before using voice input.","creatingSession": "Creating session",+ "slowSend": {+ "preparing": "Preparing to send…",+ "uploading": "Uploading attachments…",+ "connecting": "Connecting to your computer…",+ "checkingModel": "Checking model settings…",+ "creating": "Creating session…",+ "sending": "Sending your message…"+ },"createAndSend": "Create session and send first message","modelAccessibility": "Model: {{model}}","voiceInput": "Voice input",diff --git a/apps/mobile/src/i18n/locales/ja/session.json b/apps/mobile/src/i18n/locales/ja/session.jsonindex 50a30e80a8..dd47a0dedd 100644--- a/apps/mobile/src/i18n/locales/ja/session.json+++ b/apps/mobile/src/i18n/locales/ja/session.json@@ -268,6 +268,14 @@"composerPlaceholder": "今日は何をしましょうか〜","voiceSelectDeviceFirst": "デバイスを選択してから音声入力を使用してください。","creatingSession": "セッションを作成中",+ "slowSend": {+ "preparing": "送信を準備中…",+ "uploading": "添付ファイルをアップロード中…",+ "connecting": "コンピュータに接続中…",+ "checkingModel": "モデル設定を確認中…",+ "creating": "セッションを作成中…",+ "sending": "メッセージを送信中…"+ },"createAndSend": "セッションを作成して最初のメッセージを送信","modelAccessibility": "モデル:{{model}}","voiceInput": "音声入力",diff --git a/apps/mobile/src/i18n/locales/ko/session.json b/apps/mobile/src/i18n/locales/ko/session.jsonindex 5d6fea9502..d1493becbc 100644--- a/apps/mobile/src/i18n/locales/ko/session.json+++ b/apps/mobile/src/i18n/locales/ko/session.json@@ -268,6 +268,14 @@"composerPlaceholder": "오늘 무엇을 해볼까요~","voiceSelectDeviceFirst": "기기를 선택한 후 음성 입력을 사용하세요.","creatingSession": "세션 생성 중",+ "slowSend": {+ "preparing": "전송 준비 중…",+ "uploading": "첨부 파일 업로드 중…",+ "connecting": "컴퓨터에 연결 중…",+ "checkingModel": "모델 설정 확인 중…",+ "creating": "세션 생성 중…",+ "sending": "메시지 전송 중…"+ },"createAndSend": "세션을 만들고 첫 메시지 보내기","modelAccessibility": "모델: {{model}}","voiceInput": "음성 입력",diff --git a/apps/mobile/src/i18n/locales/zh-CN/session.json b/apps/mobile/src/i18n/locales/zh-CN/session.jsonindex 3faf053725..f51575c720 100644--- a/apps/mobile/src/i18n/locales/zh-CN/session.json+++ b/apps/mobile/src/i18n/locales/zh-CN/session.json@@ -268,6 +268,14 @@"composerPlaceholder": "今天我们做点什么呢~","voiceSelectDeviceFirst": "请选择设备后再使用语音输入。","creatingSession": "正在创建任务",+ "slowSend": {+ "preparing": "正在准备发送…",+ "uploading": "正在上传附件…",+ "connecting": "正在连接电脑…",+ "checkingModel": "正在检查模型设置…",+ "creating": "正在创建任务…",+ "sending": "正在发送消息…"+ },"createAndSend": "创建任务并发送首条消息","modelAccessibility": "模型:{{model}}","voiceInput": "语音输入",diff --git a/apps/mobile/src/i18n/locales/zh-TW/session.json b/apps/mobile/src/i18n/locales/zh-TW/session.jsonindex 62689a142b..56a73144aa 100644--- a/apps/mobile/src/i18n/locales/zh-TW/session.json+++ b/apps/mobile/src/i18n/locales/zh-TW/session.json@@ -268,6 +268,14 @@"composerPlaceholder": "今天我們做點什麼呢~","voiceSelectDeviceFirst": "請選擇裝置後再使用語音輸入。","creatingSession": "正在建立任務",+ "slowSend": {+ "preparing": "正在準備傳送…",+ "uploading": "正在上傳附件…",+ "connecting": "正在連接電腦…",+ "checkingModel": "正在檢查模型設定…",+ "creating": "正在建立任務…",+ "sending": "正在傳送訊息…"+ },"createAndSend": "建立任務並傳送首條訊息","modelAccessibility": "模型:{{model}}","voiceInput": "語音輸入",diff --git a/apps/mobile/src/session/SlowSendNotice.tsx b/apps/mobile/src/session/SlowSendNotice.tsxnew file mode 100644index 0000000000..e1eefa3d03--- /dev/null+++ b/apps/mobile/src/session/SlowSendNotice.tsx@@ -0,0 +1,30 @@+import { useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { Text } from '@/components/AppText';+import { lineHeight, typeScale, useTheme } from '@/theme';++export type SlowSendPhase = 'preparing' | 'uploading' | 'connecting' | 'checkingModel' | 'creating' | 'sending';+export const SLOW_SEND_NOTICE_DELAY_MS = 8_000;++/** Fast sends add no text or layout space; one elapsed clock survives phase changes. */+export function SlowSendNotice({ startedAt, phase }: { startedAt: number | null; phase: SlowSendPhase }) {+ const { t } = useTranslation();+ const { colors } = useTheme();+ const [visibleFor, setVisibleFor] = useState<number | null>(null);+ useEffect(() => {+ setVisibleFor(null);+ if (startedAt === null) return;+ const timer = setTimeout(() => setVisibleFor(startedAt), Math.max(0, startedAt + SLOW_SEND_NOTICE_DELAY_MS - Date.now()));+ return () => clearTimeout(timer);+ }, [startedAt]);+ if (startedAt === null || visibleFor !== startedAt) return null;+ return (+ <Text+ accessibilityLiveRegion="polite"+ style={{ color: colors.textSecondary, fontSize: typeScale.caption, lineHeight: lineHeight.caption }}+ testID="session.slowSendNotice"+ >+ {t(`session.new.slowSend.${phase}`)}+ </Text>+ );+}diff --git a/apps/mobile/src/session/mobileAttachmentUpload.ts b/apps/mobile/src/session/mobileAttachmentUpload.tsindex 8c9612f26f..38e2089cc4 100644--- a/apps/mobile/src/session/mobileAttachmentUpload.ts+++ b/apps/mobile/src/session/mobileAttachmentUpload.ts@@ -35,7 +35,7 @@ export type MobileAttachmentFileUploader = (putUrl: string,fileUri: string,headers: Record<string, string>,- opts?: { signal?: AbortSignal },+ opts?: { signal?: AbortSignal; onProgress?: (bytesSent: number) => void },) => Promise<{ status: number; body?: string }>;interface UploadDeps {@@ -86,14 +86,6 @@ export async function presignMobileAttachmentUpload(return normalizePresignResult(result);}-/**- * Blob PUT 的整体超时:Android 的 RN fetch 没有默认超时,弱网僵死会让上传- * (以及等它的发送按钮)无限挂起。上限放宽到 2 分钟,给慢速蜂窝网上传大附件- * 留足余量;body 是 Blob 可复用,传输层失败(拿不到 HTTP 响应)重试一次,- * 与原生文件直传路径(putMobileAttachmentUploadFromFile)同口径。- */-const PUT_BLOB_TIMEOUT_MS = 120_000;-export async function putMobileAttachmentUpload(putUrl: string,body: MobileAttachmentUploadBody,@@ -101,31 +93,18 @@ export async function putMobileAttachmentUpload(deps: UploadDeps = {},): Promise<void> {const fetchImpl = deps.fetch ?? fetch;- let transportError: unknown;- for (let attempt = 0; attempt < UPLOAD_TRANSPORT_ATTEMPTS; attempt += 1) {- const controller = new AbortController();- const timer = setTimeout(() => controller.abort(), PUT_BLOB_TIMEOUT_MS);- let response: Response;- try {- response = await fetchImpl(putUrl, {- method: 'PUT',- headers: buildMobileAttachmentUploadHeaders(mimeType),- body,- signal: controller.signal,- });- } catch (err) {- transportError = err;- continue;- } finally {- clearTimeout(timer);- }- if (!response.ok) {- const code = extractOssErrorCode(await readResponseTextSafe(response));- throw new Error(i18n.t('composer.upload.failedHttp', { status: response.status, code: code ? ` (${code})` : '' }));- }- return;- }- throw new Error(i18n.t('composer.upload.failedNetwork', { detail: summarizeTransportError(transportError) }));+ await putAttachmentWithRecovery(async (signal) => {+ const response = await fetchImpl(putUrl, {+ method: 'PUT',+ headers: buildMobileAttachmentUploadHeaders(mimeType),+ body,+ signal,+ });+ return {+ status: response.status,+ body: response.ok ? undefined : await readResponseTextSafe(response),+ };+ });}function buildMobileAttachmentUploadHeaders(mimeType: string | undefined): Record<string, string> {@@ -169,7 +148,7 @@ async function uploadFileNative(putUrl: string,fileUri: string,headers: Record<string, string>,- opts: { signal?: AbortSignal } = {},+ opts: { signal?: AbortSignal; onProgress?: (bytesSent: number) => void } = {},): Promise<{ status: number; body?: string }> {const FileSystem = await import('expo-file-system/legacy');if (opts.signal?.aborted) throw new Error(uploadAbortedMessage());@@ -178,7 +157,7 @@ async function uploadFileNative(httpMethod: 'PUT',sessionType: FileSystem.FileSystemSessionType.FOREGROUND,uploadType: FileSystem.FileSystemUploadType.BINARY_CONTENT,- });+ }, (progress) => opts.onProgress?.(progress.totalBytesSent));const onAbort = () => {void task.cancelAsync().catch(() => undefined);};@@ -193,68 +172,109 @@ async function uploadFileNative(}}-/** 传输层异常(拿不到 HTTP 响应)总尝试次数:失败自动重试 1 次。 */+/** 同一签名地址、同一份不可变字节最多两次 PUT,不重新创建附件或发送消息。 */const UPLOAD_TRANSPORT_ATTEMPTS = 2;--/**- * 原生文件直传的单次尝试超时,与 Blob 版 PUT_BLOB_TIMEOUT_MS 同口径:iOS 前台- * NSURLSession 只在「60s 完全无字节流动」时才自行超时,慢速蜂窝网上传大附件- * (上限 30MB)可以合法地涓涓细流挂很多分钟,期间发送等待没有任何出口。- * 超时不进传输层重试(两轮 120s 太久),直接报错让用户看到失败卡原地重试。- */-const PUT_FILE_TIMEOUT_MS = 120_000;+const PUT_IDLE_TIMEOUT_MS = 60_000;+const PUT_ATTEMPT_TIMEOUT_MS = 120_000;+const PUT_RETRY_DELAY_MS = 800;// i18n 文案取值放函数里(而非模块顶层常量):模块顶层求值会把语言冻结在加载时刻,// LocaleProvider 挂载后的语言切换就读不到,故在抛错点当场求值。const uploadAbortedMessage = () => i18n.t('composer.upload.cancelled');const uploadTimeoutMessage = () => i18n.t('composer.upload.timeout');+interface UploadRecoveryOptions {+ signal?: AbortSignal;+ /** 最终失败后原生 PUT 仍迟到成功时,再回收中转对象。 */+ onLateSuccess?: () => void;+}++async function putAttachmentWithRecovery(+ send: (signal: AbortSignal, onProgress: (bytesSent: number) => void) => Promise<{ status: number; body?: string }>,+ opts: UploadRecoveryOptions = {},+ reportsProgress = false,+): Promise<void> {+ let terminalFailure = false;+ let lastError: unknown;+ try {+ for (let attempt = 0; attempt < UPLOAD_TRANSPORT_ATTEMPTS; attempt += 1) {+ if (opts.signal?.aborted) throw new Error(uploadAbortedMessage());+ const controller = new AbortController();+ let rejectWait!: (error: Error) => void;+ const interrupted = new Promise<never>((_resolve, reject) => { rejectWait = reject; });+ const cancel = () => {+ rejectWait(new Error(uploadAbortedMessage()));+ controller.abort();+ };+ opts.signal?.addEventListener('abort', cancel);+ // Reject the JS wait independently of native cancellation. Some native calls+ // never settle even after cancelAsync; their late result cannot win this attempt.+ const expire = () => {+ rejectWait(new Error(uploadTimeoutMessage()));+ controller.abort();+ };+ const timer = setTimeout(expire, PUT_ATTEMPT_TIMEOUT_MS);+ // fetch 没有进度事件,保留完整单次预算;原生上传只在字节停滞时提前恢复。+ let idleTimer = setTimeout(expire, reportsProgress ? PUT_IDLE_TIMEOUT_MS : PUT_ATTEMPT_TIMEOUT_MS);+ let lastBytesSent = 0;+ let settled = false;+ const onProgress = (bytesSent: number) => {+ if (settled || controller.signal.aborted || !Number.isFinite(bytesSent) || bytesSent <= lastBytesSent) return;+ lastBytesSent = bytesSent;+ clearTimeout(idleTimer);+ idleTimer = setTimeout(expire, PUT_IDLE_TIMEOUT_MS);+ };+ let result: { status: number; body?: string };+ try {+ result = await Promise.race([+ send(controller.signal, onProgress).then((value) => {+ if (terminalFailure && value.status >= 200 && value.status < 300) opts.onLateSuccess?.();+ return value;+ }),+ interrupted,+ ]);+ } catch (error) {+ if (opts.signal?.aborted) throw new Error(uploadAbortedMessage());+ lastError = controller.signal.aborted+ ? new Error(uploadTimeoutMessage())+ : new Error(i18n.t('composer.upload.failedNetwork', { detail: summarizeTransportError(error) }));+ result = { status: 0 };+ } finally {+ settled = true;+ clearTimeout(timer);+ clearTimeout(idleTimer);+ opts.signal?.removeEventListener('abort', cancel);+ }+ if (result.status >= 200 && result.status < 300) return;+ if (result.status !== 0) {+ const code = extractOssErrorCode(result.body);+ lastError = new Error(i18n.t('composer.upload.failedHttp', {+ status: result.status, code: code ? ` (${code})` : '',+ }));+ // 权限、签名和内容错误不会因重试恢复;仅自动恢复临时传输/服务错误。+ if (result.status !== 408 && result.status !== 429 && result.status < 500) throw lastError;+ }+ if (attempt + 1 < UPLOAD_TRANSPORT_ATTEMPTS) {+ await new Promise<void>((resolve) => setTimeout(resolve, PUT_RETRY_DELAY_MS));+ }+ }+ throw lastError;+ } catch (error) {+ terminalFailure = true;+ throw error;+ }+}+export async function putMobileAttachmentUploadFromFile(putUrl: string,fileUri: string,mimeType: string | undefined,deps: UploadDeps = {},- opts: { signal?: AbortSignal } = {},+ opts: UploadRecoveryOptions = {},): Promise<void> {const uploadFile = deps.uploadFile ?? uploadFileNative;const headers = buildMobileAttachmentUploadHeaders(mimeType);- // 原生传输层异常(如 iOS NSURLError,连 HTTP 响应都没拿到)自动重试一次;- // 拿到 HTTP 状态码的失败(403 签名/权限类)重试无意义,直接抛。- let transportError: unknown;- for (let attempt = 0; attempt < UPLOAD_TRANSPORT_ATTEMPTS; attempt += 1) {- if (opts.signal?.aborted) throw new Error(uploadAbortedMessage());- // 每次尝试独立的超时窗;外部取消(用户 X 掉 / 页面退出)与超时共用一个- // 传给传输层的 signal,层内只管断传输,这里负责把两种中止分诊成不同结局。- const timeout = new AbortController();- const timer = setTimeout(() => timeout.abort(), PUT_FILE_TIMEOUT_MS);- const onOuterAbort = () => timeout.abort();- if (opts.signal) opts.signal.addEventListener('abort', onOuterAbort);- let status: number;- let body: string | undefined;- try {- ({ status, body } = await uploadFile(putUrl, fileUri, headers, {- signal: timeout.signal,- }));- } catch (err) {- // 外部取消:立刻收手,不重试(调用方自己发起的中止,静默语义由上层决定)。- if (opts.signal?.aborted) throw new Error(uploadAbortedMessage());- // 超时:不进第二轮(再等 120s 只会让用户在失败卡出现前多干等一轮),直接报错。- if (timeout.signal.aborted) throw new Error(uploadTimeoutMessage());- transportError = err;- continue;- } finally {- clearTimeout(timer);- if (opts.signal) opts.signal.removeEventListener('abort', onOuterAbort);- }- if (status < 200 || status >= 300) {- // 拿到 HTTP 状态码的失败重试无意义,直接抛;带上 OSS 错误 Code- // (SignatureDoesNotMatch / AccessDenied / …),否则裸 403 无法定位。- const code = extractOssErrorCode(body);- throw new Error(i18n.t('composer.upload.failedHttp', { status, code: code ? ` (${code})` : '' }));- }- return;- }- throw new Error(i18n.t('composer.upload.failedNetwork', { detail: summarizeTransportError(transportError) }));+ await putAttachmentWithRecovery((signal, onProgress) => uploadFile(putUrl, fileUri, headers, { signal, onProgress }), opts, true);}/** 原生 NSError 描述冗长(整条预签名 URL 都在里面),截前段给用户当排查线索即可。 */@@ -337,7 +357,10 @@ export async function uploadMobileAttachmentFromFile(snapshot.uri,candidate.mimeType,options.deps,- { signal: options.signal },+ {+ signal: options.signal,+ onLateSuccess: () => { void deleteMobileAttachmentUpload(presigned.key, options).catch(() => undefined); },+ },);} catch (error) {await deleteMobileAttachmentUpload(presigned.key, options).catch(() => undefined);diff --git a/apps/mobile/src/session/mobileLocalAttachmentUpload.ts b/apps/mobile/src/session/mobileLocalAttachmentUpload.tsindex 6bd1145bc7..a18e3f7074 100644--- a/apps/mobile/src/session/mobileLocalAttachmentUpload.ts+++ b/apps/mobile/src/session/mobileLocalAttachmentUpload.ts@@ -283,9 +283,34 @@ export function createMobileLocalAttachmentUploadController(// 同步 throw(如已知 size 的超限校验)不会在 enqueue 调用栈里就把任务清掉。await Promise.resolve();let outcome: TaskOutcome = 'failed';+ // 覆盖 token、相册读取、预处理和上传后的缩略图落盘,不能只给 HTTP 配超时。+ // 捕获本轮 signal:失败卡重试会换 controller,迟到结果仍属于旧轮。+ const signal = task.abort.signal;+ let rejectWait!: (error: Error) => void;+ let timedOut = false;+ const interrupted = new Promise<never>((_resolve, reject) => { rejectWait = reject; });+ const onAbort = () => rejectWait(new Error(i18n.t(timedOut ? 'composer.upload.timeout' : 'composer.upload.cancelled')));+ signal.addEventListener('abort', onAbort);+ const timer = setTimeout(() => {+ timedOut = true;+ task.abort.abort();+ }, 180_000);+ const step = <T>(value: T | Promise<T>, late?: (result: T) => void): Promise<T> => Promise.race([+ Promise.resolve(value).then((result) => {+ if (signal.aborted) late?.(result);+ return result;+ }),+ interrupted,+ ]);+ const cleanupLateFile = (result: { uri?: string }) => {+ if (result.uri && result.uri !== task.candidate.uri) {+ void task.candidate.cleanupLocalUris?.([result.uri]).catch(() => undefined);+ }+ };try {+ if (signal.aborted) onAbort();// token 先就位(可能仍在网络 refresh):拿不到就快速失败,不浪费后面的转码/降采样。- const token = await task.token;+ const token = await step(task.token);if (!token) {throw new Error(task.candidate.kind === 'image'? i18n.t('composer.upload.sessionExpiredImage')@@ -299,19 +324,19 @@ export function createMobileLocalAttachmentUploadController(// 先跑 candidate 自带的就位钩子(相册换址 / HEIC 转码),结果覆盖进管线输入。let source = task.candidate;if (source.resolve) {- source = { ...source, ...(await source.resolve()) };+ source = { ...source, ...(await step(source.resolve(), cleanupLateFile)) };}task.localUris.add(source.uri);// 只有图片需要降采样;文件(pdf / office / 文本)与已优化产物原样直传。const prepared = source.kind === 'image' && !source.skipPreprocess- ? await deps.preprocess({+ ? await step(deps.preprocess({uri: source.uri,name: source.name,mimeType: source.mimeType,size: source.size,width: source.width,height: source.height,- })+ }), cleanupLateFile): {uri: source.uri,name: source.name,@@ -319,7 +344,7 @@ export function createMobileLocalAttachmentUploadController(size: source.size,};task.localUris.add(prepared.uri);- const size = prepared.size > 0 ? prepared.size : await deps.statSize(prepared.uri);+ const size = prepared.size > 0 ? prepared.size : await step(deps.statSize(prepared.uri));deps.assertSize(size, task.candidate);// 取消检查点 2:资产就位 / 降采样(大图慢路径)期间被 X 掉的任务在发起 PUT 前短路// ——PUT 一旦开始便不可中止,只能事后 best-effort 删除,这里拦住就不产生 OSS 孤儿风险。@@ -327,11 +352,11 @@ export function createMobileLocalAttachmentUploadController(outcome = 'discarded';return;}- const attachment = await deps.upload(+ const attachment = await step(deps.upload({ name: prepared.name, size, mimeType: prepared.mimeType || undefined },prepared.uri,- { token, signal: task.abort.signal },- );+ { token, signal },+ ), deps.discard);if (task.discarded) {// 上传成功但用户已 X 掉 / 页面已退出:回收中转对象,不回调宿主。deps.discard(attachment);@@ -340,14 +365,14 @@ export function createMobileLocalAttachmentUploadController(// 回传就位后的 candidate(kind / sourceId 随 spread 保留):resolve 型任务// (相册 ph:// 换址、HEIC / 粘贴转码)实际上传的是 source.uri,宿主的预览// 映射要指向这个仍然在世的 file://,而不是可能被系统回收的原始临时文件。- await deps.onUploaded(+ await step(Promise.resolve(deps.onUploaded(attachment,source,prepared.uri,task.localId,[...task.localUris],- () => !disposed && !task.discarded,- );+ () => !disposed && !task.discarded && !signal.aborted,+ )), () => deps.discard(attachment));if (disposed || task.discarded) {// onUploaded 可能为粘贴图片等待持久缩略图;等待期间退屏 / removeAll// 时不能再把附件写回旧页面,且已经上传的 OSS 对象仍须回收。@@ -365,6 +390,8 @@ export function createMobileLocalAttachmentUploadController(outcome = 'failed';}} finally {+ clearTimeout(timer);+ signal.removeEventListener('abort', onAbort);if (outcome === 'failed' && !disposed) {// 失败卡保留在托盘(state=failed,可 retry / remove),不再从 map 删除——// 弱网下「图直接消失 + 一条 toast」逼用户重新找图重选,原地重试才是对的。diff --git a/apps/mobile/src/session/newSession.ts b/apps/mobile/src/session/newSession.tsindex 2c9e0b64b2..ef0ab88fe4 100644--- a/apps/mobile/src/session/newSession.ts+++ b/apps/mobile/src/session/newSession.ts@@ -451,6 +451,8 @@ export function resolveRecentModelAndProvider(* (循环 ≤3,防代际持续抖动死循环);重拉失败且代际稳定 → 未知 → 信任(fail-open)。*/export async function resolveSubmitGuardCatalog(args: {+ /** 普通创建保留用户选择,由后台建链后的权威目录终检;Goal 不适用。 */+ deferRefreshToCreation?: boolean;/** 设备缓存读取(驱逐即清空;写入受代际门控)。 */cached: () => DeviceProvidersPayload | undefined;/** 当前设备缓存代际(驱逐 +1;0 = 从未驱逐)。 */@@ -461,6 +463,10 @@ export async function resolveSubmitGuardCatalog(args: {buildRows: (payload: DeviceProvidersPayload) => readonly ProviderModelRow[];}): Promise<{ rows: readonly ProviderModelRow[]; catalogKnown: boolean; genAt: number }> {const { cached, gen, fetch, buildRows } = args;+ if (args.deferRefreshToCreation) {+ // 旧缓存可能缺少刚连接的来源,不能先把用户选择回退、再让 fresh 校验这个回退值。+ return { rows: [], catalogKnown: false, genAt: gen() };+ }for (let attempt = 0; attempt < 3; attempt += 1) {const genAt = gen();const hit = cached();diff --git a/apps/mobile/src/session/newSessionCreation.ts b/apps/mobile/src/session/newSessionCreation.tsindex ad883a6379..fd72c5dd27 100644--- a/apps/mobile/src/session/newSessionCreation.ts+++ b/apps/mobile/src/session/newSessionCreation.ts@@ -26,6 +26,7 @@* 会被 dedup 静默吞掉,丢消息比双发更糟)。*/import { useSyncExternalStore } from 'react';+import type { SlowSendPhase } from '@/session/SlowSendNotice';import * as ExpoCrypto from 'expo-crypto';import { isPreconditionFailedRemoteError } from '@cindy/maker-shared/device-link-contract';import { DEFAULT_DRAFT_SESSION_TITLE } from '@cindy/maker-shared/session-title';@@ -70,6 +71,8 @@ export interface NewSessionCreationTransport {}export interface NewSessionCreationParams {+ /** 从按下发送起计时,跨页面交接不重置慢发送提示。 */+ startedAt?: number;sessionId: string;deviceId: string;deviceName: string;@@ -118,6 +121,8 @@ export interface NewSessionCreationParams {}export interface NewSessionCreationTask {+ readonly startedAt: number;+ readonly phase: SlowSendPhase;readonly sessionId: string;readonly deviceId: string;readonly deviceName: string;@@ -135,6 +140,8 @@ export interface NewSessionCreationTask {}interface InternalTask extends NewSessionCreationTask {+ startedAt: number;+ phase: SlowSendPhase;status: NewSessionCreationStatus;error: string | null;firstMessageSessionRefs: MobileSessionReference[];@@ -281,6 +288,8 @@ export function startNewSessionCreation(params: NewSessionCreationParams): void), firstMessageSessionRefs);remoteSessionStore.setInputProjectionOptimistically(params.sessionId, buildOptimisticProjection(params.sessionId, queued));const task: InternalTask = {+ startedAt: params.startedAt ?? Date.now(),+ phase: 'connecting',sessionId: params.sessionId,deviceId: params.deviceId,deviceName: params.deviceName,@@ -312,6 +321,8 @@ export function retryNewSessionCreation(sessionId: string): void {return;}task.status = 'running';+ task.startedAt = Date.now();+ task.phase = 'connecting';task.error = null;// 重试前把乐观行 / 气泡恢复(返回编辑路径可能没走,行一般还在,upsert 幂等)。const session = synthesizeSession(task.params);@@ -876,6 +887,10 @@ function cancelStaleOwnerTask(task: InternalTask): void {}async function runPipeline(task: InternalTask): Promise<void> {+ const phase = (value: SlowSendPhase) => {+ task.phase = value;+ emit();+ };const { params } = task;const { maker, openLink, subscribe } = params.transport;const sessionId = task.sessionId;@@ -904,6 +919,7 @@ async function runPipeline(task: InternalTask): Promise<void> {// 刷新放到建链和订阅之后)——与建链并行启动时,listProviders 可能在建链完成// 前就返回旧目录快照(来源 A),而建链期间工作站已替换为 B,后续拿旧 A 快照// 重验仍会向已删除来源创建。改为建链后拉取,终检目录是「建链后最新」。+ phase('checkingModel');const freshUnauthenticated = (async (): Promise<{ unauthenticated: boolean; fresh: DeviceProvidersPayload | null } | null> => {if (!isTaskOwnerCurrent(task)) return null;try {@@ -933,6 +949,7 @@ async function runPipeline(task: InternalTask): Promise<void> {}const finalDraft: NewSessionDraft = draftPatch ? { ...task.draft, ...draftPatch } : task.draft;+ phase('creating');const createOutcome = await createSessionIdempotent(task, finalDraft);// started 写盘后二次重验可能修正草稿(codex review P2:将 started 后修正的// 草稿传给排队消息)——createOpts 用修正版创建,排队消息合成也必须用同一@@ -948,6 +965,7 @@ async function runPipeline(task: InternalTask): Promise<void> {// 权威会话刷新(dialogue 会话此刻才拿到被控端分配的 workingDir);失败不阻断,// 排队 createOpts 用合成行兜底(project 会话字段本就齐全)。+ phase('sending');let freshSession: RemoteSession | null = null;try {assertTaskOwnerCurrent(task);diff --git a/apps/mobile/src/session/useMobileLocalAttachments.ts b/apps/mobile/src/session/useMobileLocalAttachments.tsindex 49184c51e7..ada8354cc0 100644--- a/apps/mobile/src/session/useMobileLocalAttachments.ts+++ b/apps/mobile/src/session/useMobileLocalAttachments.ts@@ -285,7 +285,7 @@ export function useMobileLocalAttachments(discardMobileUploadedAttachment(attachment, {getToken: () => optionsRef.current.getAccessToken(),});- if (candidate.cleanupLocalUris) await candidate.cleanupLocalUris(localUris);+ if (candidate.cleanupLocalUris) void candidate.cleanupLocalUris(localUris).catch(() => undefined);return;}// 发送后气泡的本地缩略图兜底:消息里持久化的是 cindy-oss-attach:// 中转引用,@@ -313,7 +313,8 @@ export function useMobileLocalAttachments(// 只有持久缩略图已经接管 composer / sent-message 预览后才删源文件;// 注册失败时保留到页面卸载,不能让已上传附件立刻变成坏图。if (deliveredCandidate.uri !== candidate.uri) {- await candidate.cleanupLocalUris(localUris);+ // 附件已交给 composer/outbox,清理失败不能再把成功翻成上传失败。+ void candidate.cleanupLocalUris(localUris).catch(() => undefined);}}},