Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 统一自动重连活动行 (#1793)
Dash4a0f3bde3748
diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreAutoResumeCard.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreAutoResumeCard.test.tsindex e5f3f9c57d..d97f45557e 100644--- a/apps/desktop/src/renderer/__tests__/makerChatStoreAutoResumeCard.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreAutoResumeCard.test.ts@@ -56,9 +56,10 @@ vi.mock('@/lib/composerDraftStore', () => ({}),}));-import { makerChatStore } from '@/lib/makerChatStore';+import { EMPTY_SESSION_STATE, handleStreamEvent, makerChatStore } from '@/lib/makerChatStore';import * as messageService from '@/lib/messageService';import type { Message } from '@/lib/ccAgent.types';+import type { ChatMessage } from '@/lib/makerChatStore';import { CONTINUE_AFTER_ERROR_PROMPT } from '../../shared/interruptedTurn.js';const inputStop = vi.fn(async () => projection({ queuePaused: false }));@@ -67,13 +68,25 @@ const inputGetProjection = vi.fn<() => Promise<unknown>>(async () =>);let inputProjectionCb: ((projection: unknown) => void) | null = null;+let makerEventCb: ((payload: unknown) => void) | null = null;+let makerStatusCb: ((payload: unknown) => void) | null = null;function makeElectronApiStub() {const fanOut = () => () => () => {};return {maker: {- onEvent: fanOut(),- onStatusChanged: fanOut(),+ onEvent: (cb: (payload: unknown) => void) => {+ makerEventCb = cb;+ return () => {+ makerEventCb = null;+ };+ },+ onStatusChanged: (cb: (payload: unknown) => void) => {+ makerStatusCb = cb;+ return () => {+ makerStatusCb = null;+ };+ },onInputProjection: (cb: (projection: unknown) => void) => {inputProjectionCb = cb;return () => {@@ -245,6 +258,8 @@ describe('applyInputProjection 自愈进行中提示', () => {makerChatStore.__teardownGlobalListeners();delete (globalThis as { window?: unknown }).window;inputProjectionCb = null;+ makerEventCb = null;+ makerStatusCb = null;vi.useRealTimers();vi.clearAllMocks();});@@ -320,6 +335,101 @@ describe('applyInputProjection 自愈进行中提示', () => {).toBe(false);});+ it('无关 projection 不误删原生重连行,接管 projection 到达时才交棒', () => {+ makerEventCb?.({+ sessionId: SID,+ event: {+ type: 'error',+ source: 'codex',+ data: { message: 'Reconnecting... 1/5', isTerminal: false, willRetry: true },+ },+ });+ expect(+ makerChatStore+ .getSnapshot(SID)+ .messages.some((m) => m.clientId === '__codex_reconnect_pending__'),+ ).toBe(true);++ inputProjectionCb!(projection());+ expect(+ makerChatStore+ .getSnapshot(SID)+ .messages.some((m) => m.clientId === '__codex_reconnect_pending__'),+ '普通队列 projection 不应打断仍在进行的原生重连',+ ).toBe(true);++ inputProjectionCb!(projection({ autoResumePending: PENDING_INFO }));+ const rows = makerChatStore.getSnapshot(SID).messages;+ expect(rows.some((m) => m.clientId === '__codex_reconnect_pending__')).toBe(false);+ expect(rows.some((m) => m.clientId === PENDING_CARD_ID)).toBe(true);+ });++ it('credentialSwitchWait projection 会收掉原生重连行', () => {+ makerEventCb?.({+ sessionId: SID,+ event: {+ type: 'error',+ source: 'codex',+ data: { message: 'Reconnecting... 1/5', isTerminal: false, willRetry: true },+ },+ });+ expect(+ makerChatStore+ .getSnapshot(SID)+ .messages.some((m) => m.clientId === '__codex_reconnect_pending__'),+ ).toBe(true);++ inputProjectionCb!(+ projection({ credentialSwitchWait: { clientId: 'queued-1', blockedBySessionIds: [SID] } }),+ );++ const snapshot = makerChatStore.getSnapshot(SID);+ expect(snapshot.credentialSwitchWait).toEqual({+ clientId: 'queued-1',+ blockedBySessionIds: [SID],+ });+ expect(+ snapshot.messages.some((m) => m.clientId === '__codex_reconnect_pending__'),+ ).toBe(false);+ });++ it('Stop 会同步撤掉原生重连活动行', () => {+ makerEventCb?.({+ sessionId: SID,+ event: {+ type: 'error',+ source: 'codex',+ data: { message: 'Reconnecting... 1/5', isTerminal: false, willRetry: true },+ },+ });+ expect(+ makerChatStore+ .getSnapshot(SID)+ .messages.some((m) => m.clientId === '__codex_reconnect_pending__'),+ ).toBe(true);++ makerChatStore.stopSession(SID);++ expect(+ makerChatStore+ .getSnapshot(SID)+ .messages.some((m) => m.clientId === '__codex_reconnect_pending__'),+ ).toBe(false);+ });++ it('status=closed 即使缺少 done 也会撤掉 Cindy 接管活动行', () => {+ inputProjectionCb!(projection({ autoResumePending: PENDING_INFO }));+ expect(+ makerChatStore.getSnapshot(SID).messages.some((m) => m.clientId === PENDING_CARD_ID),+ ).toBe(true);++ makerStatusCb?.({ sessionId: SID, status: 'closed' });++ expect(+ makerChatStore.getSnapshot(SID).messages.some((m) => m.clientId === PENDING_CARD_ID),+ ).toBe(false);+ });+it('救不回来时错误回落成横幅,提示卡同时撤掉', () => {inputProjectionCb!(projection({ autoResumePending: PENDING_INFO }));inputProjectionCb!(@@ -332,6 +442,273 @@ describe('applyInputProjection 自愈进行中提示', () => {});});+describe('Codex 原生重连进行态与终态接管交棒', () => {+ const reconnectEvent = (message: string, isTerminal: boolean) => ({+ sessionId: SID,+ type: 'error' as const,+ source: 'codex' as const,+ data: {+ message,+ isTerminal,+ willRetry: !isTerminal,+ },+ });+ const stateWithCindyPending = (error = PENDING_INFO.error) => {+ const pendingCard = {+ ...serverMessage({+ clientId: PENDING_CARD_ID,+ content: '',+ }),+ systemCardType: 'auto-resume-pending' as const,+ systemCardData: { ...PENDING_INFO, error },+ } as ChatMessage;+ return {+ ...EMPTY_SESSION_STATE,+ messages: [pendingCard],+ };+ };++ it('Reconnecting N/M 原地更新到灰色活动行,正常事件到达后撤掉', () => {+ const first = handleStreamEvent(+ EMPTY_SESSION_STATE,+ reconnectEvent('Reconnecting... 1/5', false),+ );+ const firstCard = first.messages.find((m) => m.clientId === '__codex_reconnect_pending__');+ expect(firstCard?.systemCardType).toBe('auto-resume-pending');+ expect(firstCard?.systemCardData).toEqual({ attempt: 1, maxAttempts: 5 });+ expect(first.recoverableError).toBeNull();++ const second = handleStreamEvent(first, reconnectEvent('Reconnecting... 2/5', false));+ const cards = second.messages.filter((m) => m.clientId === '__codex_reconnect_pending__');+ expect(cards).toHaveLength(1);+ expect(cards[0]?.systemCardData).toMatchObject({ attempt: 2, maxAttempts: 5 });+ expect(cards[0]?.createdAt).toBe(firstCard?.createdAt);++ const recovered = handleStreamEvent(second, {+ sessionId: SID,+ type: 'text',+ data: { text: '继续工作', isFinal: false },+ });+ expect(recovered.messages.some((m) => m.clientId === '__codex_reconnect_pending__')).toBe(+ false,+ );+ });++ it('重连期间无关任务更新和工具结果不会提前清除原生活动行', () => {+ const reconnecting = handleStreamEvent(+ EMPTY_SESSION_STATE,+ reconnectEvent('Reconnecting... 1/5', false),+ );+ const withTaskUpdate = handleStreamEvent(reconnecting, {+ sessionId: SID,+ type: 'agent_task_update',+ source: 'codex',+ data: { provider: 'codex', taskId: 'task-1', status: 'running' },+ });+ const withToolResult = handleStreamEvent(withTaskUpdate, {+ sessionId: SID,+ type: 'tool_result',+ source: 'codex',+ data: { toolUseIds: ['tool-1'] },+ });++ expect(withToolResult.messages.some((m) => m.clientId === '__codex_reconnect_pending__')).toBe(+ true,+ );+ });++ it('协作子代理的 collab tool_use 不会提前清除原生活动行', () => {+ const reconnecting = handleStreamEvent(+ EMPTY_SESSION_STATE,+ reconnectEvent('Reconnecting... 1/5', false),+ );+ const withCollabTool = handleStreamEvent(reconnecting, {+ sessionId: SID,+ type: 'tool_use',+ source: 'codex',+ data: { toolUseId: 'tool-1', toolName: 'collab:spawn', input: { task: '审查' } },+ });++ expect(+ withCollabTool.messages.some((m) => m.clientId === '__codex_reconnect_pending__'),+ ).toBe(true);+ });++ it('普通根 turn tool_use 仍会清除原生活动行', () => {+ const reconnecting = handleStreamEvent(+ EMPTY_SESSION_STATE,+ reconnectEvent('Reconnecting... 1/5', false),+ );+ const withRootTool = handleStreamEvent(reconnecting, {+ sessionId: SID,+ type: 'tool_use',+ source: 'codex',+ data: { toolUseId: 'tool-1', toolName: 'shell', input: { command: 'pwd' } },+ });++ expect(+ withRootTool.messages.some((m) => m.clientId === '__codex_reconnect_pending__'),+ ).toBe(false);+ });++ it('带 turnContinuationId 的 done 不会清除原生活动行', () => {+ const reconnecting = handleStreamEvent(+ EMPTY_SESSION_STATE,+ reconnectEvent('Reconnecting... 1/5', false),+ );+ const withContinuationDone = handleStreamEvent(reconnecting, {+ sessionId: SID,+ type: 'done',+ data: { reason: 'foreground-done' },+ turnContinuationId: 1,+ });++ expect(+ withContinuationDone.messages.some((m) => m.clientId === '__codex_reconnect_pending__'),+ ).toBe(true);+ expect(withContinuationDone.isStreaming).toBe(true);+ expect(withContinuationDone.agentStatus.isRunning).toBe(true);+ });++ it.each([+ ['认证', 'Reconnecting... 1/5 (401 Missing bearer)', { errorStatus: 401 }, /missing bearer/i],+ [+ '额度',+ 'Reconnecting... 1/5 (rate limit)',+ { usageLimit: true, errorStatus: 429 },+ /rate limit/i,+ ],+ ])('无关任务更新不会吞掉%s类可操作错误', (_label, message, extra, expected) => {+ const event = reconnectEvent(message, false);+ const actionable = handleStreamEvent(EMPTY_SESSION_STATE, {+ ...event,+ data: { ...event.data, ...extra },+ });+ const afterTaskUpdate = handleStreamEvent(actionable, {+ sessionId: SID,+ type: 'agent_task_update',+ source: 'codex',+ data: { provider: 'codex', taskId: 'task-1', status: 'running' },+ });++ expect(afterTaskUpdate.recoverableError).toMatch(expected);+ });++ it('已有 Cindy 接管活动行时,迟到的非终态重连继续保持接管态', () => {+ const next = handleStreamEvent(+ stateWithCindyPending(),+ reconnectEvent('Reconnecting... 4/5', false),+ );+ expect(next.error).toBeNull();+ expect(next.recoverableError).toBeNull();+ expect(next.messages.some((m) => m.clientId === PENDING_CARD_ID)).toBe(true);+ expect(next.messages.some((m) => m.clientId === '__codex_reconnect_pending__')).toBe(false);+ expect(next.isStreaming).toBe(false);+ expect(next.agentStatus.isRunning).toBe(false);+ });++ it('认证和额度类非终态重连保留可操作错误,不伪装成灰色活动行', () => {+ const authEvent = reconnectEvent('Reconnecting... 1/5 (401 Missing bearer)', false);+ const authNext = handleStreamEvent(EMPTY_SESSION_STATE, {+ ...authEvent,+ data: { ...authEvent.data, errorStatus: 401 },+ });+ expect(authNext.messages.some((m) => m.clientId === '__codex_reconnect_pending__')).toBe(false);+ expect(authNext.recoverableError).toContain('Missing bearer');++ const usageEvent = reconnectEvent('Reconnecting... 1/5 (rate limit)', false);+ const usageNext = handleStreamEvent(EMPTY_SESSION_STATE, {+ ...usageEvent,+ data: { ...usageEvent.data, usageLimit: true, errorStatus: 429 },+ });+ expect(usageNext.messages.some((m) => m.clientId === '__codex_reconnect_pending__')).toBe(+ false,+ );+ expect(usageNext.recoverableError).toContain('rate limit');++ const stringStatusNext = handleStreamEvent(EMPTY_SESSION_STATE, {+ ...reconnectEvent('Reconnecting... 1/5', false),+ data: {+ ...reconnectEvent('Reconnecting... 1/5', false).data,+ status: '401',+ },+ });+ expect(+ stringStatusNext.messages.some((m) => m.clientId === '__codex_reconnect_pending__'),+ ).toBe(false);+ expect(stringStatusNext.recoverableError).toContain('Reconnecting');+ });++ it('已有 Cindy 接管活动行时,随后到达的终态 maker:event 不再点亮红 banner', () => {+ const message =+ 'Codex backend unreachable — the daemon retried 4 times over 133s without success (last error: "Reconnecting... 3/5").';+ const next = handleStreamEvent(stateWithCindyPending(message), reconnectEvent(message, true));+ expect(next.error).toBeNull();+ expect(next.recoverableError).toBeNull();+ expect(next.messages.some((m) => m.clientId === PENDING_CARD_ID)).toBe(true);+ });++ it.each([+ [+ 'codex reconnect stall',+ 'Codex app-server has been reconnecting for 120s without making progress.',+ 'codex_reconnect_stalled',+ ],+ ['network timeout', 'Request timed out', undefined],+ ['service unavailable', '503 Service Unavailable', undefined],+ ['upstream overload', 'Selected model is at capacity', 'upstream-overload'],+ ])('已有 Cindy 接管活动行时,%s 的终态广播保持灰色接管态', (_label, message, reason) => {+ const event = reconnectEvent(message, true);+ const next = handleStreamEvent(stateWithCindyPending(message), {+ ...event,+ data: { ...event.data, ...(reason ? { reason } : {}) },+ });+ expect(next.error).toBeNull();+ expect(next.messages.some((m) => m.clientId === PENDING_CARD_ID)).toBe(true);+ });++ it('残留接管卡不会吞掉正文不匹配的新网络终态错误', () => {+ const next = handleStreamEvent(+ stateWithCindyPending('Request timed out'),+ reconnectEvent('503 Service Unavailable', true),+ );+ expect(next.error).toContain('503 Service Unavailable');+ expect(next.messages.some((m) => m.clientId === PENDING_CARD_ID)).toBe(false);+ });++ it('残留接管卡不能吞掉新的认证终态错误', () => {+ const next = handleStreamEvent(stateWithCindyPending(), {+ ...reconnectEvent('Codex authentication failed: Missing bearer token.', true),+ data: {+ ...reconnectEvent('Codex authentication failed: Missing bearer token.', true).data,+ errorStatus: 401,+ },+ });+ expect(next.error).toMatch(/missing bearer/i);+ expect(next.messages.some((m) => m.clientId === PENDING_CARD_ID)).toBe(false);+ });++ it('终态错误之后的迟到非终态重连不会重新创建活动行或点亮 running', () => {+ const terminal = handleStreamEvent(+ EMPTY_SESSION_STATE,+ reconnectEvent('Codex backend unreachable — retry budget exhausted.', true),+ );+ const late = handleStreamEvent(terminal, reconnectEvent('Reconnecting... 5/5', false));+ expect(late.error).toContain('Codex backend unreachable');+ expect(late.messages.some((m) => m.clientId === '__codex_reconnect_pending__')).toBe(false);+ expect(late.isStreaming).toBe(false);+ expect(late.agentStatus.isRunning).toBe(false);+ });++ it('没有 Cindy 接管活动行时,同一终态仍回落红 banner', () => {+ const next = handleStreamEvent(+ EMPTY_SESSION_STATE,+ reconnectEvent('Codex backend unreachable — retry budget exhausted.', true),+ );+ expect(next.error).toContain('Codex backend unreachable');+ });+});+// Main now owns the vendor-turn continuation identity; Renderer mirrors it without a sticky seen marker.describe('续跑边界投影能力与 vendor turn owner', () => {beforeEach(() => {@@ -438,7 +815,12 @@ describe('同一次中断事件的多次重连折叠成一行', () => {vi.clearAllMocks();});- const resumeRow = (clientId: string, attempt: number, outcome?: 'succeeded' | 'failed', at = '2026-06-12T00:00:0') =>+ const resumeRow = (+ clientId: string,+ attempt: number,+ outcome?: 'succeeded' | 'failed',+ at = '2026-06-12T00:00:0',+ ) =>serverMessage({clientId,role: 'user',@@ -524,7 +906,10 @@ describe('同一次中断事件的多次重连折叠成一行', () => {const cards = makerChatStore.getSnapshot(SID).messages.filter((m) => m.systemCardType === 'auto-resume');- expect(cards.map((m) => m.clientId), '同一次中断只该留最新那一行').toEqual(['r2']);+ expect(+ cards.map((m) => m.clientId),+ '同一次中断只该留最新那一行',+ ).toEqual(['r2']);});it('进行中的 ephemeral 行会盖掉它前面那条已落库的重连行', async () => {diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex 22fe5ef0a4..f72a5f08e7 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -148,6 +148,7 @@ import {extractUsageLimitRecoveryHint,type UsageLimitRecoveryHint,} from '@/lib/usageLimitRecovery';+import { parseReconnectAttemptMessage } from '@/utils/networkError';import {materializeAnnotatedAttachmentsForSend,@@ -277,9 +278,9 @@ export function decodeRemoteErrorMessage(msg: string): string {const bracketMatch = BRACKET_ERROR_CODE_RE.exec(msg);const bracketCode = bracketMatch?.[1];if (- bracketCode- && (DEVICE_LINK_CHAT_ERROR_CODES.has(bracketCode)- || AGENT_RUNTIME_CHAT_ERROR_CODES.has(bracketCode))+ bracketCode &&+ (DEVICE_LINK_CHAT_ERROR_CODES.has(bracketCode) ||+ AGENT_RUNTIME_CHAT_ERROR_CODES.has(bracketCode))) {return i18n.t(`chat.remoteError.${bracketCode}`, {defaultValue: bracketMatch[2] || msg,@@ -1033,10 +1034,10 @@ function isRemoteClearFenceCurrent(sessionId: string, fence?: RemoteClearFence):const current = fence ?? remoteClearFences.get(sessionId);return Boolean(current &&- remoteClearFences.get(sessionId) === current &&- isDataOwnerGenerationCurrent(current.dataOwner) &&- getStickySessionDeviceId(sessionId) === current.deviceId &&- (rendererClearGenerationBySession.get(sessionId) ?? 0) === current.clearGeneration,+ remoteClearFences.get(sessionId) === current &&+ isDataOwnerGenerationCurrent(current.dataOwner) &&+ getStickySessionDeviceId(sessionId) === current.deviceId &&+ (rendererClearGenerationBySession.get(sessionId) ?? 0) === current.clearGeneration,);}@@ -1185,11 +1186,11 @@ function resolveRemoteClearFenceFromProjection(}type RemoteClearOperationResult<T> =- | { kind: 'value'; value: T }- | { kind: 'error'; error: unknown }- | { kind: 'timeout' };+ { kind: 'value'; value: T } | { kind: 'error'; error: unknown } | { kind: 'timeout' };-async function awaitRemoteClearOperation<T>(promise: Promise<T>): Promise<RemoteClearOperationResult<T>> {+async function awaitRemoteClearOperation<T>(+ promise: Promise<T>,+): Promise<RemoteClearOperationResult<T>> {let timeoutId: ReturnType<typeof setTimeout> | undefined;try {return await Promise.race([@@ -2828,11 +2829,11 @@ function observeRemoteInputClearBoundary();const acknowledgesPendingFence = Boolean(pendingFenceIsCurrent &&- typeof normalized === 'number' &&- (opts.acknowledgePendingFence === true ||- pendingFence!.clearBoundaryBeforeRequest === null ||- (typeof pendingFence!.clearBoundaryBeforeRequest === 'number' &&- normalized > pendingFence!.clearBoundaryBeforeRequest)),+ typeof normalized === 'number' &&+ (opts.acknowledgePendingFence === true ||+ pendingFence!.clearBoundaryBeforeRequest === null ||+ (typeof pendingFence!.clearBoundaryBeforeRequest === 'number' &&+ normalized > pendingFence!.clearBoundaryBeforeRequest)),);let advanced = false;if (!hadPrevious) {@@ -3357,6 +3358,119 @@ function shallowEqualRecord(}const AUTO_RESUME_PENDING_CLIENT_ID = '__auto_resume_pending__';+/** Codex app-server 自带的 Reconnecting N/M 进行态行。与 Cindy 接管行分开,避免+ * 无关的 input projection 把仍在进行中的原生重连误删。 */+const CODEX_RECONNECT_PENDING_CLIENT_ID = '__codex_reconnect_pending__';++function removeCodexReconnectPendingCard(messages: ChatMessage[]): ChatMessage[] {+ if (!messages.some((message) => message.clientId === CODEX_RECONNECT_PENDING_CLIENT_ID)) {+ return messages;+ }+ return messages.filter((message) => message.clientId !== CODEX_RECONNECT_PENDING_CLIENT_ID);+}++function removeResumePendingCards(messages: ChatMessage[]): ChatMessage[] {+ if (+ !messages.some(+ (message) =>+ message.clientId === CODEX_RECONNECT_PENDING_CLIENT_ID ||+ message.clientId === AUTO_RESUME_PENDING_CLIENT_ID,+ )+ ) {+ return messages;+ }+ return messages.filter(+ (message) =>+ message.clientId !== CODEX_RECONNECT_PENDING_CLIENT_ID &&+ message.clientId !== AUTO_RESUME_PENDING_CLIENT_ID,+ );+}++function upsertCodexReconnectPendingCard(+ messages: ChatMessage[],+ data: Record<string, unknown>,+): ChatMessage[] {+ const existingIndex = messages.findIndex(+ (message) => message.clientId === CODEX_RECONNECT_PENDING_CLIENT_ID,+ );+ const card: ChatMessage = {+ clientId: CODEX_RECONNECT_PENDING_CLIENT_ID,+ role: 'assistant',+ content: '',+ isStreaming: false,+ systemCardType: 'auto-resume-pending',+ systemCardData: data,+ createdAt: new Date().toISOString(),+ };+ if (existingIndex >= 0) {+ const existing = messages[existingIndex];+ if (existing && shallowEqualRecord(existing.systemCardData, data)) return messages;+ return messages.map((message, index) =>+ index === existingIndex+ ? { ...existing, ...card, createdAt: existing.createdAt ?? card.createdAt }+ : message,+ );+ }+ return collapseConsecutiveAutoResumeRows([...messages, card]);+}++function isCodexUserActionableRetryError(data: unknown): boolean {+ const root = data && typeof data === 'object' ? (data as Record<string, unknown>) : {};+ const message = typeof root.message === 'string' ? root.message : '';+ const sdkError = typeof root.sdkError === 'string' ? root.sdkError : '';+ const rawStatus = root.errorStatus ?? root.status;+ const status =+ typeof rawStatus === 'number'+ ? rawStatus+ : typeof rawStatus === 'string' && rawStatus.trim() !== ''+ ? Number(rawStatus)+ : null;+ const authError =+ sdkError === 'authentication_failed' ||+ sdkError === 'authentication_error' ||+ status === 401 ||+ /\b401\b|Missing bearer|authentication_(?:error|failed)|invalid[\s_-]*api[\s_-]*key|api key not valid/i.test(+ message,+ );+ return authError || extractUsageLimitRecoveryHint(data) !== null;+}++/**+ * Codex 原生重连行只应在真正的 turn 进展或明确收尾时让位。+ *+ * `maker:event` 里还混着后台任务更新、tool_result、thinking 等旁路事件;它们+ * 可能属于同一会话但不代表重连已经恢复。Codex 子代理的 descendant 状态通知不会走这条+ * 主事件流,而是专用的 `agent_task_update`;但协作控制调用本身仍可能以 `tool_use` 进入流。+ * `collab:*` 是这类控制调用的稳定命名空间,不代表根 turn 已经恢复,因此不能让它提前+ * 清掉原生行。其它 `tool_use` 仍作为根 turn 的实质进展边界,并与 main 的+ * `isSubstantiveProgressEvent` 对齐。文本仍共用可见文本判据,避免空白 delta 误报恢复。+ */+function isCodexReconnectRecoveryOutput(event: CCAgentStreamEvent): boolean {+ if (event.type === 'text') {+ const text = (event.data as { text?: unknown } | null | undefined)?.text;+ return hasUserVisibleText(text);+ }+ if (event.type === 'tool_use') {+ const toolName = (event.data as { toolName?: unknown } | null | undefined)?.toolName;+ return typeof toolName !== 'string' || !toolName.startsWith('collab:');+ }+ return event.type === 'done' && !isTurnContinuationBoundaryEvent(event);+}++/** Main 的接管 projection 与随后 maker:event 来自两个 channel。只有活动行里保存的+ * 原始错误与终态 event 完全一致,才把 event 视为同一次接管的广播回声;不能仅凭存在+ * 一张 pending 卡就吞掉后来其它 turn 的错误。 */+function hasMatchingAutoResumePendingError(messages: ChatMessage[], data: unknown): boolean {+ const root = data && typeof data === 'object' ? (data as Record<string, unknown>) : {};+ const message = typeof root.message === 'string' ? root.message : '';+ if (!message) return false;+ return messages.some(+ (item) =>+ item.clientId === AUTO_RESUME_PENDING_CLIENT_ID &&+ typeof item.systemCardData?.error === 'string' &&+ item.systemCardData.error === message,+ );+}function applyInputProjection(projection: AgentInputProjection,@@ -3492,11 +3606,20 @@ function applyInputProjection(if (messages.some((message) => message.clientId === item.clientId)) return messages;return [...messages, { ...item.chatMessage, isPendingPersist: true }];}, dedupedMessages);+ // Codex 原生重连已经被 host 接管、进入凭证切换等待或明确回落时,原生进行态行+ // 必须让位给 Cindy 的接管行、凭证切换状态或终态错误。没有这些字段的普通+ // projection 不触碰它,以免无关队列投影把正在更新的 N/M 进度提前擦掉。+ const projectionSettledCodexReconnect = Boolean(+ projection.autoResumePending || projection.error || projection.credentialSwitchWait,+ );+ const messagesBeforeAutoResume = projectionSettledCodexReconnect+ ? removeCodexReconnectPendingCard(withSettlingMessages)+ : withSettlingMessages;// 中断自愈接管中 → 在流末尾挂一条 ephemeral 的「正在自动继续」分隔条(不落库);// 接管结束(补发已发出 / 放弃 / 用户自己接手)由同一处撤掉。红横幅只留给最终失败,// 所以这几秒里 projection.error 是 null,用户看到的就只有这条低调提示。const autoResumePending = !!projection.autoResumePending;- const hasPendingCard = withSettlingMessages.some(+ const hasPendingCard = messagesBeforeAutoResume.some((m) => m.clientId === AUTO_RESUME_PENDING_CLIENT_ID,);const pendingCardData = projection.autoResumePending@@ -3507,7 +3630,7 @@ function applyInputProjection(? // 卡已在:必须把最新展示信息写回去 —— 同一次中断的进度会连续更新// (1/5 → 2/5 …),原样保留旧卡的话进度永远停在第一次(copilot review)。// 只在内容真的变了时才换引用,避免每次 projection 都触发无谓重渲染。- withSettlingMessages.map((m) =>+ messagesBeforeAutoResume.map((m) =>m.clientId === AUTO_RESUME_PENDING_CLIENT_ID &&pendingCardData &&!shallowEqualRecord(m.systemCardData, pendingCardData)@@ -3515,7 +3638,7 @@ function applyInputProjection(: m,): [- ...withSettlingMessages,+ ...messagesBeforeAutoResume,{clientId: AUTO_RESUME_PENDING_CLIENT_ID,role: 'assistant' as const,@@ -3527,8 +3650,8 @@ function applyInputProjection(},]: hasPendingCard- ? withSettlingMessages.filter((m) => m.clientId !== AUTO_RESUME_PENDING_CLIENT_ID)- : withSettlingMessages;+ ? messagesBeforeAutoResume.filter((m) => m.clientId !== AUTO_RESUME_PENDING_CLIENT_ID)+ : messagesBeforeAutoResume;// 折叠:同一次中断事件里,ephemeral 进行中行与它前面那些已落库的重连行只显示最新// 一条(否则第 2 次重连时会看到「未成功」+「重新连接中 2/5」两行并存)。const messages = collapseConsecutiveAutoResumeRows(withPendingCard);@@ -4164,10 +4287,34 @@ export function handleStreamEvent(inputState: SessionChatState,event: CCAgentStreamEvent,): SessionChatState {- const state =- event.type === 'error' || inputState.recoverableError == null+ const reconnectAttempt =+ event.type === 'error'+ ? parseReconnectAttemptMessage(+ typeof (event.data as { message?: unknown } | null | undefined)?.message === 'string'+ ? (event.data as { message: string }).message+ : '',+ )+ : null;+ const isCodexReconnectProgress =+ event.type === 'error' &&+ event.source === 'codex' &&+ !isTerminalErrorData(event.data) &&+ reconnectAttempt !== null &&+ !isCodexUserActionableRetryError(event.data);+ const hasCodexReconnectRecoveryOutput = isCodexReconnectRecoveryOutput(event);+ const shouldClearCodexReconnectPendingCard =+ event.type === 'error' ? !isCodexReconnectProgress : hasCodexReconnectRecoveryOutput;+ const stateBeforeReconnectCleanup =+ !hasCodexReconnectRecoveryOutput || inputState.recoverableError == null? inputState: { ...inputState, recoverableError: null };+ const messagesAfterReconnectCleanup = shouldClearCodexReconnectPendingCard+ ? removeCodexReconnectPendingCard(stateBeforeReconnectCleanup.messages)+ : stateBeforeReconnectCleanup.messages;+ const state =+ messagesAfterReconnectCleanup === stateBeforeReconnectCleanup.messages+ ? stateBeforeReconnectCleanup+ : { ...stateBeforeReconnectCleanup, messages: messagesAfterReconnectCleanup };// agent-meta: 任何带 agentMeta 的事件都刷新 lastAgentMeta——mid-turn 抢救// assistant 累积流时拿这份当 fallback。直接 mutate state 不行,下面各 case// 在 return 时把它合并进去;如果 case 没主动处理 lastAgentMeta,由下面统一兜底。@@ -4706,6 +4853,48 @@ export function handleStreamEvent(: decodeRemoteErrorMessage(safeErrMsg);const isTerminalError = isTerminalErrorData(event.data);if (!isTerminalError) {+ // Codex app-server 的有限重连进度是进行态,不是用户需要处理的错误。+ // 复用 Cindy 自动接管活动行的视觉通道,固定 clientId 原地更新 N/M;+ // host 接管成功后 projection 会先撤掉这条原生行并交棒给自己的 pending 行。+ if (isCodexReconnectProgress) {+ const hasAutoResumePendingCard = state.messages.some(+ (message) => message.clientId === AUTO_RESUME_PENDING_CLIENT_ID,+ );+ // 终态错误之后跨 channel 到达的迟到 Reconnecting 不能复活运行态。+ // 正常首个重连事件没有 error/retry token,仍按进行中的 turn 点亮 spinner;+ // 已有 Cindy 接管卡时则保留当前 running 快照,交给 projection 的权威状态。+ const terminalized = state.error !== null || state.errorRetryText !== null;+ if (terminalized && !hasAutoResumePendingCard) {+ return {+ ...state,+ messages: removeCodexReconnectPendingCard(state.messages),+ };+ }+ return {+ ...state,+ messages: hasAutoResumePendingCard+ ? state.messages+ : upsertCodexReconnectPendingCard(state.messages, {+ attempt: reconnectAttempt.attempt,+ maxAttempts: reconnectAttempt.maxAttempts,+ }),+ error: null,+ usageLimitRecovery: null,+ errorReason: null,+ recoverableError: null,+ errorRetryText: null,+ isStreaming: hasAutoResumePendingCard ? state.isStreaming : true,+ agentStatus: {+ ...(hasAutoResumePendingCard+ ? state.agentStatus+ : {+ ...state.agentStatus,+ isRunning: true,+ startedAt: state.agentStatus.startedAt ?? Date.now(),+ }),+ },+ };+ }return {...state,error: null,@@ -4727,6 +4916,10 @@ export function handleStreamEvent(}const finalized = finalizeStreamingInState(state);const derivedRetryText = deriveErrorRetryText(finalized);+ const suppressAutoResumeBroadcastError =+ event.source === 'codex' &&+ !isCodexUserActionableRetryError(event.data) &&+ hasMatchingAutoResumePendingError(finalized.messages, event.data);// main coordinator 在终止型 error 时**先**同步 emit projection(errorRetryText// = projectionRetryText 的权威 retry token,active-turn 恢复恒非空)再 broadcast// 本事件,所以此刻 finalized.errorRetryText 可能已经持有 main 的 token。本地推导@@ -4745,11 +4938,21 @@ export function handleStreamEvent(reason === 'remote_daemon_closed' && isSessionUpgrading(event.sessionId);return {...finalized,- error: isPlannedUpgradeClose ? null : errMsg,- usageLimitRecovery: isPlannedUpgradeClose- ? null- : extractUsageLimitRecoveryHint(event.data),- errorReason: isPlannedUpgradeClose ? null : (reason ?? null),+ messages: suppressAutoResumeBroadcastError+ ? finalized.messages+ : finalized.messages.filter(+ (message) => message.clientId !== AUTO_RESUME_PENDING_CLIENT_ID,+ ),+ // coordinator 已经先发 autoResumePending projection 时,终态 maker:event+ // 只是同一次失败的广播回声,不能把接管态重新点成红色横幅。若接管失败,+ // projection 会先撤掉 pending 行并带 error 到达,此处仍正常落红。+ error: isPlannedUpgradeClose || suppressAutoResumeBroadcastError ? null : errMsg,+ usageLimitRecovery:+ isPlannedUpgradeClose || suppressAutoResumeBroadcastError+ ? null+ : extractUsageLimitRecoveryHint(event.data),+ errorReason:+ isPlannedUpgradeClose || suppressAutoResumeBroadcastError ? null : (reason ?? null),recoverableError: null,errorRetryText: derivedRetryText ?? preservedRetryText,isStreaming: false,@@ -5146,6 +5349,11 @@ function forceFinalizeOnSessionClosed(state: SessionChatState): SessionChatStatestate.steeringQueueClientIds.length === 0 &&state.continuationTurnClientId === null &&!state.pendingTaskWake &&+ !state.messages.some(+ (message) =>+ message.clientId === CODEX_RECONNECT_PENDING_CLIENT_ID ||+ message.clientId === AUTO_RESUME_PENDING_CLIENT_ID,+ ) &&stoppedTasks === state.taskUpdates) {return state;@@ -5156,8 +5364,8 @@ function forceFinalizeOnSessionClosed(state: SessionChatState): SessionChatState// as NO_ACTIVE_TURN, the missing marker tells the catch path not to fallback// into a fresh normal turn.const steeringIds = new Set(finalized.steeringQueueClientIds);- const cleared = finalized.messages- .map((m) => {+ const cleared = removeResumePendingCards(+ finalized.messages.map((m) => {let next = m;if (m.isStreaming) next = { ...next, isStreaming: false };if (m.role === 'ask_user' && m.askUserStatus === 'pending') {@@ -5167,8 +5375,8 @@ function forceFinalizeOnSessionClosed(state: SessionChatState): SessionChatStatenext = { ...next, planReviewStatus: 'expired' as const };}return next;- })- .filter((m) => !steeringIds.has(m.clientId));+ }),+ ).filter((m) => !steeringIds.has(m.clientId));return {...finalized,messages: cleared,@@ -5360,11 +5568,7 @@ function isCurrentLiveIngress(context?: LiveIngressContext): boolean {return !hasStamp || isDataOwnerPushStampCurrent(context.ownerStamp);}- return isRemoteDataOwnerPushCurrent(- context.remoteDeviceId,- context.ownerStamp,- hasStamp,- );+ return isRemoteDataOwnerPushCurrent(context.remoteDeviceId, context.ownerStamp, hasStamp);}function isCurrentLocalLiveIngress(ownerStamp: unknown): boolean {@@ -5380,8 +5584,7 @@ function sameLiveIngressScope(a: LiveIngressContext, b: LiveIngressContext): booconst bStamp = isDataOwnerPushStamp(b.ownerStamp) ? b.ownerStamp : null;if (aStamp === null || bStamp === null) return aStamp === bStamp;return (- aStamp.dataOwnerId === bStamp.dataOwnerId &&- aStamp.ownerGeneration === bStamp.ownerGeneration+ aStamp.dataOwnerId === bStamp.dataOwnerId && aStamp.ownerGeneration === bStamp.ownerGeneration);}@@ -5412,11 +5615,9 @@ function bindIpc(ipcUnsubscribers.push(() => {});return;}- const result = (- subscribe as (- cb: (data: unknown, ownerStamp?: unknown) => void,- ) => unknown- )(handler);+ const result = (subscribe as (cb: (data: unknown, ownerStamp?: unknown) => void) => unknown)(+ handler,+ );if (typeof result === 'function') {ipcUnsubscribers.push(result as () => void);} else {@@ -5482,10 +5683,7 @@ function flushPendingTextDelta(sessionId: string, deferNotification = false): vopendingTextDeltaBatches.delete(sessionId);if (pendingTextDeltaBatches.size === 0) clearTextDeltaFlushTimer();- if (- !isDataOwnerGenerationCurrent(pending.dataOwner) ||- !isCurrentLiveIngress(pending.ingress)- ) {+ if (!isDataOwnerGenerationCurrent(pending.dataOwner) || !isCurrentLiveIngress(pending.ingress)) {return;}@@ -6110,10 +6308,7 @@ function initGlobalListeners(): void {);// ── Maker interaction request: permission/ask/plan 三合一,按 kind 分发 ──- const handleInteractionRequestRaw = (- raw: unknown,- ingress: LiveIngressContext = {},- ) => {+ const handleInteractionRequestRaw = (raw: unknown, ingress: LiveIngressContext = {}) => {if (!isCurrentLiveIngress(ingress)) return;const payload = raw as {sessionId?: string;@@ -6280,10 +6475,7 @@ function initGlobalListeners(): void {}};- const handleLiveInteractionRequestRaw = (- raw: unknown,- ingress: LiveIngressContext = {},- ) => {+ const handleLiveInteractionRequestRaw = (raw: unknown, ingress: LiveIngressContext = {}) => {if (!isCurrentLiveIngress(ingress)) return;const sessionId = (raw as { sessionId?: unknown } | null)?.sessionId;if (typeof sessionId === 'string' && sessionId.length > 0) {@@ -6305,10 +6497,7 @@ function initGlobalListeners(): void {applyInteractionRequestRef = handleInteractionRequestRaw;// ── Maker interaction dismissed: setPermissionMode 切换 / close 时关掉对话框 ──- const handleInteractionDismissedRaw = (- raw: unknown,- ingress: LiveIngressContext = {},- ) => {+ const handleInteractionDismissedRaw = (raw: unknown, ingress: LiveIngressContext = {}) => {if (!isCurrentLiveIngress(ingress)) return;const payload = raw as { sessionId?: string; requestId?: string; reason?: string } | null;if (!payload?.sessionId || !payload.requestId) return;@@ -6336,10 +6525,7 @@ function initGlobalListeners(): void {handleStreamEvent(s, { sessionId, type: 'permission_dismissed', data }),);};- const handleLiveInteractionDismissedRaw = (- raw: unknown,- ingress: LiveIngressContext = {},- ) => {+ const handleLiveInteractionDismissedRaw = (raw: unknown, ingress: LiveIngressContext = {}) => {if (!isCurrentLiveIngress(ingress)) return;const sessionId = (raw as { sessionId?: unknown } | null)?.sessionId;if (typeof sessionId === 'string' && sessionId.length > 0) {@@ -6359,10 +6545,7 @@ function initGlobalListeners(): void {// Main 端写库的消息推送(接管路径 persistUserMessage / persistAssistantMessage),也复用给// device-link 远程会话(被控端 messages:created 经 onRemotePush 转发,注入同一套 in-memory state)。- function handleMessageCreatedRaw(- raw: unknown,- ingress: LiveIngressContext = {},- ): void {+ function handleMessageCreatedRaw(raw: unknown, ingress: LiveIngressContext = {}): void {if (!isCurrentLiveIngress(ingress)) return;const payload = raw as { sessionId?: string; message?: Message } | null;if (!payload?.sessionId || !payload.message) return;@@ -6429,10 +6612,7 @@ function initGlobalListeners(): void {// 消息本地删除推送:本机多窗口与 device-link 控制端共用同一 reducer。// 新 payload 一次带齐整轮 clientIds;旧 host 仍回退到单个 clientId。- function handleMessageDeletedRaw(- raw: unknown,- ingress: LiveIngressContext = {},- ): void {+ function handleMessageDeletedRaw(raw: unknown, ingress: LiveIngressContext = {}): void {if (!isCurrentLiveIngress(ingress)) return;const payload = raw as {sessionId?: string;@@ -6450,10 +6630,7 @@ function initGlobalListeners(): void {removeMessagesByClientIds(payload.sessionId, clientIds);}- function handleUsageMessageTurnCostRaw(- raw: unknown,- ingress: LiveIngressContext = {},- ): void {+ function handleUsageMessageTurnCostRaw(raw: unknown, ingress: LiveIngressContext = {}): void {if (!isCurrentLiveIngress(ingress)) return;const p = raw as {sessionId?: string;@@ -8712,7 +8889,14 @@ function ensureInitialMessages(sessionId: string): void {// device-link 远程 session 经隧道读被控端 row(本地 DB 没有,直接 get 会 404)。getSessionFor(sessionId).then((session) => {- if (!isCurrentHistoryFetch(sessionId, historyFetchToken, historyOriginAtStart, historyEpochAtStart)) {+ if (+ !isCurrentHistoryFetch(+ sessionId,+ historyFetchToken,+ historyOriginAtStart,+ historyEpochAtStart,+ )+ ) {// The history list owns the shared in-flight guard and will settle the// invalidated generation. Do not release it while that request is still// pending, otherwise a caller could start a second initial fetch beside it.@@ -8768,7 +8952,14 @@ function ensureInitialMessages(sessionId: string): void {});}).catch((err) => {- if (!isCurrentHistoryFetch(sessionId, historyFetchToken, historyOriginAtStart, historyEpochAtStart)) {+ if (+ !isCurrentHistoryFetch(+ sessionId,+ historyFetchToken,+ historyOriginAtStart,+ historyEpochAtStart,+ )+ ) {// See the resolve branch above: let listMessagesFor settle the shared// initial-fetch guard and decide whether the current generation retries.return;@@ -8783,7 +8974,14 @@ function ensureInitialMessages(sessionId: string): void {listMessagesFor(sessionId).then(async (existing) => {- if (!isCurrentHistoryFetch(sessionId, historyFetchToken, historyOriginAtStart, historyEpochAtStart)) {+ if (+ !isCurrentHistoryFetch(+ sessionId,+ historyFetchToken,+ historyOriginAtStart,+ historyEpochAtStart,+ )+ ) {retryInvalidatedInitialHistoryFetchIfNeeded(sessionId,historyFetchToken,@@ -8793,7 +8991,14 @@ function ensureInitialMessages(sessionId: string): void {return;}if (existing.length === 0) {- if (!isCurrentHistoryFetch(sessionId, historyFetchToken, historyOriginAtStart, historyEpochAtStart)) {+ if (+ !isCurrentHistoryFetch(+ sessionId,+ historyFetchToken,+ historyOriginAtStart,+ historyEpochAtStart,+ )+ ) {retryInvalidatedInitialHistoryFetchIfNeeded(sessionId,historyFetchToken,@@ -8841,7 +9046,14 @@ function ensureInitialMessages(sessionId: string): void {let merged: Message[] = existing;let oldestRow = oldestMessageRow(merged, 'newest-first');if (!oldestRow) {- if (!isCurrentHistoryFetch(sessionId, historyFetchToken, historyOriginAtStart, historyEpochAtStart)) {+ if (+ !isCurrentHistoryFetch(+ sessionId,+ historyFetchToken,+ historyOriginAtStart,+ historyEpochAtStart,+ )+ ) {retryInvalidatedInitialHistoryFetchIfNeeded(sessionId,historyFetchToken,@@ -8936,7 +9148,14 @@ function ensureInitialMessages(sessionId: string): void {limit: 50,before: oldestRow.id,});- if (!isCurrentHistoryFetch(sessionId, historyFetchToken, historyOriginAtStart, historyEpochAtStart)) {+ if (+ !isCurrentHistoryFetch(+ sessionId,+ historyFetchToken,+ historyOriginAtStart,+ historyEpochAtStart,+ )+ ) {retryInvalidatedInitialHistoryFetchIfNeeded(sessionId,historyFetchToken,@@ -8961,7 +9180,14 @@ function ensureInitialMessages(sessionId: string): void {// perf/session-switch 探针纯诊断:整段测量走 import.meta.env.DEV,生产// 构建里 Vite 把常量折成 false 后 dead-code 消除,零开销。const ingestStartMs = import.meta.env.DEV ? performance.now() : 0;- if (!isCurrentHistoryFetch(sessionId, historyFetchToken, historyOriginAtStart, historyEpochAtStart)) {+ if (+ !isCurrentHistoryFetch(+ sessionId,+ historyFetchToken,+ historyOriginAtStart,+ historyEpochAtStart,+ )+ ) {retryInvalidatedInitialHistoryFetchIfNeeded(sessionId,historyFetchToken,@@ -9028,7 +9254,14 @@ function ensureInitialMessages(sessionId: string): void {void reconcilePendingInteractions(sessionId, isCurrentHistoryLoad).catch(() => undefined);}).catch(() => {- if (!isCurrentHistoryFetch(sessionId, historyFetchToken, historyOriginAtStart, historyEpochAtStart)) {+ if (+ !isCurrentHistoryFetch(+ sessionId,+ historyFetchToken,+ historyOriginAtStart,+ historyEpochAtStart,+ )+ ) {retryInvalidatedInitialHistoryFetchIfNeeded(sessionId,historyFetchToken,@@ -11624,16 +11857,18 @@ function stopSession(setState(sessionId, (s) => {const id = s.streamingClientId;// F7.6 / FP-3: expire any pending ask_user + plan_review messages on stop- const msgs = s.messages.map((m) => {- if (id && m.clientId === id) return { ...m, isStreaming: false };- if (m.role === 'ask_user' && m.askUserStatus === 'pending') {- return { ...m, askUserStatus: 'expired' as const };- }- if (m.role === 'plan_review' && m.planReviewStatus === 'pending') {- return { ...m, planReviewStatus: 'expired' as const };- }- return m;- });+ const msgs = removeResumePendingCards(+ s.messages.map((m) => {+ if (id && m.clientId === id) return { ...m, isStreaming: false };+ if (m.role === 'ask_user' && m.askUserStatus === 'pending') {+ return { ...m, askUserStatus: 'expired' as const };+ }+ if (m.role === 'plan_review' && m.planReviewStatus === 'pending') {+ return { ...m, planReviewStatus: 'expired' as const };+ }+ return m;+ }),+ );return {...s,@@ -11960,8 +12195,7 @@ async function clearSessionAfterGuardImpl(sessionId: string, clearedAt: string):return {...s,messages: s.messages.filter(- (message) =>- message.isPendingPersist && postClearOptimisticClientIds.has(message.clientId),+ (message) => message.isPendingPersist && postClearOptimisticClientIds.has(message.clientId),),taskUpdates: new Map(),pendingTaskWake: false,