Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 保留自动重连真实运行态
Dash6bdd0ee97ee7
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex 721946e47d..bfc3e757d4 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -8098,6 +8098,11 @@ export default function SessionScreen() {focusedRequestKey={focusedMessageRequestKey}followLatestRequestKey={messageListFollowLatestRequestKey}isSessionStreaming={isSessionStreaming}+ makerTurnRunning={makerTurnRunning}+ continuationTurnClientId={inputProjection.continuationTurnClientId}+ continuationInFlightProjectionCapability={+ inputProjection.continuationInFlightProjectionCapability+ }items={messageListItems}pendingSend={pendingSendActions}loadingEarlier={loadingEarlier}diff --git a/apps/mobile/src/__tests__/autoResumePresentation.test.ts b/apps/mobile/src/__tests__/autoResumePresentation.test.tsnew file mode 100644index 0000000000..ca720594fe--- /dev/null+++ b/apps/mobile/src/__tests__/autoResumePresentation.test.ts@@ -0,0 +1,58 @@+import { describe, expect, it } from 'vitest';+import {+ canExpandMobileAutoResume,+ getMobileAutoResumePresentation,+ isMobileAutoResumeRowInFlight,+ readMobileAutoResumeInfo,+ summarizeMobileInterruption,+ toggleMobileAutoResumeExpanded,+} from '@/session/autoResumePresentation';++describe('autoResumePresentation', () => {+ const info = { error: 'API Error: socket hang up. Please retry.', attempt: 2, maxAttempts: 5, sessionTotal: 3 };++ it('keeps pending progress live while the continuation owner is in flight', () => {+ expect(getMobileAutoResumePresentation({ ...info, live: true }).state).toBe('live');+ const inFlight = isMobileAutoResumeRowInFlight({+ isContinuationTurnOwner: true,+ makerTurnRunning: true,+ isLastUserInput: false,+ projectionCapability: 'supported',+ });++ expect(getMobileAutoResumePresentation({ ...info }, inFlight).state).toBe('live');+ });++ it('uses the legacy fallback only for a legacy projection', () => {+ const args = {+ isContinuationTurnOwner: false,+ makerTurnRunning: true,+ isLastUserInput: true,+ };+ expect(isMobileAutoResumeRowInFlight({ ...args, projectionCapability: 'legacy' })).toBe(true);+ expect(isMobileAutoResumeRowInFlight({ ...args, projectionCapability: 'supported' })).toBe(false);+ expect(isMobileAutoResumeRowInFlight({ ...args, projectionCapability: 'unknown' })).toBe(false);+ });++ it('lets terminal outcomes win over a stale in-flight signal', () => {+ expect(getMobileAutoResumePresentation({ ...info, outcome: 'succeeded' }, true).state).toBe('succeeded');+ expect(getMobileAutoResumePresentation({ ...info, outcome: 'failed' }, true).state).toBe('failed');+ });++ it('shows a neutral recorded row when there is context but no live or terminal outcome', () => {+ expect(getMobileAutoResumePresentation({ sessionTotal: 3 }).state).toBe('neutral');+ expect(getMobileAutoResumePresentation({}).state).toBe('separator');+ });++ it('normalizes interruption context and keeps expansion bounded to useful detail', () => {+ expect(readMobileAutoResumeInfo({ attempt: 0, maxAttempts: '5', outcome: 'unknown' })).toEqual({});+ expect(summarizeMobileInterruption(' API Error: socket hang up. Please retry. More detail. '))+ .toBe('socket hang up.');+ expect(summarizeMobileInterruption(`API Error: ${'x'.repeat(80)}`)).toHaveLength(72);+ expect(canExpandMobileAutoResume(info)).toBe(true);+ expect(canExpandMobileAutoResume({})).toBe(false);+ expect(toggleMobileAutoResumeExpanded(false, true)).toBe(true);+ expect(toggleMobileAutoResumeExpanded(true, true)).toBe(false);+ expect(toggleMobileAutoResumeExpanded(true, false)).toBe(false);+ });+});diff --git a/apps/mobile/src/__tests__/inputProjection.test.ts b/apps/mobile/src/__tests__/inputProjection.test.tsindex a33a4e5169..19f861cba8 100644--- a/apps/mobile/src/__tests__/inputProjection.test.ts+++ b/apps/mobile/src/__tests__/inputProjection.test.ts@@ -370,6 +370,31 @@ describe('inputProjection', () => {});});+ it('distinguishes supported, legacy, and not-yet-received continuation ownership', () => {+ expect(normalizeInputProjection(undefined)).toMatchObject({+ continuationTurnClientId: null,+ continuationInFlightProjectionCapability: 'unknown',+ });+ expect(normalizeInputProjection({ sessionId: 'legacy' })).toMatchObject({+ continuationTurnClientId: null,+ continuationInFlightProjectionCapability: 'legacy',+ });+ expect(normalizeInputProjection({+ sessionId: 'supported-null',+ continuationTurnClientId: null,+ })).toMatchObject({+ continuationTurnClientId: null,+ continuationInFlightProjectionCapability: 'supported',+ });+ expect(normalizeInputProjection({+ sessionId: 'supported-owner',+ continuationTurnClientId: 'resume-1',+ })).toMatchObject({+ continuationTurnClientId: 'resume-1',+ continuationInFlightProjectionCapability: 'supported',+ });+ });+it('preserves and pauses queue only when Stop sees queued rows', () => {const queued = buildQueuedTextMessage(session(), 'later', new Date(), 'q-1');diff --git a/apps/mobile/src/__tests__/sessionMainLayerDesktopFirst.test.ts b/apps/mobile/src/__tests__/sessionMainLayerDesktopFirst.test.tsindex 1db9be8379..fac42a6ea5 100644--- a/apps/mobile/src/__tests__/sessionMainLayerDesktopFirst.test.ts+++ b/apps/mobile/src/__tests__/sessionMainLayerDesktopFirst.test.ts@@ -162,12 +162,14 @@ describe('mobile session main layer desktop-first noise budget', () => {expect(desktopSource).not.toContain('SYSTEM');expect(cardSource).toContain('<Text style={styles.systemCardTitle}>{card.title}</Text>');expect(cardSource).toContain('function MobileAutoResumeActionRow');- expect(cardSource).toContain('summarizeMobileInterruption');expect(cardSource).toContain('message.systemCard.autoResume.detail.reason');expect(cardSource).toContain('message.systemCard.autoResume.detail.attempt');expect(cardSource).toContain('message.systemCard.autoResume.detail.sessionTotal');expect(cardSource).toContain('CompactActivityIndicator');expect(cardSource).toContain('message.systemCard.autoResume.pendingWithProgress');+ expect(cardSource).toContain('importantForAccessibility="no-hide-descendants"');+ expect(cardSource).toContain('accessible={false}');+ expect(source).toMatch(/autoResumeHeader:\s*\{[\s\S]*?minHeight:\s*44,/);expect(cardSource).not.toContain('SYSTEM');expect(cardSource).not.toContain('systemCardEyebrow');expect(source).not.toContain('systemCardEyebrow: {');diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsxindex 3aa0af4313..dbd6318158 100644--- a/apps/mobile/src/session/MessageRenderer.tsx+++ b/apps/mobile/src/session/MessageRenderer.tsx@@ -274,6 +274,12 @@ import type {MobileMediaPlayerStatus,} from '@/session/mediaPlayerWebViewHtml';import { formatMobileSystemCard } from '@/session/systemCard';+import {+ getMobileAutoResumePresentation,+ isMobileAutoResumeRowInFlight,+ toggleMobileAutoResumeExpanded,+} from '@/session/autoResumePresentation';+import type { ContinuationInFlightProjectionCapability } from '@/session/types';import {projectMobileWorkActivities,projectRecentMobileWorkActivities,@@ -477,6 +483,14 @@ interface MessageActions {screenWidth?: number;/** 会话是否流式中:驱动工具行 running/done 状态(未 settled 且流式中才显示进行中)。 */isSessionStreaming?: boolean;+ /** 当前 maker vendor turn 是否仍在运行;旧端续跑归属兜底只允许使用这条窄信号。 */+ makerTurnRunning?: boolean;+ /** 当前 vendor turn 的自动续跑 owner。 */+ continuationTurnClientId?: string | null;+ /** 只有明确识别为 legacy 的投影才允许使用最后一条输入的兼容判据。 */+ continuationInFlightProjectionCapability?: ContinuationInFlightProjectionCapability;+ /** 含自动续跑合成行、排除 steer 的最后一条用户输入。 */+ lastUserInputClientId?: string | null;}export function MessageRenderer({@@ -505,6 +519,9 @@ export function MessageRenderer({emptyTestID,bottomOverlayHeight,isSessionStreaming,+ makerTurnRunning,+ continuationTurnClientId,+ continuationInFlightProjectionCapability,loadingEarlier,focusedRequestKey,queueFooter,@@ -547,6 +564,7 @@ export function MessageRenderer({const { t } = useTranslation();const styles = useThemedStyles(makeStyles);const firstUserMessageClientId = findFirstUserMessageClientId(items);+ const lastUserInputClientId = findLastUserInputClientId(items);const focusedItemKeyRef = useRef(focusedItemKey);focusedItemKeyRef.current = focusedItemKey;const listRef = useRef<LegendListRef>(null);@@ -800,13 +818,21 @@ export function MessageRenderer({busyClientId,busyAction,firstUserMessageClientId,+ lastUserInputClientId,+ makerTurnRunning,+ continuationTurnClientId,+ continuationInFlightProjectionCapability,isSessionStreaming,screenWidth: viewportLayout.contentWidth,}), [busyClientId,busyAction,+ continuationInFlightProjectionCapability,+ continuationTurnClientId,firstUserMessageClientId,isSessionStreaming,+ lastUserInputClientId,+ makerTurnRunning,onCopyMessageLink,onAddMessageToComposer,onDeleteMessage,@@ -1952,6 +1978,13 @@ function MessageBubble({) : null}{item.message.systemCardType ? (<MobileSystemCard+ autoResumeInFlight={isMobileAutoResumeRowInFlight({+ isContinuationTurnOwner: clientId === actions.continuationTurnClientId,+ makerTurnRunning: actions.makerTurnRunning === true,+ isLastUserInput: clientId === actions.lastUserInputClientId,+ projectionCapability:+ actions.continuationInFlightProjectionCapability ?? 'unknown',+ })}data={item.message.systemCardData}type={item.message.systemCardType}/>@@ -3229,9 +3262,11 @@ function MobileAgentSwitchCard({ data }: { data?: Record<string, unknown> }) {}function MobileSystemCard({+ autoResumeInFlight,data,type,}: {+ autoResumeInFlight?: boolean;data?: Record<string, unknown>;type: NonNullable<NormalizedRemoteMessage['systemCardType']>;}) {@@ -3240,7 +3275,9 @@ function MobileSystemCard({if (type === 'agent-switch') return <MobileAgentSwitchCard data={data} />;// auto-resume 复用桌面 AgentActionRow 的单行状态布局:默认只显示当前状态和压缩后的// 中断原因,完整诊断按需展开,避免底层错误全文把手机消息流撑成一张大卡片。- if (type === 'auto-resume') return <MobileAutoResumeActionRow data={data} />;+ if (type === 'auto-resume') {+ return <MobileAutoResumeActionRow data={data} inFlight={autoResumeInFlight === true} />;+ }const card = formatMobileSystemCard(type, data);return (<View style={styles.systemCard} testID={`message.systemCard.${type}`}>@@ -3261,61 +3298,21 @@ function MobileSystemCard({);}-interface MobileAutoResumeInfo {- error?: string;- attempt?: number;- maxAttempts?: number;- sessionTotal?: number;- outcome?: 'succeeded' | 'failed';-}--function readMobileAutoResumeInfo(data?: Record<string, unknown>): MobileAutoResumeInfo {- const number = (value: unknown) =>- typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined;- const attempt = number(data?.attempt);- const maxAttempts = number(data?.maxAttempts);- const sessionTotal = number(data?.sessionTotal);- return {- ...(typeof data?.error === 'string' && data.error.trim() ? { error: data.error } : {}),- ...(attempt !== undefined ? { attempt } : {}),- ...(maxAttempts !== undefined ? { maxAttempts } : {}),- ...(sessionTotal !== undefined ? { sessionTotal } : {}),- ...(data?.outcome === 'succeeded' || data?.outcome === 'failed'- ? { outcome: data.outcome }- : {}),- };-}--function summarizeMobileInterruption(detail?: string): string | undefined {- if (!detail) return undefined;- const compact = detail- .replace(/^\s*API Error:\s*/i, '')- .replace(/\s+/g, ' ')- .trim();- if (!compact) return undefined;- const firstSentence = compact.split(/(?<=[.。!?!?])\s/)[0] ?? compact;- return firstSentence.length > 72 ? `${firstSentence.slice(0, 71)}…` : firstSentence;-}-function MobileAutoResumeActionRow({data,+ inFlight,}: {data?: Record<string, unknown>;+ inFlight: boolean;}) {const styles = useThemedStyles(makeStyles);const { colors } = useTheme();const { t } = useTranslation();const [expanded, setExpanded] = useState(false);- const info = readMobileAutoResumeInfo(data);- const hasProgress = info.attempt !== undefined && info.maxAttempts !== undefined;- const hasInterruptionContext =- data?.live === true ||- info.error !== undefined ||- hasProgress ||- info.sessionTotal !== undefined ||- info.outcome !== undefined;-- if (!hasInterruptionContext) {+ const presentation = getMobileAutoResumePresentation(data, inFlight);+ const { canExpand, hasProgress, info, state, summary } = presentation;++ if (state === 'separator') {const label = t('message.systemCard.autoResume.separator');return (<View style={styles.autoResumeSeparator} testID="message.systemCard.auto-resume-separator">@@ -3329,21 +3326,18 @@ function MobileAutoResumeActionRow({);}- const live = data?.live === true;- const label = live+ const label = state === 'live'? hasProgress? t('message.systemCard.autoResume.pendingWithProgress', {attempt: info.attempt,total: info.maxAttempts,}): t('message.systemCard.autoResume.pending')- : info.outcome === 'succeeded'+ : state === 'succeeded'? t('message.systemCard.autoResume.succeeded')- : info.outcome === 'failed'+ : state === 'failed'? t('message.systemCard.autoResume.failed'): t('message.systemCard.autoResume.neutral');- const summary = summarizeMobileInterruption(info.error);- const canExpand = Boolean(info.error) || hasProgress || info.sessionTotal !== undefined;const accessibilityLabel = summary ? `${label}: ${summary}` : label;return (@@ -3353,15 +3347,22 @@ function MobileAutoResumeActionRow({accessibilityRole={canExpand ? 'button' : undefined}accessibilityState={canExpand ? { expanded } : undefined}disabled={!canExpand}- onPress={canExpand ? () => setExpanded((value) => !value) : undefined}+ onPress={canExpand+ ? () => setExpanded((value) => toggleMobileAutoResumeExpanded(value, canExpand))+ : undefined}style={({ pressed }) => [styles.autoResumeHeader, pressed && styles.pressed]}>- <View style={styles.autoResumeIconSlot} accessibilityElementsHidden>- {live ? (+ <View+ accessible={false}+ accessibilityElementsHidden+ importantForAccessibility="no-hide-descendants"+ style={styles.autoResumeIconSlot}+ >+ {state === 'live' ? (<CompactActivityIndicator color={colors.textTertiary} size={iconSize.sm} />- ) : info.outcome === 'succeeded' ? (+ ) : state === 'succeeded' ? (<Check color={colors.textTertiary} size={iconSize.sm} strokeWidth={iconStroke.regular} />- ) : info.outcome === 'failed' ? (+ ) : state === 'failed' ? (<X color={colors.textTertiary} size={iconSize.sm} strokeWidth={iconStroke.regular} />) : (<RefreshCw color={colors.textTertiary} size={iconSize.sm} strokeWidth={iconStroke.regular} />@@ -5955,6 +5956,30 @@ function findFirstUserMessageClientIdInItem(return undefined;}+function findLastUserInputClientId(items: readonly MobileMessageRenderItem[]): string | null {+ for (let index = items.length - 1; index >= 0; index--) {+ const found = findLastUserInputClientIdInItem(items[index]);+ if (found) return found;+ }+ return null;+}++function findLastUserInputClientIdInItem(+ item: MobileMessageRenderItem | MobileWorkChildItem,+): string | null {+ if (item.type === 'message' && item.message.role === 'user') {+ const delivery = item.message.source.agentMeta?.delivery;+ return delivery === 'steer' ? null : messageClientId(item);+ }+ if (item.type === 'work_group') {+ for (let index = item.children.length - 1; index >= 0; index--) {+ const found = findLastUserInputClientIdInItem(item.children[index]);+ if (found) return found;+ }+ }+ return null;+}+function messageClientId(item: MobileMessageItem): string {return item.message.source.clientId || item.message.source.id || item.message.key;}@@ -6263,7 +6288,7 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({alignItems: 'center',flexDirection: 'row',gap: spacing.xs,- minHeight: 40,+ minHeight: 44,paddingHorizontal: spacing.xs,},autoResumeIconSlot: {diff --git a/apps/mobile/src/session/autoResumePresentation.ts b/apps/mobile/src/session/autoResumePresentation.tsnew file mode 100644index 0000000000..1df7514b00--- /dev/null+++ b/apps/mobile/src/session/autoResumePresentation.ts@@ -0,0 +1,98 @@+import type { ContinuationInFlightProjectionCapability } from '@/session/types';++export interface MobileAutoResumeInfo {+ error?: string;+ attempt?: number;+ maxAttempts?: number;+ sessionTotal?: number;+ outcome?: 'succeeded' | 'failed';+}++export type MobileAutoResumeState = 'separator' | 'live' | 'succeeded' | 'failed' | 'neutral';++export interface MobileAutoResumePresentation {+ info: MobileAutoResumeInfo;+ state: MobileAutoResumeState;+ summary?: string;+ hasProgress: boolean;+ canExpand: boolean;+}++export function readMobileAutoResumeInfo(data?: Record<string, unknown>): MobileAutoResumeInfo {+ const number = (value: unknown) =>+ typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined;+ const attempt = number(data?.attempt);+ const maxAttempts = number(data?.maxAttempts);+ const sessionTotal = number(data?.sessionTotal);+ return {+ ...(typeof data?.error === 'string' && data.error.trim() ? { error: data.error } : {}),+ ...(attempt !== undefined ? { attempt } : {}),+ ...(maxAttempts !== undefined ? { maxAttempts } : {}),+ ...(sessionTotal !== undefined ? { sessionTotal } : {}),+ ...(data?.outcome === 'succeeded' || data?.outcome === 'failed'+ ? { outcome: data.outcome }+ : {}),+ };+}++export function summarizeMobileInterruption(detail?: string): string | undefined {+ if (!detail) return undefined;+ const compact = detail+ .replace(/^\s*API Error:\s*/i, '')+ .replace(/\s+/g, ' ')+ .trim();+ if (!compact) return undefined;+ const firstSentence = compact.split(/(?<=[.。!?!?])\s/)[0] ?? compact;+ return firstSentence.length > 72 ? `${firstSentence.slice(0, 71)}…` : firstSentence;+}++export function canExpandMobileAutoResume(info: MobileAutoResumeInfo): boolean {+ return Boolean(info.error) || (info.attempt !== undefined && info.maxAttempts !== undefined)+ || info.sessionTotal !== undefined;+}++export function getMobileAutoResumePresentation(+ data: Record<string, unknown> | undefined,+ inFlight = false,+): MobileAutoResumePresentation {+ const info = readMobileAutoResumeInfo(data);+ const hasProgress = info.attempt !== undefined && info.maxAttempts !== undefined;+ const hasInterruptionContext =+ data?.live === true ||+ info.error !== undefined ||+ hasProgress ||+ info.sessionTotal !== undefined ||+ info.outcome !== undefined;++ if (!hasInterruptionContext) {+ return { info, state: 'separator', hasProgress, canExpand: false };+ }++ // A recorded terminal outcome wins over any stale live/in-flight signal.+ const state: MobileAutoResumeState = info.outcome+ ?? ((data?.live === true || inFlight) ? 'live' : 'neutral');+ const summary = summarizeMobileInterruption(info.error);+ return {+ info,+ state,+ ...(summary ? { summary } : {}),+ hasProgress,+ canExpand: canExpandMobileAutoResume(info),+ };+}++export function toggleMobileAutoResumeExpanded(expanded: boolean, canExpand: boolean): boolean {+ return canExpand ? !expanded : false;+}++/** Mirror Desktop's continuation-owner rule, including its explicit legacy fallback. */+export function isMobileAutoResumeRowInFlight(args: {+ isContinuationTurnOwner: boolean;+ makerTurnRunning: boolean;+ isLastUserInput: boolean;+ projectionCapability: ContinuationInFlightProjectionCapability;+}): boolean {+ return args.isContinuationTurnOwner || (+ args.projectionCapability === 'legacy' && args.makerTurnRunning && args.isLastUserInput+ );+}diff --git a/apps/mobile/src/session/inputProjection.ts b/apps/mobile/src/session/inputProjection.tsindex 34e61e099e..f7c0802f98 100644--- a/apps/mobile/src/session/inputProjection.ts+++ b/apps/mobile/src/session/inputProjection.ts@@ -46,11 +46,18 @@ export const EMPTY_INPUT_PROJECTION: InputProjection = Object.freeze({recovery: null,errorRetryText: null,credentialSwitchWait: null,+ continuationTurnClientId: null,+ continuationInFlightProjectionCapability: 'unknown',});export function normalizeInputProjection(value: unknown, fallbackSessionId = ''): InputProjection {const record = readRecord(value);const pendingQueue = readQueuedMessages(record?.pendingQueue);+ const continuationInFlightProjectionCapability = record === null+ ? 'unknown'+ : Object.prototype.hasOwnProperty.call(record, 'continuationTurnClientId')+ ? 'supported'+ : 'legacy';return {sessionId: readString(record?.sessionId) ?? fallbackSessionId,pendingQueue,@@ -64,6 +71,8 @@ export function normalizeInputProjection(value: unknown, fallbackSessionId = '')recovery: record?.recovery,errorRetryText: readString(record?.errorRetryText),autoResumePending: readRecord(record?.autoResumePending),+ continuationTurnClientId: readString(record?.continuationTurnClientId),+ continuationInFlightProjectionCapability,credentialSwitchWait: readCredentialSwitchWait(record?.credentialSwitchWait),};}diff --git a/apps/mobile/src/session/types.ts b/apps/mobile/src/session/types.tsindex 2c48fe96fb..4f6ab2dcf5 100644--- a/apps/mobile/src/session/types.ts+++ b/apps/mobile/src/session/types.ts@@ -203,6 +203,13 @@ export interface QueuedRemoteMessage {origin?: Record<string, unknown>;}+/**+ * Whether the host projection can identify the owner of an in-flight continuation turn.+ * `legacy` is reserved for projections that omit the field entirely; an explicit `null`+ * is a supported projection with no continuation owner.+ */+export type ContinuationInFlightProjectionCapability = 'unknown' | 'legacy' | 'supported';+export interface InputProjection {sessionId: string;pendingQueue: QueuedRemoteMessage[];@@ -216,6 +223,10 @@ export interface InputProjection {recovery?: unknown;errorRetryText: string | null;autoResumePending?: Record<string, unknown> | null;+ /** Current vendor-turn owner for an auto-resume continuation, when supported by the host. */+ continuationTurnClientId?: string | null;+ /** Capability marker kept distinct from an explicit `continuationTurnClientId: null`. */+ continuationInFlightProjectionCapability?: ContinuationInFlightProjectionCapability;/*** 凭证切换等待态(对齐桌面 AgentInputProjection.credentialSwitchWait):发送需要* 重启共享 Codex 进程,但其它本地 Codex 任务在跑;消息保留在队首,挡路任务结束后