Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 显示自动重连过程与结果 (#1161)
Chris Zhang0ce5aa9b576b
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex dc06827630..fb5b9d2250 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -3547,7 +3547,7 @@ export default function SessionScreen() {// remoteSessionRunning(activity 推送 / 活跃快照会先置 true,重连场景渲染先于清理)。buildMobileMessageRenderItems(messages,- { isSessionStreaming, renderOrphanTaskUpdates: makerTurnRunning },+ { autoResumePending: inputProjection.autoResumePending, isSessionStreaming, renderOrphanTaskUpdates: makerTurnRunning, sessionId },taskUpdates,),forkOrigin,@@ -3563,7 +3563,7 @@ export default function SessionScreen() {const reconciled = reconcileMobileMessageRenderItems(previous, items);return reconciled;},- [errorTailClientId, forkOrigin, isSessionStreaming, makerTurnRunning, messages, sessionId, taskUpdates],+ [errorTailClientId, forkOrigin, inputProjection.autoResumePending, isSessionStreaming, makerTurnRunning, messages, sessionId, taskUpdates],);// 只在本次 render 真正 commit 后更新 reconcile 基准。写入 useMemo/ref 会让// Concurrent Mode 下被丢弃的 render 泄漏成下一轮的 previous,破坏尾行 memo 的稳定性。diff --git a/apps/mobile/src/__tests__/inputProjection.test.ts b/apps/mobile/src/__tests__/inputProjection.test.tsindex 59fa5446cb..a33a4e5169 100644--- a/apps/mobile/src/__tests__/inputProjection.test.ts+++ b/apps/mobile/src/__tests__/inputProjection.test.ts@@ -352,6 +352,7 @@ describe('inputProjection', () => {queueAbortPending: true,error: 'failed',errorRetryText: 'retry',+ autoResumePending: { error: 'socket hang up', attempt: 2, maxAttempts: 5, sessionTotal: 3 },});expect(projection).toMatchObject({@@ -365,6 +366,7 @@ describe('inputProjection', () => {queueAbortPending: true,error: 'failed',errorRetryText: 'retry',+ autoResumePending: { error: 'socket hang up', attempt: 2, maxAttempts: 5, sessionTotal: 3 },});});diff --git a/apps/mobile/src/__tests__/messageNormalize.test.ts b/apps/mobile/src/__tests__/messageNormalize.test.tsindex 399e65aa91..3ae5708c3f 100644--- a/apps/mobile/src/__tests__/messageNormalize.test.ts+++ b/apps/mobile/src/__tests__/messageNormalize.test.ts@@ -941,13 +941,15 @@ describe('normalizeRemoteMessages', () => {expect(items[1].turnCompleted).toBeUndefined();});- it('renders silent-stop auto-resume rows as system cards instead of user bubbles', () => {+ it('renders auto-resume rows as system cards with interruption outcome metadata', () => {const items = normalizeRemoteMessages([message({id: 'auto-resume',role: 'user',content: '继续',- agentMeta: { delivery: 'turn', autoResume: true },+ agentMeta: { delivery: 'turn', autoResume: true, autoResumeInfo: {+ error: 'socket hang up', attempt: 2, maxAttempts: 5, sessionTotal: 3,+ }, autoResumeOutcome: 'failed' },}),]);@@ -957,6 +959,7 @@ describe('normalizeRemoteMessages', () => {label: 'user',body: '',systemCardType: 'auto-resume',+ systemCardData: { error: 'socket hang up', attempt: 2, maxAttempts: 5, sessionTotal: 3, outcome: 'failed' },align: 'agent',});});diff --git a/apps/mobile/src/__tests__/messageRenderModel.test.ts b/apps/mobile/src/__tests__/messageRenderModel.test.tsindex 0e237e2dfa..d3de2be976 100644--- a/apps/mobile/src/__tests__/messageRenderModel.test.ts+++ b/apps/mobile/src/__tests__/messageRenderModel.test.ts@@ -39,6 +39,19 @@ function toolUse(id: string, toolName: string, input: unknown, seconds: number):}describe('messageRenderModel', () => {+ it('appends live auto-resume state while folding an earlier retry from the same interruption', () => {+ const priorRetry = message({ id: 'retry-1', role: 'user', content: '', agentMeta: { autoResume: true } });+ const items = buildMobileMessageRenderItems([message({ id: 'a', role: 'assistant', content: 'partial', agentMeta: { isStreaming: true } }), priorRetry], {+ isSessionStreaming: true,+ autoResumePending: { error: 'socket hang up', attempt: 2, maxAttempts: 5, sessionTotal: 3 },+ });+ expect(expectType(items[0], 'message').message.isTurnFinalAssistant).toBe(true);+ expect(expectType(items[1], 'message').message).toMatchObject({+ systemCardType: 'auto-resume',+ systemCardData: { error: 'socket hang up', attempt: 2, maxAttempts: 5, sessionTotal: 3, live: true },+ createdAt: '2026-01-01T00:00:00.001Z',+ });+ });it('reuses unchanged history rows and attachment view models during a streaming tail update', () => {const user = message({id: 'user-1',diff --git a/apps/mobile/src/__tests__/systemCard.test.ts b/apps/mobile/src/__tests__/systemCard.test.tsindex 1846f82165..5c0bf12f76 100644--- a/apps/mobile/src/__tests__/systemCard.test.ts+++ b/apps/mobile/src/__tests__/systemCard.test.ts@@ -141,6 +141,22 @@ describe('formatMobileSystemCard — goal 续跑卡按原因分说法', () => {});});+describe('formatMobileSystemCard — 中断自动重连状态', () => {+ const info = { error: 'socket hang up', attempt: 2, maxAttempts: 5, sessionTotal: 3 };+ it('shows live progress, reason, current attempt, and conversation total', () => {+ expect(formatMobileSystemCard('auto-resume', { ...info, live: true })).toMatchObject({+ title: 'Reconnecting 2/5…',+ subtitle: 'Attempt 2/5 · 3 reconnects in this conversation',+ body: 'socket hang up',+ });+ });+ it('uses persisted outcome while keeping silent-stop records on their original copy', () => {+ expect(['succeeded', 'failed', undefined].map((outcome) =>+ formatMobileSystemCard('auto-resume', outcome ? { ...info, outcome } : {}).title,+ )).toEqual(['Reconnected', 'Reconnect failed', 'Connection interrupted — resumed automatically']);+ });+});+describe('commandNeedsRemoteSession', () => {// 新建会话的几秒窗口里 composer 全程可用(本 PR 的目的),于是用户可以在会话还没// 在被控端建成时发出 slash 命令。要远端的必须挡住(执行只会消费草稿再糊错误卡,diff --git a/apps/mobile/src/i18n/locales/en/message.json b/apps/mobile/src/i18n/locales/en/message.jsonindex 8b00da2ad3..d13ec8f5f6 100644--- a/apps/mobile/src/i18n/locales/en/message.json+++ b/apps/mobile/src/i18n/locales/en/message.json@@ -171,7 +171,15 @@"goalComplete": "Goal reached · {{turns}} turns · took {{duration}}","goalResumed": "Usage restored, continuing the goal","goalCapacityRetry": "Model service was busy — retrying the goal",- "autoResume": "Connection dropped, resumed automatically",+ "autoResume": {+ "separator": "Connection interrupted — resumed automatically",+ "succeeded": "Reconnected",+ "failed": "Reconnect failed",+ "neutral": "Reconnect",+ "pending": "Reconnecting…",+ "pendingWithProgress": "Reconnecting {{attempt}}/{{total}}…",+ "details": "Attempt {{attempt}}/{{total}} · {{count}} reconnects in this conversation"+ },"modelLabel": "Model","sessionLabel": "Session","sessionResumed": "Resumed",diff --git a/apps/mobile/src/i18n/locales/ja/message.json b/apps/mobile/src/i18n/locales/ja/message.jsonindex f920552f5e..1d9ffef8f9 100644--- a/apps/mobile/src/i18n/locales/ja/message.json+++ b/apps/mobile/src/i18n/locales/ja/message.json@@ -171,7 +171,15 @@"goalComplete": "目標を達成 · {{turns}} 回 · 所要 {{duration}}","goalResumed": "使用量が回復、目標を継続","goalCapacityRetry": "モデルサービスが混雑していました。目標を再試行します",- "autoResume": "接続が切断、自動的に継続しました",+ "autoResume": {+ "separator": "接続が中断されたため、自動的に再開しました",+ "succeeded": "再接続しました",+ "failed": "再接続できませんでした",+ "neutral": "再接続",+ "pending": "再接続中…",+ "pendingWithProgress": "再接続中 {{attempt}}/{{total}}…",+ "details": "今回の再試行 {{attempt}}/{{total}} · この会話での再接続 {{count}} 回"+ },"modelLabel": "モデル","sessionLabel": "セッション","sessionResumed": "再開済み",diff --git a/apps/mobile/src/i18n/locales/ko/message.json b/apps/mobile/src/i18n/locales/ko/message.jsonindex 9004717dde..7330bcc4a7 100644--- a/apps/mobile/src/i18n/locales/ko/message.json+++ b/apps/mobile/src/i18n/locales/ko/message.json@@ -171,7 +171,15 @@"goalComplete": "목표 달성 · {{turns}}회 · 소요 {{duration}}","goalResumed": "사용량이 회복되어 목표를 계속합니다","goalCapacityRetry": "모델 서비스가 혼잡했습니다. 목표를 다시 시도합니다",- "autoResume": "연결이 끊겨 자동으로 계속했습니다",+ "autoResume": {+ "separator": "연결이 중단되어 자동으로 재개되었습니다",+ "succeeded": "다시 연결되었습니다",+ "failed": "다시 연결하지 못했습니다",+ "neutral": "다시 연결",+ "pending": "다시 연결하는 중…",+ "pendingWithProgress": "다시 연결하는 중 {{attempt}}/{{total}}…",+ "details": "이번 재시도 {{attempt}}/{{total}} · 이 대화에서 재연결 {{count}}회"+ },"modelLabel": "모델","sessionLabel": "세션","sessionResumed": "재개됨",diff --git a/apps/mobile/src/i18n/locales/zh-CN/message.json b/apps/mobile/src/i18n/locales/zh-CN/message.jsonindex 88eb92f389..60620230f5 100644--- a/apps/mobile/src/i18n/locales/zh-CN/message.json+++ b/apps/mobile/src/i18n/locales/zh-CN/message.json@@ -171,7 +171,15 @@"goalComplete": "目标已达成 · {{turns}} 轮 · 耗时 {{duration}}","goalResumed": "用量已恢复,继续目标","goalCapacityRetry": "模型服务繁忙,正在重试目标",- "autoResume": "连接中断,已自动继续",+ "autoResume": {+ "separator": "连接中断,已自动继续",+ "succeeded": "已重新连接",+ "failed": "重新连接未成功",+ "neutral": "重新连接",+ "pending": "重新连接中…",+ "pendingWithProgress": "重新连接中 {{attempt}}/{{total}}…",+ "details": "本次重试 {{attempt}}/{{total}} · 本对话累计重连 {{count}} 次"+ },"modelLabel": "模型","sessionLabel": "对话","sessionResumed": "已续接",diff --git a/apps/mobile/src/session/inputProjection.ts b/apps/mobile/src/session/inputProjection.tsindex 927a776459..c5345723a2 100644--- a/apps/mobile/src/session/inputProjection.ts+++ b/apps/mobile/src/session/inputProjection.ts@@ -63,6 +63,7 @@ export function normalizeInputProjection(value: unknown, fallbackSessionId = '')error: readString(record?.error),recovery: record?.recovery,errorRetryText: readString(record?.errorRetryText),+ autoResumePending: readRecord(record?.autoResumePending),credentialSwitchWait: readCredentialSwitchWait(record?.credentialSwitchWait),};}diff --git a/apps/mobile/src/session/messageNormalize.ts b/apps/mobile/src/session/messageNormalize.tsindex 8b665e35bf..08fee44241 100644--- a/apps/mobile/src/session/messageNormalize.ts+++ b/apps/mobile/src/session/messageNormalize.ts@@ -309,6 +309,8 @@ export function normalizeRemoteMessages(messages: readonly RemoteMessage[]): Nor// user 以保留 turn 边界(上一段被截断 turn 的工具行按历史收敛),align 'agent'// 让卡片走系统卡的左侧版式而不是右侧用户气泡。if (message.role === 'user' && message.agentMeta?.autoResume === true) {+ const autoResumeInfo = readRecord(message.agentMeta.autoResumeInfo) ?? {};+ const autoResumeOutcome = message.agentMeta.autoResumeOutcome;result.push({key: messageNormalizeKey(message),source: message,@@ -317,7 +319,13 @@ export function normalizeRemoteMessages(messages: readonly RemoteMessage[]): Norlabel: 'user',body: '',systemCardType: 'auto-resume',- systemCardData: {},+ isSyntheticTrigger: true,+ systemCardData: {+ ...autoResumeInfo,+ ...(autoResumeOutcome === 'succeeded' || autoResumeOutcome === 'failed'+ ? { outcome: autoResumeOutcome }+ : {}),+ },align: 'agent',createdAt: message.createdAt,});diff --git a/apps/mobile/src/session/messageRenderModel.ts b/apps/mobile/src/session/messageRenderModel.tsindex 2f150c3eee..a72cbe6553 100644--- a/apps/mobile/src/session/messageRenderModel.ts+++ b/apps/mobile/src/session/messageRenderModel.ts@@ -24,6 +24,7 @@ import {hasSubagentMessages,} from '@/session/subagentGrouping';+const MAX_VALID_DATE_MS = 8.64e15;export type MobileTodoItem = MessageRenderTodoItem;export type MobileMessageItem = MessageRenderMessageItem<NormalizedRemoteMessage>;export type MobileThinkingItem = MessageRenderThinkingItem<NormalizedRemoteMessage>;@@ -76,12 +77,26 @@ export type MobileMessageRenderItem =export function buildMobileMessageRenderItems(messages: readonly RemoteMessage[],- options: MessageRenderOptions = {},+ options: MessageRenderOptions & { autoResumePending?: Record<string, unknown> | null; sessionId?: string } = {},taskUpdates?: ReadonlyMap<string, AgentTaskUpdate>,): MobileMessageRenderItem[] {const normalized = normalizeRemoteMessages(messages);scopeUnsettledToolsToActiveTail(normalized);markTurnFinalAssistants(normalized, options.isSessionStreaming === true);+ if (options.autoResumePending) {+ const pendingCreatedAtMs = messageCreatedMs(normalized.at(-1));+ normalized.push(...normalizeRemoteMessages([{+ id: 'mobile:auto-resume-pending',+ clientId: 'mobile:auto-resume-pending',+ sessionId: options.sessionId ?? messages[0]?.sessionId ?? '',+ role: 'user',+ content: '',+ toolUseId: null,+ agentMeta: { autoResume: true, autoResumeInfo: { ...options.autoResumePending, live: true } },+ createdAt: pendingCreatedAtMs === null || pendingCreatedAtMs >= MAX_VALID_DATE_MS ? '' : new Date(pendingCreatedAtMs + 1).toISOString(),+ }]));+ }+ collapseConsecutiveAutoResumeCards(normalized);// 无子 agent(Claude `Agent` 嵌套)→ 走原始线性路径,并接上 live agent_task 卡:// Task / collab:* 工具调用按 toolUseId→clientId 链接;无对应工具调用的孤儿更新兜底// 仅在会话运行中(isSessionStreaming)生效——空闲时孤儿是 stale 残留(工具调用已滑出@@ -107,10 +122,26 @@ export function buildMobileMessageRenderItems(*/function dropSyntheticTriggerItems(items: MobileMessageRenderItem[]): MobileMessageRenderItem[] {return items.filter(- (item) => !(item.type === 'message' && item.message.isSyntheticTrigger === true),+ (item) => !(item.type === 'message' && item.message.isSyntheticTrigger === true && !item.message.systemCardType),);}+/** 同一次中断只展示最新状态;旧行仍作为 turn boundary 留在 normalized 流中。 */+function collapseConsecutiveAutoResumeCards(messages: NormalizedRemoteMessage[]): void {+ let hasNewerCard = false;+ for (let index = messages.length - 1; index >= 0; index--) {+ const message = messages[index];+ if (message.systemCardType === 'auto-resume') {+ if (hasNewerCard) delete message.systemCardType;+ hasNewerCard = true;+ } else if (+ message.systemCardType+ || (message.isSyntheticTrigger !== true && message.kind !== 'thinking'+ && (message.kind === 'tool' || !!message.attachments?.length || /[^\s\p{Cf}\p{Cc}]/u.test(message.body)))+ ) hasNewerCard = false;+ }+}+export function extractTodosFromMessage(message: RemoteMessage): MobileTodoItem[] | null {return extractTodosFromSourceMessage(message);}diff --git a/apps/mobile/src/session/systemCard.ts b/apps/mobile/src/session/systemCard.tsindex 430108c310..2f642ba8b8 100644--- a/apps/mobile/src/session/systemCard.ts+++ b/apps/mobile/src/session/systemCard.ts@@ -124,12 +124,31 @@ export function formatMobileSystemCard(rows: [],};}- if (type === 'auto-resume') return { title: i18n.t('message.systemCard.autoResume'), rows: [] };+ if (type === 'auto-resume') return formatAutoResumeCard(data);if (type === 'agent-switch') return formatAgentSwitchCard(data);if (type === 'learn') return formatLearnCard(data);return formatSystemCard(type, data);}+function formatAutoResumeCard(data: Record<string, unknown> | undefined): SystemCardPresentation {+ const number = (value: unknown) => typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined;+ const error = typeof data?.error === 'string' && data.error.trim() ? data.error : undefined;+ const attempt = number(data?.attempt);+ const maxAttempts = number(data?.maxAttempts);+ const sessionTotal = number(data?.sessionTotal);+ const outcome = data?.outcome === 'succeeded' || data?.outcome === 'failed' ? data.outcome : undefined;+ const hasInterruptionContext = !!(data?.live === true || error || attempt || maxAttempts || sessionTotal || outcome);+ if (!hasInterruptionContext) return { title: i18n.t('message.systemCard.autoResume.separator'), rows: [] };+ const title = data?.live === true+ ? attempt && maxAttempts+ ? i18n.t('message.systemCard.autoResume.pendingWithProgress', { attempt, total: maxAttempts })+ : i18n.t('message.systemCard.autoResume.pending')+ : i18n.t(`message.systemCard.autoResume.${outcome ?? 'neutral'}`);+ const subtitle = attempt && maxAttempts && sessionTotal+ ? i18n.t('message.systemCard.autoResume.details', { attempt, total: maxAttempts, count: sessionTotal }) : undefined;+ return { title, ...(error ? { body: error } : {}), subtitle, rows: [] };+}+/*** session-agent-switch 边界卡的纯数据兜底(标题 + 目标模型行)。* 注意:实际渲染已改由 MessageRenderer 的 MobileAgentSwitchCard 直接读 datadiff --git a/apps/mobile/src/session/types.ts b/apps/mobile/src/session/types.tsindex c6a6db528d..fbc4011a1b 100644--- a/apps/mobile/src/session/types.ts+++ b/apps/mobile/src/session/types.ts@@ -213,6 +213,7 @@ export interface InputProjection {error: string | null;recovery?: unknown;errorRetryText: string | null;+ autoResumePending?: Record<string, unknown> | null;/*** 凭证切换等待态(对齐桌面 AgentInputProjection.credentialSwitchWait):发送需要* 重启共享 Codex 进程,但其它本地 Codex 任务在跑;消息保留在队首,挡路任务结束后