Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(codex): 在界面显示流式重连进度 (#790)

Dashac2e853fcfcd
diff --git a/apps/desktop/src/main/agent-island/__tests__/service.test.ts b/apps/desktop/src/main/agent-island/__tests__/service.test.ts
index 6a59b170c1..cef40c085c 100644
--- a/apps/desktop/src/main/agent-island/__tests__/service.test.ts
+++ b/apps/desktop/src/main/agent-island/__tests__/service.test.ts
@@ -204,6 +204,14 @@ function terminalErrorEvent(message: string, reason?: string): AgentEvent {
};
}
+function recoverableErrorEvent(message: string): AgentEvent {
+ return {
+ type: 'error',
+ source: 'codex',
+ data: { message, isTerminal: false, willRetry: true },
+ };
+}
+
function authenticationErrorEvent(message = 'authentication failed'): AgentEvent {
return {
type: 'error',
@@ -943,6 +951,57 @@ describe('AgentIslandService native publishing', () => {
expect(publish.mock.calls.at(-1)?.[0].pillSnapshot.pendingInteractionCount).toBe(0);
});
+ it('keeps permission routing through recoverable errors and clears it on terminal errors', async () => {
+ const { AgentIslandService } = await import('../service.js');
+ const publish = vi.fn(() => true);
+ const resolver = vi.fn(() => true);
+ const service = new AgentIslandService({
+ getMainWindow: () => null,
+ nativeHost: { failed: false, publish },
+ });
+
+ syncEnabledForTest(service, publish);
+ service.setPermissionResolver(resolver);
+ handleInteractionRequestForTest(service,
+ { sessionId: 's1', agentKind: 'codex' },
+ {
+ kind: 'permission',
+ requestId: 'req-reconnecting',
+ toolName: 'Bash',
+ input: { command: 'pnpm test' },
+ },
+ );
+
+ service.handleAgentEvent(
+ { sessionId: 's1', agentKind: 'codex' },
+ recoverableErrorEvent('Reconnecting... 1/5'),
+ );
+ service.handlePermissionAction({ requestId: 'req-reconnecting', action: 'allow' });
+
+ expect(resolver).toHaveBeenCalledWith('req-reconnecting', {
+ kind: 'permission',
+ behavior: 'allow',
+ permissionUpdates: undefined,
+ });
+
+ handleInteractionRequestForTest(service,
+ { sessionId: 's1', agentKind: 'codex' },
+ {
+ kind: 'permission',
+ requestId: 'req-terminal',
+ toolName: 'Bash',
+ input: { command: 'pnpm test' },
+ },
+ );
+ service.handleAgentEvent(
+ { sessionId: 's1', agentKind: 'codex' },
+ terminalErrorEvent('retry exhausted'),
+ );
+ service.handlePermissionAction({ requestId: 'req-terminal', action: 'allow' });
+
+ expect(resolver).toHaveBeenCalledTimes(1);
+ });
+
it('clears an island permission prompt by request id after app-side approval', async () => {
const { AgentIslandService } = await import('../service.js');
const publish = vi.fn((state: AgentIslandDisplayState, frameOrFrames: AgentIslandNativeFrame | AgentIslandNativeFrame[]) => {
diff --git a/apps/desktop/src/main/agent-island/__tests__/state.test.ts b/apps/desktop/src/main/agent-island/__tests__/state.test.ts
index 4da2372c9f..94314fe1ab 100644
--- a/apps/desktop/src/main/agent-island/__tests__/state.test.ts
+++ b/apps/desktop/src/main/agent-island/__tests__/state.test.ts
@@ -289,6 +289,83 @@ describe('Agent Island display state', () => {
]);
});
+ it('preserves one assistant stream across a recoverable reconnect error', () => {
+ const state = createAgentIslandState();
+ const start = 1_000;
+ setAgentIslandStrings(state, {
+ ...DEFAULT_AGENT_ISLAND_STRINGS,
+ networkReconnecting: '({{attempt}}/{{maxAttempts}})正在重连…',
+ });
+
+ applyAgentIslandUserPrompt(state, { sessionId: 's1', title: 'Task', agentKind: 'codex' }, 'run tests', start);
+ applyAgentIslandEvent(state, { sessionId: 's1' }, textDeltaEvent('我会先'), start + 100);
+ applyAgentIslandEvent(state, { sessionId: 's1' }, {
+ type: 'error',
+ source: 'codex',
+ data: {
+ message: 'Reconnecting... 1/5',
+ isTerminal: false,
+ willRetry: true,
+ },
+ }, start + 200);
+ expect(state.sessions.get('s1')).toMatchObject({
+ assistantStreamRawText: '我会先',
+ reconnectStatus: '(1/5)正在重连…',
+ });
+ expect(buildAgentIslandDisplayState(state, start + 200).sessions[0]).toMatchObject({
+ detail: '(1/5)正在重连…',
+ compactDetail: '(1/5)正在重连…',
+ });
+
+ applyAgentIslandEvent(state, { sessionId: 's1' }, {
+ type: 'error',
+ source: 'codex',
+ data: {
+ message: 'Reconnecting... 2/5',
+ isTerminal: false,
+ willRetry: true,
+ },
+ }, start + 250);
+ expect(buildAgentIslandDisplayState(state, start + 250).sessions[0]).toMatchObject({
+ detail: '(2/5)正在重连…',
+ compactDetail: '(2/5)正在重连…',
+ });
+
+ applyAgentIslandEvent(state, { sessionId: 's1' }, {
+ type: 'error',
+ source: 'codex',
+ data: {
+ message: 'Waiting before another automatic retry',
+ isTerminal: false,
+ willRetry: true,
+ },
+ }, start + 275);
+ expect(state.sessions.get('s1')?.reconnectStatus).toBeNull();
+ expect(buildAgentIslandDisplayState(state, start + 275).sessions[0]?.compactDetail)
+ .not.toContain('2/5');
+
+ applyAgentIslandEvent(state, { sessionId: 's1' }, textDeltaEvent('继续处理'), start + 300);
+ expect(state.sessions.get('s1')?.reconnectStatus).toBeNull();
+ applyAgentIslandEvent(
+ state,
+ { sessionId: 's1' },
+ finalTextEvent('我会先继续处理并完成。'),
+ start + 400,
+ );
+
+ const session = state.sessions.get('s1');
+ expect(session).toMatchObject({
+ running: true,
+ phase: 'running',
+ assistantStreamLineId: null,
+ assistantStreamRawText: '',
+ });
+ expect(session?.activityLines.map((line) => `${line.kind}:${line.text}`)).toEqual([
+ 'user:run tests',
+ 'assistant:我会先继续处理并完成。',
+ ]);
+ });
+
it('keeps whitespace-only assistant deltas in the raw stream accumulator', () => {
const state = createAgentIslandState();
const start = 1_000;
diff --git a/apps/desktop/src/main/agent-island/service.ts b/apps/desktop/src/main/agent-island/service.ts
index 783080d0b6..fce3dd95f5 100644
--- a/apps/desktop/src/main/agent-island/service.ts
+++ b/apps/desktop/src/main/agent-island/service.ts
@@ -2,7 +2,12 @@ import { dialog, ipcMain, screen, BrowserWindow, type Display, type OpenDialogOp
import path from 'node:path';
import { release as getOsRelease } from 'node:os';
import { SESSION_ACTIVITY_CHANNEL } from '@cindy/device-link';
-import type { AgentEvent, InteractionDecision, InteractionRequest } from '@cindy/maker-core';
+import {
+ isTerminalAgentErrorEvent,
+ type AgentEvent,
+ type InteractionDecision,
+ type InteractionRequest,
+} from '@cindy/maker-core';
import type { SchedulerEvent } from '@cindy/maker-scheduler';
import { BRAND_NAME } from '@cindy/maker-shared/branding';
import type { ApplicationMenuCommand } from '../../shared/applicationMenuCommands.js';
@@ -950,7 +955,7 @@ export class AgentIslandService {
}
private prunePermissionRequestsForAgentEvent(sessionId: string, event: AgentEvent): void {
- if (event.type === 'done' || event.type === 'error') {
+ if (event.type === 'done' || isTerminalAgentErrorEvent(event)) {
this.deletePermissionRequestsForSession(sessionId);
return;
}
@@ -2012,6 +2017,7 @@ function buildAgentIslandStrings(): AgentIslandStrings {
input: t('agentIsland.native.input'),
done: t('agentIsland.native.done'),
running: t('agentIsland.native.running'),
+ networkReconnecting: t('agentIsland.native.networkReconnecting'),
updatingTasks: t('agentIsland.native.updatingTasks'),
awaitingPermission: t('agentIsland.native.awaitingPermission'),
awaitingQuestion: t('agentIsland.native.awaitingQuestion'),
diff --git a/apps/desktop/src/main/agent-island/state.ts b/apps/desktop/src/main/agent-island/state.ts
index e0e7421f90..1c63c91150 100644
--- a/apps/desktop/src/main/agent-island/state.ts
+++ b/apps/desktop/src/main/agent-island/state.ts
@@ -1,4 +1,8 @@
-import type { AgentEvent, InteractionRequest } from '@cindy/maker-core';
+import {
+ parseReconnectAttemptMessage,
+ type AgentEvent,
+ type InteractionRequest,
+} from '@cindy/maker-core';
import { DEFAULT_TOOL_ROW_WORDING, type ToolRowWording } from '@cindy/maker-shared/message-presentation';
import { stripTrailingPathSeparators } from '../../shared/pathText';
@@ -100,6 +104,8 @@ interface AgentIslandSessionState {
projectName: string | null;
detail: string;
detailSource: 'tool' | 'status' | 'interaction' | null;
+ /** Localized transient reconnect progress; kept separate from tool/interaction detail. */
+ reconnectStatus: string | null;
currentToolUseId: string | null;
toolDetailUntil: number | null;
phase: AgentIslandSessionPhase;
@@ -432,6 +438,7 @@ export function applyAgentIslandUserPrompt(
session.interactionKind = undefined;
session.detail = '';
session.detailSource = null;
+ session.reconnectStatus = null;
session.currentToolUseId = null;
session.toolDetailUntil = null;
clearAssistantStream(session);
@@ -481,6 +488,9 @@ export function applyAgentIslandEvent(
const session = getOrCreateSession(state, meta, now);
applyMeta(session, meta);
+ if (event.type !== 'error') {
+ session.reconnectStatus = null;
+ }
session.lastActivityAt = now;
if (event.type === 'text') {
@@ -590,14 +600,26 @@ export function applyAgentIslandEvent(
}
if (event.type === 'error') {
- clearAssistantStream(session);
const data = asRecord(event.data);
const isTerminal = typeof data?.isTerminal === 'boolean'
? data.isTerminal
: typeof data?.willRetry === 'boolean'
? !data.willRetry
: true;
- if (!isTerminal) return true;
+ if (!isTerminal) {
+ const message = typeof data?.message === 'string' ? data.message : '';
+ const reconnectAttempt = parseReconnectAttemptMessage(message);
+ session.reconnectStatus = reconnectAttempt
+ ? formatReconnectStatus(
+ state.strings.networkReconnecting,
+ reconnectAttempt.attempt,
+ reconnectAttempt.maxAttempts,
+ )
+ : null;
+ return true;
+ }
+ session.reconnectStatus = null;
+ clearAssistantStream(session);
session.running = false;
session.phase = 'error';
session.interactionKind = undefined;
@@ -634,6 +656,7 @@ export function applyAgentIslandInteractionRequest(
): void {
const session = getOrCreateSession(state, meta, now);
applyMeta(session, meta);
+ session.reconnectStatus = null;
session.pendingInteractionIds.add(request.requestId);
session.pendingInteractionKinds.set(request.requestId, request.kind);
session.pendingInteractionDetails.set(request.requestId, detailForInteraction(request, state.toolWording));
@@ -1841,6 +1864,9 @@ function pillTitle(session: AgentIslandSessionState, mode: 'micro' | 'compact'):
}
function compactDetailForSession(session: AgentIslandSessionState): string {
+ if (session.phase === 'running' && session.reconnectStatus) {
+ return truncateInlineText(session.reconnectStatus, AGENT_ISLAND_COMPACT_DETAIL_MAX_LENGTH);
+ }
const messagePreview = messagePreviewTextForSession(session);
if (messagePreview) return truncateInlineText(messagePreview, AGENT_ISLAND_COMPACT_DETAIL_MAX_LENGTH);
@@ -1918,6 +1944,7 @@ function getOrCreateSession(
projectName: projectNameFromWorkingDir(meta.workingDir, meta.workspaceKind),
detail: '',
detailSource: null,
+ reconnectStatus: null,
currentToolUseId: null,
toolDetailUntil: null,
phase: 'running',
@@ -2017,11 +2044,12 @@ function applyMeta(session: AgentIslandSessionState, meta: AgentIslandSessionMet
}
function toSnapshot(session: AgentIslandSessionState): AgentIslandSessionSnapshot {
+ const reconnectStatus = session.phase === 'running' ? session.reconnectStatus : null;
return {
sessionId: session.sessionId,
title: session.title || session.projectName || session.sessionId.slice(0, 8),
projectName: session.projectName,
- detail: session.detail,
+ detail: reconnectStatus ?? session.detail,
compactDetail: compactDetailForSession(session),
messagePreview: session.messagePreview?.line ?? null,
phase: session.phase,
@@ -2298,6 +2326,12 @@ function normalizeInlineText(text: string): string {
.replace(/\s+/g, ' ');
}
+function formatReconnectStatus(template: string, attempt: number, maxAttempts: number): string {
+ return template
+ .replaceAll('{{attempt}}', String(attempt))
+ .replaceAll('{{maxAttempts}}', String(maxAttempts));
+}
+
function truncateInlineText(text: string, maxLength: number): string {
const normalized = normalizeInlineText(text);
const chars = Array.from(normalized);
diff --git a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
index 1f06e7211a..39f887d95a 100644
--- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
@@ -1008,6 +1008,16 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()
expect(secondComplete).not.toHaveBeenCalled();
expect(mocks.persistUserMessage).toHaveBeenCalledTimes(1);
+ h.emit({
+ type: 'error',
+ data: { message: 'Reconnecting... 1/5', isTerminal: false, willRetry: true },
+ });
+ await flushMicrotasks();
+ expect(h.send).toHaveBeenCalledTimes(1);
+ expect(firstComplete).not.toHaveBeenCalled();
+ expect(secondComplete).not.toHaveBeenCalled();
+ expect(mocks.feishuIm.sendText).not.toHaveBeenCalled();
+
h.emit({ type: 'text', data: { text: 'first final', isFinal: true } });
h.emit({ type: 'done', data: {} });
await waitForAssertion(() => {
@@ -1044,6 +1054,14 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()
expect(mocks.feishuIm.sendMarkdownText).toHaveBeenCalledTimes(1);
expect(mocks.persistUserMessage).not.toHaveBeenCalled();
+ h.emit({
+ type: 'error',
+ data: { message: 'Reconnecting... 1/5', isTerminal: false, willRetry: true },
+ });
+ await flushMicrotasks();
+ expect(h.send).not.toHaveBeenCalled();
+ expect(mocks.persistUserMessage).not.toHaveBeenCalled();
+
h.isTurnRunning.mockReturnValue(false);
h.emit({ type: 'done', data: {} }); // desktop turn 的 stray done
await waitForAssertion(() => {
diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.ts
index 782be5f9f5..7403ef3400 100644
--- a/apps/desktop/src/main/im/shared/turnRunner.ts
+++ b/apps/desktop/src/main/im/shared/turnRunner.ts
@@ -1306,8 +1306,9 @@ export function createTurnRunner(
if (state.attached && event.turnOrigin?.kind === 'scheduler') {
transpondScheduledEvent(state, event);
}
- // done/error 同时是"session 空闲了"的信号 — 触发排队消息派发(原有语义)。
- if (event.type === 'done' || event.type === 'error') {
+ // done / 终止型 error 同时是"session 空闲了"的信号 — 触发排队消息派发。
+ // 非终止 error 表示底层仍在自动恢复,不能抢跑下一条消息。
+ if (event.type === 'done' || isTerminalAgentErrorEvent(event)) {
maybeDispatchNextQueued(state, userId);
return;
}
@@ -1339,6 +1340,9 @@ export function createTurnRunner(
}
return handleTurnDoneAsync(state, userId);
case 'error':
+ // 可重试错误只是进行中状态;保持当前 turn、卡片和排队消息不动,
+ // 等后续 text / done 或终止型 error 正常收口。
+ if (!isTerminalAgentErrorEvent(event)) return;
return handleTurnErrorAsync(state, userId, event.data);
case 'session_id':
return persistSdkSessionId(localSessionId, event.data);
diff --git a/apps/desktop/src/renderer/__tests__/errorBannerCodexXaiAuth.test.tsx b/apps/desktop/src/renderer/__tests__/errorBannerCodexXaiAuth.test.tsx
index b7e0035d71..eb1174b859 100644
--- a/apps/desktop/src/renderer/__tests__/errorBannerCodexXaiAuth.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/errorBannerCodexXaiAuth.test.tsx
@@ -10,7 +10,10 @@ const { useCodexRuntimeRouteMock } = vi.hoisted(() => ({
vi.mock('react-i18next', () => ({
useTranslation: () => ({
- t: (key: string) => key,
+ t: (key: string, options?: { attempt?: number; maxAttempts?: number }) =>
+ options?.attempt && options.maxAttempts
+ ? `${key}:${options.attempt}/${options.maxAttempts}`
+ : key,
}),
}));
@@ -71,6 +74,17 @@ describe('ErrorBanner Codex xAI auth classification', () => {
});
describe('ErrorBanner network retry guidance', () => {
+ it('shows Codex reconnect progress while the turn keeps running', () => {
+ render(createElement(ErrorBanner, {
+ error: 'Reconnecting... 3/5',
+ onRetry: vi.fn(),
+ isRecoverable: true,
+ }));
+
+ expect(screen.getByText('chat.errorBanner.networkReconnecting:3/5')).toBeTruthy();
+ expect(screen.queryByTitle('chat.errorBanner.retryTitle')).toBeNull();
+ });
+
it('does not tell the user to click Retry when no safe retry target exists', () => {
render(createElement(ErrorBanner, {
error: 'Request timed out.',
diff --git a/apps/desktop/src/renderer/__tests__/networkError.test.ts b/apps/desktop/src/renderer/__tests__/networkError.test.ts
index 5a739c5e0d..02677da966 100644
--- a/apps/desktop/src/renderer/__tests__/networkError.test.ts
+++ b/apps/desktop/src/renderer/__tests__/networkError.test.ts
@@ -9,7 +9,7 @@
import { describe, it, expect } from 'vitest';
-import { isNetworkishErrorMessage } from '@/utils/networkError';
+import { isNetworkishErrorMessage, parseReconnectAttemptMessage } from '@/utils/networkError';
describe('isNetworkishErrorMessage', () => {
it.each([
@@ -21,6 +21,8 @@ describe('isNetworkishErrorMessage', () => {
'connect ECONNREFUSED 127.0.0.1:3333',
'fetch failed',
'socket hang up',
+ 'Reconnecting... 2/5',
+ 'Reconnecting… 3/5 (stream disconnected before completion)',
])('matches networkish message: %s', (msg) => {
expect(isNetworkishErrorMessage(msg)).toBe(true);
});
@@ -35,3 +37,19 @@ describe('isNetworkishErrorMessage', () => {
expect(isNetworkishErrorMessage(msg)).toBe(false);
});
});
+
+describe('parseReconnectAttemptMessage', () => {
+ it('extracts valid Codex reconnect progress', () => {
+ expect(parseReconnectAttemptMessage('Reconnecting... 3/5')).toEqual({
+ attempt: 3,
+ maxAttempts: 5,
+ });
+ });
+
+ it.each(['Reconnecting...', 'Reconnecting... 0/5', 'Reconnecting... 6/5'])(
+ 'rejects malformed progress: %s',
+ (msg) => {
+ expect(parseReconnectAttemptMessage(msg)).toBeNull();
+ },
+ );
+});
diff --git a/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx b/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
index 060f200064..aeeddca0ab 100644
--- a/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
+++ b/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
@@ -28,7 +28,7 @@ import {
} from '@/hooks/useCodexSessionExpiredPrompt';
import { cn } from '@/lib/utils';
import { isInvalidEncryptedContentError } from '@/utils/encryptedContentError';
-import { isNetworkishErrorMessage } from '@/utils/networkError';
+import { isNetworkishErrorMessage, parseReconnectAttemptMessage } from '@/utils/networkError';
interface ErrorBannerProps {
error: string;
@@ -177,7 +177,9 @@ export function ErrorBanner({
isOpenAiConnectionExpired && isChatGptConnectionConnected(openAiAuthState, false);
const openAiReconnectRequired = isOpenAiConnectionExpired && !openAiConnectionRecoveredSinceError;
// 网络类错误(502/连接失败/fetch failed 等):友好文案 + 原始错误折叠可查。
- const isNetworkishError = isNetworkishErrorMessage(error);
+ // Codex `Reconnecting... N/M` 额外解析次数,让 recoverable 状态持续更新而非裸英文。
+ const reconnectAttempt = parseReconnectAttemptMessage(error);
+ const isNetworkishError = reconnectAttempt !== null || isNetworkishErrorMessage(error);
// Retry 的显示条件与网络错误文案必须共用同一个判定。外部发起的 turn(例如
// scheduler / goal)失败时没有安全的 recovery target,errorRetryText 会是 null;
// 此时不能一边隐藏按钮,一边仍提示用户“点击重试”。
@@ -222,7 +224,12 @@ export function ErrorBanner({
// 非终止(isRecoverable,daemon 自动重试中)与终止(可点重试)文案区分。
// 放在所有专属指引分支之后:401 等更具体的分支优先。
displayError = isRecoverable
- ? t('chat.errorBanner.networkAutoRetrying')
+ ? reconnectAttempt
+ ? t('chat.errorBanner.networkReconnecting', {
+ attempt: reconnectAttempt.attempt,
+ maxAttempts: reconnectAttempt.maxAttempts,
+ })
+ : t('chat.errorBanner.networkAutoRetrying')
: t(
safeRetryText
? 'chat.errorBanner.networkUnreachable'
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 0179d9c43d..c2f6cd6a25 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -61,6 +61,7 @@
"input": "Input",
"done": "Done",
"running": "Running",
+ "networkReconnecting": "({{attempt}}/{{maxAttempts}}) Connection interrupted — reconnecting…",
"updatingTasks": "Updating tasks",
"awaitingPermission": "Awaiting permission",
"awaitingQuestion": "Awaiting your reply",
@@ -4554,6 +4555,7 @@
"networkUnreachable": "Network error: the service is temporarily unreachable. Click \"Retry\" to try again.",
"networkUnreachableNoRetry": "Network error: the service is temporarily unreachable.",
"networkAutoRetrying": "Network error — retrying automatically…",
+ "networkReconnecting": "Connection interrupted — reconnecting ({{attempt}}/{{maxAttempts}})…",
"networkShowRaw": "Show raw error",
"networkHideRaw": "Hide raw error",
"silentStopContinue": "Continue",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 7a12d46239..232b866a3a 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -61,6 +61,7 @@
"input": "入力",
"done": "完了",
"running": "実行中",
+ "networkReconnecting": "({{attempt}}/{{maxAttempts}})接続が中断されました。再接続中…",
"updatingTasks": "タスクを更新中",
"awaitingPermission": "承認待ち",
"awaitingQuestion": "返信待ち",
@@ -4553,6 +4554,7 @@
"networkUnreachable": "ネットワークエラー:サービスに一時的に接続できません。「再試行」を押してください。",
"networkUnreachableNoRetry": "ネットワークエラー:サービスに一時的に接続できません。",
"networkAutoRetrying": "ネットワークエラー:自動的に再試行しています…",
+ "networkReconnecting": "接続が中断されました。再接続中({{attempt}}/{{maxAttempts}})…",
"networkShowRaw": "元のエラーを表示",
"networkHideRaw": "元のエラーを隠す",
"silentStopContinue": "続行",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 005850b50b..f6ad930898 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -61,6 +61,7 @@
"input": "입력",
"done": "완료",
"running": "실행 중",
+ "networkReconnecting": "({{attempt}}/{{maxAttempts}}) 연결이 끊어졌습니다. 다시 연결하는 중…",
"updatingTasks": "작업 업데이트 중",
"awaitingPermission": "승인 대기 중",
"awaitingQuestion": "답장 대기 중",
@@ -4553,6 +4554,7 @@
"networkUnreachable": "네트워크 오류: 서비스에 일시적으로 연결할 수 없습니다. ‘다시 시도’를 눌러 주세요.",
"networkUnreachableNoRetry": "네트워크 오류: 서비스에 일시적으로 연결할 수 없습니다.",
"networkAutoRetrying": "네트워크 오류: 자동으로 다시 시도하는 중…",
+ "networkReconnecting": "연결이 끊어졌습니다. 다시 연결하는 중({{attempt}}/{{maxAttempts}})…",
"networkShowRaw": "원본 오류 보기",
"networkHideRaw": "원본 오류 숨기기",
"silentStopContinue": "계속",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 0a9254f189..5a59b6fcd4 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -61,6 +61,7 @@
"input": "输入",
"done": "完成",
"running": "运行中",
+ "networkReconnecting": "({{attempt}}/{{maxAttempts}})网络连接中断,正在重新连接…",
"updatingTasks": "正在更新任务",
"awaitingPermission": "等待授权",
"awaitingQuestion": "等待你的回复",
@@ -4553,6 +4554,7 @@
"networkUnreachable": "网络异常,服务暂时不可达,可点击「重试」。",
"networkUnreachableNoRetry": "网络异常,服务暂时不可达。",
"networkAutoRetrying": "网络异常,正在自动重试…",
+ "networkReconnecting": "网络连接中断,正在重新连接({{attempt}}/{{maxAttempts}})…",
"networkShowRaw": "查看原始错误",
"networkHideRaw": "收起原始错误",
"silentStopContinue": "继续",
diff --git a/apps/desktop/src/renderer/utils/networkError.ts b/apps/desktop/src/renderer/utils/networkError.ts
index 4cb8a3f30f..5650d2f7b3 100644
--- a/apps/desktop/src/renderer/utils/networkError.ts
+++ b/apps/desktop/src/renderer/utils/networkError.ts
@@ -9,12 +9,38 @@
* retry-loop 何时透出提示;不跨 bundle 共享代码,与 401 pattern 的两端一致性
* 同款惯例)。修改时两处同步。
*
- * "Request timed out" / "Connection error" 是 Anthropic SDK 的
+ * `Reconnecting... N/M` 是 Codex streaming response 的有限重连状态;解析后的
+ * attempt/maxAttempts 会显示在 recoverable banner。`Request timed out` /
+ * `Connection error` 是 Anthropic SDK 的
* APIConnectionTimeoutError / APIConnectionError 原文(SDK 重试耗尽后透传成
* 终止型 turn error),同属重试可自愈的网络类(2026-07-13 超时横幅裸英文实锤)。
*/
+export interface ReconnectAttempt {
+ attempt: number;
+ maxAttempts: number;
+}
+
+export function parseReconnectAttemptMessage(message: string): ReconnectAttempt | null {
+ const match = /\bReconnecting(?:\.{3}|…)\s*(\d+)\s*\/\s*(\d+)\b/i.exec(message);
+ if (!match) return null;
+ const attempt = Number(match[1]);
+ const maxAttempts = Number(match[2]);
+ if (
+ !Number.isSafeInteger(attempt) ||
+ !Number.isSafeInteger(maxAttempts) ||
+ attempt < 1 ||
+ maxAttempts < attempt
+ ) {
+ return null;
+ }
+ return { attempt, maxAttempts };
+}
+
export function isNetworkishErrorMessage(message: string): boolean {
- return /\b50[234]\b|Bad Gateway|Service Unavailable|Gateway Time-?out|upstream unreachable|ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOTFOUND|ENETUNREACH|EHOSTUNREACH|EPIPE|EAI_AGAIN|fetch failed|network error|socket hang up|AggregateError|Request timed out|Connection error/i.test(
- message,
+ return (
+ parseReconnectAttemptMessage(message) !== null ||
+ /\b50[234]\b|Bad Gateway|Service Unavailable|Gateway Time-?out|upstream unreachable|ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOTFOUND|ENETUNREACH|EHOSTUNREACH|EPIPE|EAI_AGAIN|fetch failed|network error|socket hang up|AggregateError|Request timed out|Connection error/i.test(
+ message,
+ )
);
}
diff --git a/apps/desktop/src/shared/agentIsland.ts b/apps/desktop/src/shared/agentIsland.ts
index b5a092c3d1..8877ade592 100644
--- a/apps/desktop/src/shared/agentIsland.ts
+++ b/apps/desktop/src/shared/agentIsland.ts
@@ -411,6 +411,8 @@ export interface AgentIslandStrings {
input: string;
done: string;
running: string;
+ /** `{{attempt}}` / `{{maxAttempts}}` are interpolated by the main-process reducer. */
+ networkReconnecting: string;
updatingTasks: string;
/** 等待交互摘要(按 interactionKind 出人话,替代过期 tool 状态行;文案与侧栏卡片 awaiting* 对齐)。 */
awaitingPermission: string;
@@ -437,6 +439,7 @@ export const DEFAULT_AGENT_ISLAND_STRINGS: AgentIslandStrings = {
input: 'Input',
done: 'Done',
running: 'Running',
+ networkReconnecting: 'Connection interrupted — reconnecting ({{attempt}}/{{maxAttempts}})…',
updatingTasks: 'Updating tasks',
awaitingPermission: 'Awaiting permission',
awaitingQuestion: 'Awaiting your reply',
diff --git a/apps/mobile/app/devices/index.tsx b/apps/mobile/app/devices/index.tsx
index cbfe3a2735..4468e1e25f 100644
--- a/apps/mobile/app/devices/index.tsx
+++ b/apps/mobile/app/devices/index.tsx
@@ -299,9 +299,13 @@ export default function HomeScreen() {
const hydrateDeviceSessions = useCallback(async (device: DeviceView): Promise<HydrateDeviceSessionsResult> => {
updateDeviceConnectionState(device.deviceId, 'syncing');
try {
- const [list, activeSessions] = await withTransientRemoteRetry(async () => {
+ const [list, activeSessions, activeSessionSnapshotEpoch] = await withTransientRemoteRetry(async () => {
await subscribe('device-list', device.deviceId, ['sessions']);
- return Promise.all([
+ // Capture inside the retry callback so every maker:list-active attempt gets its own
+ // fence. A newer retry push received while this request is in flight must survive
+ // the older snapshot, while progress predating this attempt can be cleared.
+ const activeSessionSnapshotEpoch = remoteSessionStore.captureActiveSessionSnapshotEpoch();
+ const [list, activeSessions] = await Promise.all([
invoke<RemoteSession[]>(device.deviceId, 'local-db:sessions:list', [
LIST_LIMIT,
remoteListStatusFilter(statusFilter),
@@ -315,6 +319,7 @@ export default function HomeScreen() {
throw err;
}),
]);
+ return [list, activeSessions, activeSessionSnapshotEpoch] as const;
});
const nextSessions = Array.isArray(list) ? list : [];
remoteSessionStore.setDeviceSessions(
@@ -323,7 +328,11 @@ export default function HomeScreen() {
nextSessions,
);
if (Array.isArray(activeSessions)) {
- remoteSessionStore.setActiveSessionSnapshots(device.deviceId, activeSessions);
+ remoteSessionStore.setActiveSessionSnapshots(
+ device.deviceId,
+ activeSessions,
+ activeSessionSnapshotEpoch,
+ );
}
// schedule-index(1+N 个 listRuns)是次要徽标数据,延后发,避开"开 app→立刻点会话"时和会话关键读
// 抢同一条 WS 管道(见 scheduleIndexDefer / issue #324)。home 自动化分组与名称已由 fallbackScheduleInfo
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index fb871f4f49..d84a3b8a42 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -398,6 +398,7 @@ import {
sessionMetaWriteGuard,
sessionMetaWriteQueue,
sessionPendingWrites,
+ type RemoteSessionRunStatus,
useRemoteSessions,
useSessionGoalStatus,
useSessionInputProjection,
@@ -2637,23 +2638,36 @@ export default function SessionScreen() {
// subscribe 只负责之后的实时推送,不该挡数据读;失败不影响 open,重连 rehydration 会补订阅。
void subscribe(`session:${sessionId}`, deviceId, ['sessions']).catch(() => undefined);
};
+ const fetchActiveSessionSnapshot = async () => {
+ // Capture immediately before every request. Because this helper is invoked inside
+ // withTransientRemoteRetry, each retry receives a fresh fence as well.
+ const activityEpochAtFetchStart = remoteSessionStore.captureActiveSessionSnapshotEpoch();
+ const activeSessions = await maker.listActiveSessions().catch(() => []);
+ return { activeSessions, activityEpochAtFetchStart };
+ };
setLoading(true);
setError(null);
try {
if (!isReopen) {
// 首开 / 强制替换:A1 全量并行(含整窗 listMessages),不回退。
- const [sessionMeta, history, pendingInteractions, projection, activeSessions] = await withTransientRemoteRetry(async () => {
+ const [sessionMeta, history, pendingInteractions, projection, activeSessionSnapshot] = await withTransientRemoteRetry(async () => {
await openAndSubscribe();
return Promise.all([
maker.getSession(sessionId),
listMessagesWithPayloadRetry((limit) => maker.listMessages(sessionId, { limit })),
maker.getPendingInteractions(sessionId),
maker.input.getProjection(sessionId),
- maker.listActiveSessions().catch(() => []),
+ fetchActiveSessionSnapshot(),
]);
});
remoteSessionStore.upsertDeviceSession(deviceId, deviceName, sessionMeta);
- remoteSessionStore.setActiveSessionSnapshots(deviceId, Array.isArray(activeSessions) ? activeSessions : []);
+ remoteSessionStore.setActiveSessionSnapshots(
+ deviceId,
+ Array.isArray(activeSessionSnapshot.activeSessions)
+ ? activeSessionSnapshot.activeSessions
+ : [],
+ activeSessionSnapshot.activityEpochAtFetchStart,
+ );
const historyPage: RemoteMessage[] = Array.isArray(history.messages) ? history.messages : [];
if (options.replaceMessages) {
remoteSessionStore.setMessages(sessionId, historyPage);
@@ -2666,13 +2680,13 @@ export default function SessionScreen() {
remoteSessionStore.setInputProjection(sessionId, projection);
} else {
// 重开:便宜并行(不含整窗 listMessages)拿 meta + pending + projection + active。
- const [sessionMeta, pendingInteractions, projection, activeSessions] = await withTransientRemoteRetry(async () => {
+ const [sessionMeta, pendingInteractions, projection, activeSessionSnapshot] = await withTransientRemoteRetry(async () => {
await openAndSubscribe();
return Promise.all([
maker.getSession(sessionId),
maker.getPendingInteractions(sessionId),
maker.input.getProjection(sessionId),
- maker.listActiveSessions().catch(() => []),
+ fetchActiveSessionSnapshot(),
]);
});
// 廉价对账:updatedAt 主信号(任何消息变化都会 bump),_count 仅在两侧都有时作辅助;
@@ -2686,7 +2700,13 @@ export default function SessionScreen() {
storedSession: storedSessionAtStart,
});
remoteSessionStore.upsertDeviceSession(deviceId, deviceName, sessionMeta);
- remoteSessionStore.setActiveSessionSnapshots(deviceId, Array.isArray(activeSessions) ? activeSessions : []);
+ remoteSessionStore.setActiveSessionSnapshots(
+ deviceId,
+ Array.isArray(activeSessionSnapshot.activeSessions)
+ ? activeSessionSnapshot.activeSessions
+ : [],
+ activeSessionSnapshot.activityEpochAtFetchStart,
+ );
if (metaChanged) {
const history = await withTransientRemoteRetry(() =>
listMessagesWithPayloadRetry(
@@ -7119,6 +7139,7 @@ export default function SessionScreen() {
]}
>
<ComposerActivityStatus
+ reconnectAttempt={remoteSessionRunStatus.reconnectAttempt}
sideTaskRunning={remoteSessionRunStatus.sideTaskRunning}
startedAt={composerActivityStartedAtMs}
tokenUsage={composerActivityTokenUsage}
@@ -7904,11 +7925,13 @@ function ComposerRuntimePill({
}
function ComposerActivityStatus({
+ reconnectAttempt,
sideTaskRunning,
startedAt,
tokenUsage,
visible,
}: {
+ reconnectAttempt: RemoteSessionRunStatus['reconnectAttempt'];
sideTaskRunning: boolean;
startedAt: number | null;
tokenUsage: number;
@@ -7916,6 +7939,7 @@ function ComposerActivityStatus({
}) {
const styles = useThemedStyles(makeStyles);
const { colors } = useTheme();
+ const { t } = useTranslation();
const [elapsed, setElapsed] = useState(0);
useEffect(() => {
@@ -7935,6 +7959,9 @@ function ComposerActivityStatus({
const elapsedText = formatComposerActivityElapsed(elapsed);
const tokenText = formatComposerActivityTokens(tokenUsage);
+ const activityText = reconnectAttempt
+ ? t('session.screen.networkReconnecting')
+ : t('session.screen.thinking');
return (
<View
@@ -7944,7 +7971,12 @@ function ComposerActivityStatus({
>
<View style={styles.composerActivityPrimary}>
<Sparkles color={colors.statusAccent} size={iconSize.sm} strokeWidth={iconStroke.regular} />
- <Text style={styles.composerActivityStatusText}>Thinking...</Text>
+ <Text numberOfLines={1} style={styles.composerActivityStatusText}>{activityText}</Text>
+ {reconnectAttempt ? (
+ <Text style={[styles.composerActivityStatusText, styles.composerActivityProgressText]}>
+ {reconnectAttempt.attempt}/{reconnectAttempt.maxAttempts}
+ </Text>
+ ) : null}
</View>
<View style={styles.composerActivityMeta}>
<Text style={styles.composerActivityMetaText}>{elapsedText}</Text>
@@ -8365,18 +8397,25 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({
},
composerActivityPrimary: {
alignItems: 'center',
+ flex: 1,
flexDirection: 'row',
gap: 6,
+ marginRight: spacing.sm,
minWidth: 0,
},
composerActivityStatusText: {
color: colors.statusAccent,
+ flexShrink: 1,
fontSize: typeScale.footnote,
fontWeight: fontWeight.medium,
lineHeight: lineHeight.caption,
},
+ composerActivityProgressText: {
+ flexShrink: 0,
+ },
composerActivityMeta: {
alignItems: 'center',
+ flexShrink: 0,
flexDirection: 'row',
gap: 4,
minWidth: 0,
diff --git a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts b/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
index 60d3c3e3d3..36266453d8 100644
--- a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
+++ b/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
@@ -178,7 +178,10 @@ describe('mobile home desktop-first surface', () => {
expect(source).toContain('if (isAccessRevokedError(error) || isDeviceOfflineError(error)) return false;');
expect(source).toContain("if (text.includes('REMOTE_DISABLED')) return false;");
expect(source).toContain('return true;');
- expect(source).toContain('remoteSessionStore.setActiveSessionSnapshots(device.deviceId, activeSessions)');
+ expect(source).toContain('const [list, activeSessions, activeSessionSnapshotEpoch]');
+ expect(source).toContain('remoteSessionStore.captureActiveSessionSnapshotEpoch()');
+ expect(source).toContain('return [list, activeSessions, activeSessionSnapshotEpoch] as const;');
+ expect(source).toContain('activeSessionSnapshotEpoch,');
expect(source).toContain('remoteScheduleEventStore.subscribe(() => {');
expect(source).toContain('const snapshot = remoteScheduleEventStore.getSnapshot(deviceId)');
expect(source).toContain('const version = snapshot.version');
diff --git a/apps/mobile/src/__tests__/remoteSessionStore.test.ts b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
index 52763431ac..e833e3b228 100644
--- a/apps/mobile/src/__tests__/remoteSessionStore.test.ts
+++ b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
@@ -1289,6 +1289,37 @@ describe('remoteSessionStore', () => {
}
});
+ it('clears stale reconnect progress from an active snapshot without erasing newer retry events', () => {
+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);
+ remoteSessionStore.applyRemotePush('dev-1', 'maker:event', {
+ sessionId: 's1',
+ event: { type: 'error', data: { message: 'Reconnecting... 1/5', willRetry: true } },
+ });
+
+ const currentSnapshotEpoch = remoteSessionStore.captureActiveSessionSnapshotEpoch();
+ remoteSessionStore.setActiveSessionSnapshots(
+ 'dev-1',
+ [{ sessionId: 's1', isTurnRunning: true }],
+ currentSnapshotEpoch,
+ );
+ expect(remoteSessionStore.getSessionRunStatus('s1').reconnectAttempt).toBeNull();
+
+ const staleSnapshotEpoch = remoteSessionStore.captureActiveSessionSnapshotEpoch();
+ remoteSessionStore.applyRemotePush('dev-1', 'maker:event', {
+ sessionId: 's1',
+ event: { type: 'error', data: { message: 'Reconnecting... 2/5', willRetry: true } },
+ });
+ remoteSessionStore.setActiveSessionSnapshots(
+ 'dev-1',
+ [{ sessionId: 's1', isTurnRunning: true }],
+ staleSnapshotEpoch,
+ );
+ expect(remoteSessionStore.getSessionRunStatus('s1').reconnectAttempt).toEqual({
+ attempt: 2,
+ maxAttempts: 5,
+ });
+ });
+
it('tracks session running state from maker event push boundaries', () => {
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-01-01T00:00:10.000Z'));
@@ -1305,9 +1336,54 @@ describe('remoteSessionStore', () => {
remoteSessionStore.applyRemotePush('dev-1', 'maker:event', {
sessionId: 's1',
- event: { type: 'error', data: { message: 'retrying', willRetry: true } },
+ event: { type: 'error', data: { message: 'Reconnecting... 1/5', willRetry: true } },
});
expect(remoteSessionStore.isSessionRunning('s1')).toBe(true);
+ expect(remoteSessionStore.getSessionRunStatus('s1').reconnectAttempt).toEqual({
+ attempt: 1,
+ maxAttempts: 5,
+ });
+
+ remoteSessionStore.applyRemotePush('dev-1', 'maker:event', {
+ sessionId: 's1',
+ event: {
+ type: 'error',
+ data: {
+ message: 'Reconnecting... 2/5 (stream disconnected before completion)',
+ isTerminal: false,
+ willRetry: true,
+ },
+ },
+ });
+ expect(remoteSessionStore.getSessionRunStatus('s1').reconnectAttempt).toEqual({
+ attempt: 2,
+ maxAttempts: 5,
+ });
+
+ remoteSessionStore.applyRemotePush('dev-1', 'maker:event', {
+ sessionId: 's1',
+ event: { type: 'error', data: { message: 'Waiting before retry', willRetry: true } },
+ });
+ expect(remoteSessionStore.getSessionRunStatus('s1').reconnectAttempt).toBeNull();
+
+ remoteSessionStore.applyRemotePush('dev-1', 'maker:event', {
+ sessionId: 's1',
+ event: { type: 'error', data: { message: 'Reconnecting... 3/5', willRetry: true } },
+ });
+ pushMakerText('s1', 'persist-reconnected', 'resumed', false);
+ expect(remoteSessionStore.getSessionRunStatus('s1').reconnectAttempt).toBeNull();
+
+ remoteSessionStore.applyRemotePush('dev-1', 'maker:event', {
+ sessionId: 's1',
+ event: { type: 'error', data: { message: 'Reconnecting... 4/5', willRetry: true } },
+ });
+ remoteSessionStore.applyInteractionRequest('s1', pending('permission', 'permission-1'));
+ expect(remoteSessionStore.getSessionRunStatus('s1').reconnectAttempt).toBeNull();
+
+ remoteSessionStore.applyRemotePush('dev-1', 'maker:event', {
+ sessionId: 's1',
+ event: { type: 'error', data: { message: 'Reconnecting... 5/5', willRetry: true } },
+ });
vi.setSystemTime(new Date('2026-01-01T00:00:20.000Z'));
remoteSessionStore.applyRemotePush('dev-1', 'maker:event', {
@@ -1317,6 +1393,7 @@ describe('remoteSessionStore', () => {
expect(remoteSessionStore.getSessionRunStatus('s1')).toMatchObject({
isRunning: true,
startedAt: Date.parse('2026-01-01T00:00:10.000Z'),
+ reconnectAttempt: null,
status: 'Thinking',
tokenUsage: 1200,
});
diff --git a/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts b/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts
index a2a7e69ab1..5f49ef6a9b 100644
--- a/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts
+++ b/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts
@@ -7,6 +7,18 @@ const readTextLf = (...args: Parameters<typeof readFileSync>): string =>
String(readFileSync(...args)).replace(/\r\n/g, '\n');
describe('mobile session composer desktop-first surface', () => {
+ it('fences every active-session snapshot request against newer retry progress', () => {
+ const source = readTextLf(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');
+
+ expect(source).toContain('const fetchActiveSessionSnapshot = async () => {');
+ expect(source).toContain(
+ 'const activityEpochAtFetchStart = remoteSessionStore.captureActiveSessionSnapshotEpoch();',
+ );
+ expect((source.match(/fetchActiveSessionSnapshot\(\),/g) ?? []).length).toBe(2);
+ expect((source.match(/activeSessionSnapshot\.activityEpochAtFetchStart/g) ?? []).length).toBe(2);
+ expect((source.match(/maker\.listActiveSessions\(\)/g) ?? []).length).toBe(1);
+ });
+
it('uses icon controls for attachment quick actions near the composer', () => {
const source = readTextLf(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');
const voiceStart = source.indexOf('const startVoiceRecording = useCallback(async () => {');
@@ -124,11 +136,14 @@ describe('mobile session composer desktop-first surface', () => {
expect(source).not.toContain('testID="session.attachmentPathPanel"');
expect(source).not.toContain('被控电脑上的文件路径');
expect(source).toContain('testID="session.composerActivityStatus"');
- expect(source).toContain('Thinking...');
+ expect(source).toContain("t('session.screen.thinking')");
+ expect(source).toContain("t('session.screen.networkReconnecting')");
+ expect(source).toContain('{reconnectAttempt.attempt}/{reconnectAttempt.maxAttempts}');
expect(source).toContain('ArrowDown');
expect(source).toContain('useSessionRunStatus');
expect(source).toContain('remoteSessionRunStatus.tokenUsage');
expect(source).toContain('remoteSessionRunStatus.startedAt ?? composerActivityStartedAt');
+ expect(source).toContain('reconnectAttempt={remoteSessionRunStatus.reconnectAttempt}');
expect(source).toContain('sideTaskRunning={remoteSessionRunStatus.sideTaskRunning}');
expect(source).toContain('startedAt={composerActivityStartedAtMs}');
expect(source).toContain('tokenUsage={composerActivityTokenUsage}');
@@ -142,6 +157,7 @@ describe('mobile session composer desktop-first surface', () => {
expect(source).toContain('marginTop: spacing.lg');
expect(source).toContain('height: 25');
expect(source).toContain('composerActivityStatusText');
+ expect(source).toContain('composerActivityProgressText');
expect(composerStatusCallIndex).toBeGreaterThan(-1);
expect(composerStatusCallIndex).toBeLessThan(composerViewStart);
expect(composerViewSource).not.toContain('<ComposerActivityStatus');
diff --git a/apps/mobile/src/i18n/locales/en/session.json b/apps/mobile/src/i18n/locales/en/session.json
index 2563885f2c..2db80bc769 100644
--- a/apps/mobile/src/i18n/locales/en/session.json
+++ b/apps/mobile/src/i18n/locales/en/session.json
@@ -25,6 +25,8 @@
"capabilitiesUnsupported": "Unsupported remote capability format"
},
"screen": {
+ "thinking": "Thinking…",
+ "networkReconnecting": "Reconnecting…",
"composerSyncing": "Syncing session data; you can send once it finishes.",
"composerSessionNotSynced": "This conversation has not finished syncing yet.",
"composerCreating": "Creating the session; you can keep sending after the first message goes out.",
diff --git a/apps/mobile/src/i18n/locales/ja/session.json b/apps/mobile/src/i18n/locales/ja/session.json
index 6c9e778c45..dd5b2a661e 100644
--- a/apps/mobile/src/i18n/locales/ja/session.json
+++ b/apps/mobile/src/i18n/locales/ja/session.json
@@ -25,6 +25,8 @@
"capabilitiesUnsupported": "リモート機能の形式に対応していません"
},
"screen": {
+ "thinking": "考えています…",
+ "networkReconnecting": "再接続中…",
"composerSyncing": "セッションデータを同期中です。完了すると送信できます。",
"composerSessionNotSynced": "この会話はまだ同期が完了していません。",
"composerCreating": "セッションを作成中です。最初のメッセージ送信後に続けて送信できます。",
diff --git a/apps/mobile/src/i18n/locales/ko/session.json b/apps/mobile/src/i18n/locales/ko/session.json
index 9ff9539065..808987e217 100644
--- a/apps/mobile/src/i18n/locales/ko/session.json
+++ b/apps/mobile/src/i18n/locales/ko/session.json
@@ -25,6 +25,8 @@
"capabilitiesUnsupported": "지원되지 않는 원격 기능 형식입니다"
},
"screen": {
+ "thinking": "생각 중…",
+ "networkReconnecting": "다시 연결하는 중…",
"composerSyncing": "세션 데이터를 동기화 중입니다. 완료되면 보낼 수 있습니다.",
"composerSessionNotSynced": "이 대화는 아직 동기화가 끝나지 않았습니다.",
"composerCreating": "세션을 만드는 중입니다. 첫 메시지가 전송되면 계속 보낼 수 있습니다.",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/session.json b/apps/mobile/src/i18n/locales/zh-CN/session.json
index f5f7131589..fc9ba8f652 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/session.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/session.json
@@ -25,6 +25,8 @@
"capabilitiesUnsupported": "远程能力返回格式不支持"
},
"screen": {
+ "thinking": "思考中…",
+ "networkReconnecting": "正在重新连接…",
"composerSyncing": "正在同步对话数据,同步完成后即可发送。",
"composerSessionNotSynced": "当前对话还没有同步完成。",
"composerCreating": "对话创建中,首条消息发出后即可继续发送。",
diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.ts
index a8dd824da4..1866a75bf9 100644
--- a/apps/mobile/src/session/remoteSessionStore.ts
+++ b/apps/mobile/src/session/remoteSessionStore.ts
@@ -46,12 +46,18 @@ export const sessionMetaWriteQueue = createSessionWriteQueue();
export interface RemoteSessionRunStatus {
isRunning: boolean;
+ reconnectAttempt: RemoteSessionReconnectAttempt | null;
sideTaskRunning: boolean;
startedAt: number | null;
status: string;
tokenUsage: number;
}
+export interface RemoteSessionReconnectAttempt {
+ attempt: number;
+ maxAttempts: number;
+}
+
interface SessionMessageSyncMarker {
messageCount: number | null;
updatedAt: string;
@@ -65,6 +71,7 @@ interface LivePlanSnapshot {
const EMPTY_SESSION_RUN_STATUS: RemoteSessionRunStatus = Object.freeze({
isRunning: false,
+ reconnectAttempt: null,
sideTaskRunning: false,
startedAt: null,
status: '',
@@ -181,6 +188,11 @@ const inputProjections = new Map<string, InputProjection>();
const sessionLiveActivity = new Map<string, RemoteSessionLiveActivity>();
const sessionRunning = new Map<string, boolean>();
const sessionRunStatus = new Map<string, RemoteSessionRunStatus>();
+// `maker:list-active` snapshots race live maker pushes during reconnect hydration. A snapshot
+// may clear an older transient reconnect attempt, but must not erase a newer retry event that
+// arrived after the request started.
+const sessionMakerActivityEpochs = new Map<string, number>();
+let makerActivityEpoch = 0;
const sessionMessageSyncMarkers = new Map<string, SessionMessageSyncMarker>();
// Per-session live sub-agent task state, decoded from `agent_task_update` events (live-only,
// never persisted — see @cindy/maker-shared/agent-task). Keyed taskId/parentToolUseId → update.
@@ -1449,13 +1461,22 @@ export const remoteSessionStore = {
const next: RemoteSessionRunStatus = {
...current,
isRunning: running,
+ reconnectAttempt: running ? current.reconnectAttempt : null,
sideTaskRunning: running ? current.sideTaskRunning : false,
startedAt: running ? (current.startedAt ?? Date.now()) : null,
};
if (writeSessionRunStatus(sessionId, next) || turnBoundaryChanged || streamingChanged) emit();
},
- setActiveSessionSnapshots(deviceId: string, list: readonly unknown[]): void {
+ captureActiveSessionSnapshotEpoch(): number {
+ return makerActivityEpoch;
+ },
+
+ setActiveSessionSnapshots(
+ deviceId: string,
+ list: readonly unknown[],
+ activityEpochAtFetchStart = makerActivityEpoch,
+ ): void {
// `maker:list-active` returns only currently active sessions. Absence is not
// an idle assertion: the request can have started before a turn and complete
// after a live delta, or a stale reconnect response can race a newer push.
@@ -1478,9 +1499,12 @@ export const remoteSessionStore = {
changed = writeMakerTurnRunning(sessionId, false) || changed;
}
const current = readSessionRunStatus(sessionId);
+ const hasNewerMakerActivity = (sessionMakerActivityEpochs.get(sessionId) ?? 0)
+ > activityEpochAtFetchStart;
const next: RemoteSessionRunStatus = {
...current,
isRunning: running,
+ reconnectAttempt: running && hasNewerMakerActivity ? current.reconnectAttempt : null,
sideTaskRunning: running ? current.sideTaskRunning : false,
startedAt: running ? (current.startedAt ?? Date.now()) : null,
};
@@ -1494,6 +1518,7 @@ export const remoteSessionStore = {
// 本端已对某 revision 做过决定时,更旧的快照也不得把它带回来(见 interactionRevisionFloors)。
if (isInteractionResolveSuppressed(sessionId, item)) return;
const streamingChanged = flushAndFinalizeRemoteStreamingMessages(sessionId);
+ const reconnectCleared = clearSessionReconnectAttempt(sessionId);
const existing = pendingInteractions.get(sessionId) ?? [];
// 早发晚到的旧 push 不得把手上更新的那份换回旧版本。
const requestId = item.request.requestId;
@@ -1505,7 +1530,7 @@ export const remoteSessionStore = {
);
const next = dedupeInteractions([...existing, fresher]);
if (deepValueEqual(existing, next)) {
- if (streamingChanged) emit();
+ if (streamingChanged || reconnectCleared) emit();
return;
}
pendingInteractions.set(sessionId, next);
@@ -1819,6 +1844,7 @@ export const remoteSessionStore = {
changed = writeSessionRunStatus(sessionId, {
...current,
isRunning: false,
+ reconnectAttempt: null,
sideTaskRunning: false,
startedAt: null,
}) || changed;
@@ -1827,14 +1853,19 @@ export const remoteSessionStore = {
},
applyMakerEvent(sessionId: string, event: Record<string, unknown>, persistId?: string): void {
+ markSessionMakerActivity(sessionId);
const type = readString(event, 'type');
+ const reconnectCleared = type !== null && type !== 'error' && type !== 'done'
+ ? clearSessionReconnectAttempt(sessionId)
+ : false;
if (type === 'text') {
if (isRemoteTextDeltaEvent(event)) {
- if (enqueueRemoteTextDelta(sessionId, event, persistId)) emit();
+ if (enqueueRemoteTextDelta(sessionId, event, persistId) || reconnectCleared) emit();
return;
}
let changed = flushPendingTextDelta(sessionId);
changed = applyRemoteTextEvent(sessionId, event, persistId) || changed;
+ changed = reconnectCleared || changed;
if (changed) emit();
return;
}
@@ -1890,6 +1921,21 @@ export const remoteSessionStore = {
}
const textFlushed = flushPendingTextDelta(sessionId);
+ if (type === 'error') {
+ const data = isRecord(event.data) ? event.data : null;
+ const reconnectAttempt = data?.willRetry === true
+ ? parseReconnectAttemptMessage(readString(data, 'message') ?? '')
+ : null;
+ const current = readSessionRunStatus(sessionId);
+ const changed = writeSessionRunStatus(sessionId, {
+ ...current,
+ isRunning: true,
+ reconnectAttempt,
+ startedAt: current.startedAt ?? Date.now(),
+ });
+ if (changed || textFlushed) emit();
+ return;
+ }
if (type === 'tool_use') {
// Finalize before applying update_plan so its row update and the streaming
// row transition are published in one snapshot notification.
@@ -1899,10 +1945,10 @@ export const remoteSessionStore = {
);
const livePlan = applyLivePlanToolUseMessage(sessionId, event, persistId);
if (livePlan.handled) {
- if (textFlushed || streamingChanged || livePlan.changed) emit();
+ if (textFlushed || streamingChanged || livePlan.changed || reconnectCleared) emit();
return;
}
- if (textFlushed || streamingChanged) emit();
+ if (textFlushed || streamingChanged || reconnectCleared) emit();
return;
}
if (type === 'agent_task_update') {
@@ -1917,7 +1963,7 @@ export const remoteSessionStore = {
if (next) {
sessionTaskUpdates.set(sessionId, next);
emit();
- } else if (textFlushed) {
+ } else if (textFlushed || reconnectCleared) {
emit();
}
return;
@@ -1934,7 +1980,7 @@ export const remoteSessionStore = {
// Transcript replay and the live stream may forward the same provider boundary.
// De-duplicate before finalizing, otherwise a replay could end post-compact work.
if (existing.some((message) => messageKey(message) === clientId)) {
- if (textFlushed) emit();
+ if (textFlushed || reconnectCleared) emit();
return;
}
// The compact boundary itself preserves the historical `streaming: false` marker
@@ -1995,6 +2041,7 @@ export const remoteSessionStore = {
}
const next: RemoteSessionRunStatus = {
isRunning,
+ reconnectAttempt: null,
sideTaskRunning: isRunning ? data?.skipTurnReset === true : false,
startedAt: isRunning ? (current.startedAt ?? Date.now()) : null,
status: rawStatus ?? current.status,
@@ -2006,10 +2053,11 @@ export const remoteSessionStore = {
|| turnBoundaryChanged
|| textFlushed
|| streamingChanged
+ || reconnectCleared
) emit();
return;
}
- if (textFlushed) emit();
+ if (textFlushed || reconnectCleared) emit();
},
removeDevice(deviceId: string): void {
@@ -2027,6 +2075,7 @@ export const remoteSessionStore = {
sessionLiveActivity.delete(sessionId);
sessionRunning.delete(sessionId);
sessionRunStatus.delete(sessionId);
+ sessionMakerActivityEpochs.delete(sessionId);
sessionMessageSyncMarkers.delete(sessionId);
sessionTaskUpdates.delete(sessionId);
streamingAssistantClientIds.delete(sessionId);
@@ -2061,6 +2110,8 @@ export const remoteSessionStore = {
sessionLiveActivity.clear();
sessionRunning.clear();
sessionRunStatus.clear();
+ sessionMakerActivityEpochs.clear();
+ makerActivityEpoch = 0;
sessionMessageSyncMarkers.clear();
sessionTaskUpdates.clear();
streamingAssistantClientIds.clear();
@@ -2213,6 +2264,33 @@ function readSessionRunStatus(sessionId: string): RemoteSessionRunStatus {
return sessionRunStatus.get(sessionId) ?? EMPTY_SESSION_RUN_STATUS;
}
+function clearSessionReconnectAttempt(sessionId: string): boolean {
+ const current = readSessionRunStatus(sessionId);
+ if (!current.reconnectAttempt) return false;
+ return writeSessionRunStatus(sessionId, { ...current, reconnectAttempt: null });
+}
+
+function markSessionMakerActivity(sessionId: string): void {
+ makerActivityEpoch += 1;
+ sessionMakerActivityEpochs.set(sessionId, makerActivityEpoch);
+}
+
+function parseReconnectAttemptMessage(message: string): RemoteSessionReconnectAttempt | null {
+ const match = /\bReconnecting(?:\.{3}|…)\s*(\d+)\s*\/\s*(\d+)\b/i.exec(message);
+ if (!match) return null;
+ const attempt = Number(match[1]);
+ const maxAttempts = Number(match[2]);
+ if (
+ !Number.isSafeInteger(attempt)
+ || !Number.isSafeInteger(maxAttempts)
+ || attempt < 1
+ || maxAttempts < attempt
+ ) {
+ return null;
+ }
+ return { attempt, maxAttempts };
+}
+
// 写 maker turn 边界,返回是否实际变化——变化必须参与调用方的 emit 判定(宽 run status
// 可能已被 activity / 快照流改到相同值,单靠 writeSessionRunStatus 的返回值会漏通知)。
function writeMakerTurnRunning(sessionId: string, running: boolean): boolean {
diff --git a/packages/maker-core/src/agents/codex/translator.test.ts b/packages/maker-core/src/agents/codex/translator.test.ts
index 78fa9e39e7..1853e8a9f9 100644
--- a/packages/maker-core/src/agents/codex/translator.test.ts
+++ b/packages/maker-core/src/agents/codex/translator.test.ts
@@ -299,6 +299,55 @@ describe('translateErrorNotification', () => {
expect(rt.networkRetryNotice).toBeNull();
});
+ it('willRetry=true Codex 重连进度 → 每一档都透出为非终止状态', async () => {
+ const rt = newCodexRuntimeState();
+ const ctx = makeCtx(rt);
+ const q = createAsyncQueue<AgentEvent>();
+ translateErrorNotification(
+ makeParams({ willRetry: true, message: 'Reconnecting... 1/5' }),
+ q,
+ ctx,
+ );
+ translateErrorNotification(
+ makeParams({
+ willRetry: true,
+ message: 'Reconnecting... 2/5 (stream disconnected before completion)',
+ }),
+ q,
+ ctx,
+ );
+ const events = await collect(q);
+ expect(events).toHaveLength(2);
+ expect(events.map((event) => event.data)).toEqual([
+ expect.objectContaining({
+ message: 'Reconnecting... 1/5',
+ isTerminal: false,
+ willRetry: true,
+ }),
+ expect.objectContaining({
+ message: 'Reconnecting... 2/5 (stream disconnected before completion)',
+ isTerminal: false,
+ willRetry: true,
+ }),
+ ]);
+ });
+
+ it('仅按脱敏后的可见文案识别重连进度', async () => {
+ const rt = newCodexRuntimeState();
+ const q = createAsyncQueue<AgentEvent>();
+ translateErrorNotification(
+ makeParams({
+ willRetry: true,
+ message: 'Authorization: Bearer secret-token Reconnecting... 1/5',
+ }),
+ q,
+ makeCtx(rt),
+ );
+
+ const events = await collect(q);
+ expect(events).toHaveLength(0);
+ });
+
it('willRetry=true 网络类错误同 turn 第 2 次 → 透出一条非终止提示,之后不再发', async () => {
const rt = newCodexRuntimeState();
const ctx = makeCtx(rt);
diff --git a/packages/maker-core/src/agents/codex/translator.ts b/packages/maker-core/src/agents/codex/translator.ts
index 43bfa99625..82dd4cfc87 100644
--- a/packages/maker-core/src/agents/codex/translator.ts
+++ b/packages/maker-core/src/agents/codex/translator.ts
@@ -31,6 +31,7 @@ import type { AgentEvent, AgentTaskStatus, AgentTaskUpdateEventData } from '../.
import { normalizeAccountRateLimitSnapshot } from '../../types/account-rate-limits.js';
import type { AsyncQueue } from '../shared/async-queue.js';
import { stripTerminalControlSequences } from '../shared/terminal-output.js';
+import { parseReconnectAttemptMessage } from '../shared/network-error.js';
import { commandExecutionDisplayInput, type CommandExecutionDisplayInput } from './command-display.js';
import type {
ItemCompletedNotification,
@@ -253,6 +254,16 @@ export function translateErrorNotification(
const isAuthMissing = isAuthMissingErrorMessage(safeMessage, errorStatus);
if (params.willRetry && !isAuthMissing) {
ctx.log.warn('codex error (will retry)', { message: safeMessage, threadId: params.threadId, turnId: params.turnId });
+ // Codex 自带明确的有限重连进度时,每档都透出,让 UI 从 1/5 持续更新到 5/5。
+ // 这是非终止状态:turn 仍由 app-server 继续,不结束也不另起一次不安全的请求重放。
+ if (parseReconnectAttemptMessage(safeMessage)) {
+ queue.push({
+ type: 'error',
+ data: { ...safeErrorData, isTerminal: false, willRetry: true },
+ source: 'codex',
+ });
+ return;
+ }
// 持续重试的错误 = daemon 卡在 retry-loop 里 turn 无限转圈。同 turn 第 2 次时
// 透出**一条**非终止提示 (isTerminal:false, renderer 走 recoverableError →
// "正在自动重试…" banner, 恢复后随正常事件自动清; 不结束 turn、不落 error 行)。
diff --git a/packages/maker-core/src/agents/index.ts b/packages/maker-core/src/agents/index.ts
index 598f4d621b..eb4b97fb0b 100644
--- a/packages/maker-core/src/agents/index.ts
+++ b/packages/maker-core/src/agents/index.ts
@@ -21,6 +21,10 @@ export {
type ImageResizerConfig,
type ImageResizerLogger,
} from './shared/image-resizer.js';
+export {
+ parseReconnectAttemptMessage,
+ type ReconnectAttempt,
+} from './shared/network-error.js';
// host 侧会话移动(workingDir 变更)时迁移 CLI 转录,防 resume 报
// "No conversation found"(详见 claude-code/transcript-relocation.ts 注释)
export {
diff --git a/packages/maker-core/src/agents/shared/network-error.test.ts b/packages/maker-core/src/agents/shared/network-error.test.ts
index 6226fe1440..68e7169bf1 100644
--- a/packages/maker-core/src/agents/shared/network-error.test.ts
+++ b/packages/maker-core/src/agents/shared/network-error.test.ts
@@ -9,7 +9,10 @@
import { describe, it, expect } from 'vitest';
-import { isNetworkishErrorMessage } from './network-error.js';
+import {
+ isNetworkishErrorMessage,
+ parseReconnectAttemptMessage,
+} from './network-error.js';
describe('isNetworkishErrorMessage', () => {
it.each([
@@ -21,6 +24,8 @@ describe('isNetworkishErrorMessage', () => {
'connect ECONNREFUSED 127.0.0.1:3333',
'fetch failed',
'socket hang up',
+ 'Reconnecting... 2/5',
+ 'Reconnecting… 3/5 (stream disconnected before completion)',
])('matches networkish message: %s', (msg) => {
expect(isNetworkishErrorMessage(msg)).toBe(true);
});
@@ -35,3 +40,26 @@ describe('isNetworkishErrorMessage', () => {
expect(isNetworkishErrorMessage(msg)).toBe(false);
});
});
+
+describe('parseReconnectAttemptMessage', () => {
+ it('extracts Codex retry progress with or without a trailing stream error', () => {
+ expect(parseReconnectAttemptMessage('Reconnecting... 2/5')).toEqual({
+ attempt: 2,
+ maxAttempts: 5,
+ });
+ expect(
+ parseReconnectAttemptMessage(
+ 'Reconnecting... 5/100 (stream disconnected before completion)',
+ ),
+ ).toEqual({ attempt: 5, maxAttempts: 100 });
+ });
+
+ it.each([
+ 'Reconnecting...',
+ 'Reconnecting... 0/5',
+ 'Reconnecting... 6/5',
+ 'Connection error.',
+ ])('rejects malformed or unrelated message: %s', (msg) => {
+ expect(parseReconnectAttemptMessage(msg)).toBeNull();
+ });
+});
diff --git a/packages/maker-core/src/agents/shared/network-error.ts b/packages/maker-core/src/agents/shared/network-error.ts
index 3673a112b5..89ffcf8b3b 100644
--- a/packages/maker-core/src/agents/shared/network-error.ts
+++ b/packages/maker-core/src/agents/shared/network-error.ts
@@ -11,14 +11,44 @@
* 与 401 pattern 的两端一致性同款惯例),用于把原始英文报错换成友好文案。
* 修改 pattern 时两处同步。
*
- * pattern 说明:HTTP 网关侧 502/503/504(数字带词边界,避免误伤长数字)、
+ * pattern 说明:Codex stream retry 状态 `Reconnecting... N/M`、HTTP 网关侧
+ * 502/503/504(数字带词边界,避免误伤长数字)、
* 网关标准短语、Node 网络 errno(ECONNREFUSED 等)、undici/fetch 失败短语、
* AggregateError(Node 并发连接尝试全失败的聚合错误,几乎只出现在网络场景)、
* Anthropic SDK 的 APIConnectionTimeoutError / APIConnectionError 原文
* ("Request timed out" / "Connection error",SDK 重试耗尽后透传成终止型 turn error)。
*/
+export interface ReconnectAttempt {
+ attempt: number;
+ maxAttempts: number;
+}
+
+/**
+ * Codex 会把 streaming response 的有限重连进度放进 error notification.message:
+ * `Reconnecting... 2/5`(部分入口会在后面追加括号内的底层 stream error)。
+ * 返回结构化次数供 translator 持续更新非终止状态;普通业务文案不匹配。
+ */
+export function parseReconnectAttemptMessage(message: string): ReconnectAttempt | null {
+ const match = /\bReconnecting(?:\.{3}|…)\s*(\d+)\s*\/\s*(\d+)\b/i.exec(message);
+ if (!match) return null;
+ const attempt = Number(match[1]);
+ const maxAttempts = Number(match[2]);
+ if (
+ !Number.isSafeInteger(attempt) ||
+ !Number.isSafeInteger(maxAttempts) ||
+ attempt < 1 ||
+ maxAttempts < attempt
+ ) {
+ return null;
+ }
+ return { attempt, maxAttempts };
+}
+
export function isNetworkishErrorMessage(message: string): boolean {
- return /\b50[234]\b|Bad Gateway|Service Unavailable|Gateway Time-?out|upstream unreachable|ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOTFOUND|ENETUNREACH|EHOSTUNREACH|EPIPE|EAI_AGAIN|fetch failed|network error|socket hang up|AggregateError|Request timed out|Connection error/i.test(
- message,
+ return (
+ parseReconnectAttemptMessage(message) !== null ||
+ /\b50[234]\b|Bad Gateway|Service Unavailable|Gateway Time-?out|upstream unreachable|ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOTFOUND|ENETUNREACH|EHOSTUNREACH|EPIPE|EAI_AGAIN|fetch failed|network error|socket hang up|AggregateError|Request timed out|Connection error/i.test(
+ message,
+ )
);
}