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): 多图会话重连后不再因请求超限反复中断

Dashb59b31d7856d
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts
index 5bf95fa81a..0d05f49a7a 100644
--- a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts
@@ -151,6 +151,16 @@ vi.mock('@cindy/anthropic-compat-proxy', async (importOriginal) => {
};
});
+// Media-store persistence is covered by oversized-attachment-recovery.test.ts; keep the
+// real request rewrite and replace only where the preserved file is published.
+vi.mock('../oversized-attachment-recovery.js', async () => {
+ const { recoverInlineAttachments } = await vi.importActual<typeof import('@cindy/anthropic-compat-proxy')>('@cindy/anthropic-compat-proxy');
+ return {
+ createAttachmentRecovery: () => () => (body: Parameters<typeof recoverInlineAttachments>[0], target: number) =>
+ recoverInlineAttachments(body, target, { prepare: async () => '/tmp/preserved.png', commit: async () => {} }),
+ };
+});
+
vi.mock('@cindy/responses-chat-bridge', async (importOriginal) => ({
...await importOriginal<typeof import('@cindy/responses-chat-bridge')>(),
createResponsesChatHandler: mockState.createResponsesChatHandler,
@@ -2819,6 +2829,46 @@ describe('codex proxy host', () => {
expect(mockState.stripNonAnthropicFields).toHaveBeenCalledWith(body, { url: '/responses' });
});
+ // #7055: ChatGPT closes WebSocket messages over ~16 MiB with 1009. A reconnect resends the
+ // whole image-heavy history, so every retry was rejected until the turn timed out.
+ it('fits an oversized WebSocket request under the upstream message limit before forwarding', async () => {
+ const host = await freshCodexProxyHost();
+ mockState.createAnthropicCompatProxy.mockResolvedValueOnce({
+ url: 'http://127.0.0.1:43210',
+ dispose: vi.fn(async () => undefined),
+ });
+ await host.ensureCodexProxyReady();
+ const proxyOpts = mockState.createAnthropicCompatProxy.mock.calls[0][0] as {
+ webSocketTransforms: (ctx: { url: string; headers: Readonly<Record<string, string>> }) => { outbound: Transform };
+ };
+ const { createWebSocketMessageTransform } = await vi.importActual<typeof import('@cindy/anthropic-compat-proxy')>('@cindy/anthropic-compat-proxy');
+ const send = async (input: unknown[]): Promise<Buffer> => {
+ const payload = Buffer.from(JSON.stringify({ type: 'response.create', model: 'gpt-5.4', input }));
+ const header = Buffer.alloc(14);
+ header[0] = 129; header[1] = 128 | 127; header.writeBigUInt64BE(BigInt(payload.length), 2);
+ const { outbound } = proxyOpts.webSocketTransforms({ url: '/backend-api/codex/responses', headers: {} });
+ const forwarded: Buffer[] = [];
+ outbound.on('data', chunk => forwarded.push(chunk));
+ const ended = once(outbound, 'end');
+ outbound.end(Buffer.concat([header, payload])); // zero mask
+ await ended;
+ let message = Buffer.alloc(0);
+ const reader = createWebSocketMessageTransform(true, decoded => { message = decoded; return decoded; });
+ reader.resume(); const read = once(reader, 'end'); reader.end(Buffer.concat(forwarded)); await read;
+ return message;
+ };
+ const image = { type: 'input_image', image_url: `data:image/png;base64,${Buffer.alloc(3 << 20, 1).toString('base64')}` };
+
+ const ordinary = await send([image, image]);
+ expect(JSON.parse(ordinary.toString()).input).toEqual([image, image]);
+
+ const oversized = await send([image, image, image, image, image]);
+ expect(oversized.length).toBeLessThanOrEqual(12 << 20);
+ const input = JSON.parse(oversized.toString()).input;
+ expect(input[0]).toMatchObject({ type: 'input_text', text: expect.stringContaining('/tmp/preserved.png') });
+ expect(input.at(-1)).toEqual(image);
+ });
+
it('only resolves the websocket upstream for the oauth-bearer spawn identity', async () => {
const host = await freshCodexProxyHost();
mockState.createAnthropicCompatProxy.mockResolvedValueOnce({
diff --git a/apps/desktop/src/main/maker-host/codex-proxy-host.ts b/apps/desktop/src/main/maker-host/codex-proxy-host.ts
index 9e381fa57a..8b618bd7b1 100644
--- a/apps/desktop/src/main/maker-host/codex-proxy-host.ts
+++ b/apps/desktop/src/main/maker-host/codex-proxy-host.ts
@@ -48,6 +48,7 @@ import { isClaudeSubscriptionProviderId, isXaiSubscriptionProviderId } from './s
import {
createAnthropicCompatProxy,
+ recoverOversizedMessage,
createActiveStripTransform,
createEncryptedContentRecoveryRule,
createResponsesReasoningContentRecoveryRule,
@@ -383,6 +384,12 @@ function createArmedHttpRecoveryStripTransform(useUpstreamModel = false): Reques
// 缓冲 + JSON.parse,该值同时是单请求的内存 / 解析停顿预算)。
const CODEX_PROXY_MAX_REQUEST_BODY_BYTES = 128 * 1024 * 1024;
+// ChatGPT 订阅后端的 WebSocket 单条消息上限约 16 MiB(2026-10 实测:12 MiB 通过,16 MiB 起
+// 回 1009 Message Too Big;HTTP 无此限制)。连接回收后 Codex 要整段重发历史,图片多的会话会
+// 每次被拒、退到 HTTP 慢传。超过时先把最早的内联附件外置为本地文件,压到目标值再发。
+const CODEX_WEBSOCKET_MESSAGE_LIMIT_BYTES = 15 * 1024 * 1024;
+const CODEX_WEBSOCKET_MESSAGE_TARGET_BYTES = 12 * 1024 * 1024;
+
export type CodexProxyAuthInjection = 'oauth-bearer' | 'env-key' | 'provider-oauth';
// proxy 路线 spawn 鉴权模式: codex 当前带的是 OAuth token(requires_openai_auth)还是 gateway key(env_key)。
@@ -3447,6 +3454,30 @@ async function createCodexProxyHandle(
const decision = route(body, ctx);
return decision instanceof Promise ? decision.then(uncompressed) : uncompressed(decision);
};
+ const attachmentRecovery = createAttachmentRecovery(sessionIdFromHeaders);
+ const fitWebSocketRequest = async (
+ request: Buffer,
+ ctx: { url: string; headers: Readonly<Record<string, string>> },
+ signal: AbortSignal,
+ ): Promise<Buffer> => {
+ const recover = attachmentRecovery({ reqId: 0, method: 'POST', url: ctx.url, headers: ctx.headers });
+ let recovered: Buffer | null = null;
+ try {
+ recovered = recover
+ ? await recoverOversizedMessage(request, CODEX_WEBSOCKET_MESSAGE_TARGET_BYTES, body => recover(body, CODEX_WEBSOCKET_MESSAGE_TARGET_BYTES), signal)
+ : null;
+ } catch {
+ // Same as HTTP recovery: never log paths or payloads.
+ }
+ if (!recovered) {
+ log.warn('oversized websocket request forwarded unchanged', { bytes: request.length });
+ return request;
+ }
+ log.info('oversized websocket attachments preserved outside request', {
+ originalBytes: request.length, recoveredBytes: recovered.length,
+ });
+ return recovered;
+ };
const handle = await createAnthropicCompatProxy({
// 默认上游 = gateway(含 /v1);普通模型 + oauth 由 routingTransform 覆盖到 ChatGPT。
upstream: () => buildCodexGatewayBaseUrl(),
@@ -3477,11 +3508,12 @@ async function createCodexProxyHandle(
},
requestGuard: ctx => codexTextOnlyRequestGuard(isCodexTextOnly(selectedThreadIdFromHeaders(ctx.headers)), ctx, isChatGptUpstreamBase),
// Accepted WebSockets route exclusively to CODEX_OAUTH_UPSTREAM (see resolver below).
- webSocketTransforms: ctx => codexTextOnlyWebSocketTransforms(() => isCodexTextOnly(selectedThreadIdFromHeaders(ctx.headers)), true, message => {
+ webSocketTransforms: ctx => codexTextOnlyWebSocketTransforms(() => isCodexTextOnly(selectedThreadIdFromHeaders(ctx.headers)), true, (message, signal) => {
const body: unknown = JSON.parse(message.toString('utf8'));
const context = providerContextForRequest(ctx.headers, isPlainObject(body) && typeof body.model === 'string' ? body.model : '');
const next = restrictSubscriptionRequest(body, context.sessionId ?? guestSessionId, context.providerId ?? guestProviderId ?? 'openai');
- return next ? Buffer.from(JSON.stringify(next)) : message;
+ const request = next ? Buffer.from(JSON.stringify(next)) : message;
+ return request.length > CODEX_WEBSOCKET_MESSAGE_LIMIT_BYTES ? fitWebSocketRequest(request, ctx, signal) : request;
}),
transformResponse: (ctx) => {
const response = {
@@ -3523,7 +3555,7 @@ async function createCodexProxyHandle(
}),
),
maxRequestBodyBytes: CODEX_PROXY_MAX_REQUEST_BODY_BYTES,
- oversizedRequestRecovery: createAttachmentRecovery(sessionIdFromHeaders),
+ oversizedRequestRecovery: attachmentRecovery,
debugDumpRequestBody: process.env.XDT_PROXY_DUMP_REQUEST_BODY === '1',
recoveryRules: [...CODEX_BODY_RECOVERY_RULES],
logger: log,
diff --git a/apps/desktop/src/main/maker-host/codex-text-only-policy.ts b/apps/desktop/src/main/maker-host/codex-text-only-policy.ts
index f336074653..88481f781e 100644
--- a/apps/desktop/src/main/maker-host/codex-text-only-policy.ts
+++ b/apps/desktop/src/main/maker-host/codex-text-only-policy.ts
@@ -152,17 +152,21 @@ export function codexTextOnlyRequestGuard(
};
}
-export function codexTextOnlyWebSocketTransforms(disabled: () => boolean, requiresSerial = false, transformRequest: (message: Buffer) => Buffer = message => message) {
+export function codexTextOnlyWebSocketTransforms(
+ disabled: () => boolean,
+ requiresSerial = false,
+ transformRequest: (message: Buffer, signal: AbortSignal) => Buffer | Promise<Buffer> = message => message,
+) {
// Frozen at each request, never relaxed by a subsequent UI send or teardown.
let restricted = false;
let completed = true;
return {
- outbound: createWebSocketMessageTransform(true, message => {
+ outbound: createWebSocketMessageTransform(true, (message, signal) => {
const next = disabled();
if (restricted && !completed) reject();
restricted = next;
completed = false;
- return transformRequest(restricted ? restrictCodexRequest(message, { serial: requiresSerial }) : message);
+ return transformRequest(restricted ? restrictCodexRequest(message, { serial: requiresSerial }) : message, signal);
}),
inbound: createWebSocketMessageTransform(false, message => {
if (restricted) {
diff --git a/packages/anthropic-compat-proxy/src/index.ts b/packages/anthropic-compat-proxy/src/index.ts
index ab79dbb0a8..b71cde055f 100644
--- a/packages/anthropic-compat-proxy/src/index.ts
+++ b/packages/anthropic-compat-proxy/src/index.ts
@@ -14,7 +14,7 @@
*/
export { createAnthropicCompatProxy } from './server.js';
-export { recoverInlineAttachments } from './oversized-attachments.js';
+export { recoverInlineAttachments, recoverOversizedMessage } from './oversized-attachments.js';
export type { OversizedBody, RecoveredAttachment, AttachmentKeeper } from './oversized-attachments.js';
export type { OversizedRequestRecovery } from './types.js';
export {
diff --git a/packages/anthropic-compat-proxy/src/oversized-attachments.test.ts b/packages/anthropic-compat-proxy/src/oversized-attachments.test.ts
index ef6278ecf3..a68da0076e 100644
--- a/packages/anthropic-compat-proxy/src/oversized-attachments.test.ts
+++ b/packages/anthropic-compat-proxy/src/oversized-attachments.test.ts
@@ -4,7 +4,7 @@ import path from 'node:path';
import { Readable } from 'node:stream';
import type { IncomingMessage } from 'node:http';
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { collectRecoverableBody, recoverInlineAttachments as recover, type RecoveredAttachment } from './oversized-attachments.js';
+import { collectRecoverableBody, recoverInlineAttachments as recover, recoverOversizedMessage, type RecoveredAttachment } from './oversized-attachments.js';
const recoverInlineAttachments = (body: Parameters<typeof recover>[0], limit: number, prepare: (a: RecoveredAttachment) => Promise<string>) =>
recover(body, limit, { prepare, commit: async () => {} });
@@ -170,3 +170,22 @@ it('does not commit staged files when the recovered request still cannot fit', a
expect(await recover(f.body, 1000, { prepare: async () => '/tmp/kept', commit })).toBeNull();
expect(commit).not.toHaveBeenCalled();
});
+
+// #7055: a WebSocket request is a single in-memory message, not a request stream.
+it('recovers an in-memory message within the target, oldest attachment first, and drops its spool', async () => {
+ const message = Buffer.from(JSON.stringify({ input: [image(), image(), image()] }));
+ const target = message.length - 100_000;
+ let spooled = '';
+ const result = await recoverOversizedMessage(message, target, body => {
+ spooled = body.filePath;
+ return recoverInlineAttachments(body, target, async () => '/tmp/kept.png');
+ }, new AbortController().signal);
+ expect(result!.length).toBeLessThanOrEqual(target);
+ const input = JSON.parse(result!.toString()).input;
+ expect(input[0].type).toBe('input_text');
+ expect(input.slice(1)).toEqual([image(), image()]);
+ await expect(access(spooled)).rejects.toThrow();
+ const unfit = Buffer.from(JSON.stringify({ instructions: 'x'.repeat(100_000), input: [image()] }));
+ expect(await recoverOversizedMessage(unfit, 1000, body => recoverInlineAttachments(body, 1000, async () => '/tmp/kept.png'),
+ new AbortController().signal)).toBeNull();
+});
diff --git a/packages/anthropic-compat-proxy/src/oversized-attachments.ts b/packages/anthropic-compat-proxy/src/oversized-attachments.ts
index 7fdab6bc42..40b3906fda 100644
--- a/packages/anthropic-compat-proxy/src/oversized-attachments.ts
+++ b/packages/anthropic-compat-proxy/src/oversized-attachments.ts
@@ -1,6 +1,6 @@
import { randomUUID } from 'node:crypto';
import { createReadStream } from 'node:fs';
-import { mkdtemp, open, rm, statfs, type FileHandle } from 'node:fs/promises';
+import { mkdtemp, open, rm, statfs, writeFile, type FileHandle } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import type { Readable } from 'node:stream';
@@ -101,6 +101,40 @@ export async function collectRecoverableBody(
}
}
+/**
+ * The in-memory counterpart of collectRecoverableBody for one complete message
+ * (a WebSocket request): spool it, then run the same overflow-only recovery.
+ * Returns null when recovery cannot bring the message within targetBytes.
+ */
+export async function recoverOversizedMessage(
+ message: Buffer,
+ targetBytes: number,
+ recover: (body: OversizedBody) => Promise<Buffer | null>,
+ signal: AbortSignal,
+): Promise<Buffer | null> {
+ let reserved = 0;
+ let directory: string | undefined;
+ try {
+ const required = message.length * 4;
+ const allocationUnit = await reserveDisk(required);
+ reserved += required;
+ directory = await mkdtemp(path.join(tmpdir(), 'cindy-request-'));
+ const filePath = path.join(directory, 'body.json');
+ await writeFile(filePath, message, { flag: 'wx', mode: 0o600 });
+ signal.throwIfAborted();
+ const result = await recover({ filePath, bytes: message.length, signal, reserveAttachment: async () => {
+ const overhead = allocationUnit * 2;
+ await reserveDisk(overhead);
+ reserved += overhead;
+ } });
+ signal.throwIfAborted();
+ return result && result.length <= targetBytes ? result : null;
+ } finally {
+ try { if (directory) await rm(directory, { recursive: true, force: true }); }
+ finally { reservedDiskBytes -= reserved; }
+ }
+}
+
interface StringPart { path: string; start: number; bytes: number; prefix: string }
interface TokenizedBody { json: string; parts: Map<string, StringPart> }
const STRING_MEMORY_BYTES = 64 * 1024;
diff --git a/packages/anthropic-compat-proxy/src/websocket-message-transform.test.ts b/packages/anthropic-compat-proxy/src/websocket-message-transform.test.ts
index 149f04ccb2..65d5485124 100644
--- a/packages/anthropic-compat-proxy/src/websocket-message-transform.test.ts
+++ b/packages/anthropic-compat-proxy/src/websocket-message-transform.test.ts
@@ -62,3 +62,26 @@ it('does not forward a partial message if the connection closes before FIN', asy
const failed = once(transform, 'error'); transform.end(frame(Buffer.from('partial'), true, 1, false)); await failed;
expect(output).toEqual([]);
});
+
+it('holds later frames behind an async rewrite so message order is preserved', async () => {
+ let release!: () => void;
+ const gate = new Promise<void>(resolve => { release = resolve; });
+ const writer = createWebSocketMessageTransform(true, async message => {
+ if (message.toString() !== 'slow') return message;
+ await gate;
+ return Buffer.from('rewritten');
+ });
+ const rewritten: Buffer[] = [];
+ writer.on('data', chunk => rewritten.push(chunk));
+ const ended = once(writer, 'end');
+ writer.write(frame(Buffer.from('slow'), true));
+ writer.write(frame(Buffer.from('ping'), true, 9));
+ writer.end(frame(Buffer.from('next'), true));
+ await new Promise(resolve => setImmediate(resolve));
+ expect(rewritten).toEqual([]);
+ release(); await ended;
+ const messages: string[] = [];
+ const reader = createWebSocketMessageTransform(true, message => { messages.push(message.toString()); return message; });
+ reader.resume(); const readEnd = once(reader, 'end'); reader.end(Buffer.concat(rewritten)); await readEnd;
+ expect(messages).toEqual(['rewritten', 'next']);
+});
diff --git a/packages/anthropic-compat-proxy/src/websocket-message-transform.ts b/packages/anthropic-compat-proxy/src/websocket-message-transform.ts
index 9265692a97..3a499537e3 100644
--- a/packages/anthropic-compat-proxy/src/websocket-message-transform.ts
+++ b/packages/anthropic-compat-proxy/src/websocket-message-transform.ts
@@ -1,12 +1,17 @@
import { randomBytes } from 'node:crypto';
import { Transform, type TransformCallback } from 'node:stream';
-/** Opt-in RFC6455 message filter. Negotiation must exclude compression/extensions. */
+/**
+ * Opt-in RFC6455 message filter. Negotiation must exclude compression/extensions.
+ * An async filter holds back later frames until it settles, so message order is kept;
+ * its signal aborts when the stream is destroyed.
+ */
export function createWebSocketMessageTransform(
masked: boolean,
- filter: (message: Buffer) => Buffer,
+ filter: (message: Buffer, signal: AbortSignal) => Buffer | Promise<Buffer>,
maxBytes = 128 * 1024 * 1024,
): Transform {
+ const abort = new AbortController();
// Queue incoming chunks: a large frame arriving in small packets must not
// repeatedly copy its entire accumulated prefix (quadratic in frame size).
let chunks: Array<Buffer | undefined> = [];
@@ -43,7 +48,7 @@ export function createWebSocketMessageTransform(
let opcode = 0;
return new Transform({
transform(chunk: Buffer, _encoding, callback: TransformCallback) {
- try {
+ void (async () => {
if (chunk.length) { chunks.push(chunk); buffered += chunk.length; }
while (buffered >= 2) {
const prefix = peek(Math.min(buffered, 10));
@@ -80,7 +85,8 @@ export function createWebSocketMessageTransform(
fragments.push(payload); originalFrames.push(frame); size += length;
if (!fin) continue;
const message = fragments.length === 1 ? fragments[0]! : Buffer.concat(fragments, size);
- const filtered = filter(message);
+ const result = filter(message, abort.signal);
+ const filtered = Buffer.isBuffer(result) ? result : await result;
if (filtered.length > maxBytes) throw new Error('Websocket message too large');
if (filtered === message) for (const original of originalFrames) this.push(original);
else {
@@ -99,8 +105,11 @@ export function createWebSocketMessageTransform(
}
fragments = []; originalFrames = []; size = 0; opcode = 0;
}
- callback();
- } catch (error) { callback(error as Error); }
+ })().then(() => callback(), (error: unknown) => callback(error as Error));
+ },
+ destroy(error, callback) {
+ abort.abort();
+ callback(error);
},
flush(callback) {
callback(buffered || opcode ? new Error('Incomplete websocket message') : undefined);
diff --git a/packages/maker-core/src/agents/codex/app-server/host.ts b/packages/maker-core/src/agents/codex/app-server/host.ts
index 8d1faa9954..403349c0b9 100644
--- a/packages/maker-core/src/agents/codex/app-server/host.ts
+++ b/packages/maker-core/src/agents/codex/app-server/host.ts
@@ -72,6 +72,7 @@ import {
type ItemGuardianApprovalReviewStartedNotification,
type ItemGuardianApprovalReviewCompletedNotification,
type GuardianWarningNotification,
+ type WarningNotification,
} from './protocol.js';
/**
@@ -103,6 +104,7 @@ const SUBSCRIBED_METHODS = [
'item/autoApprovalReview/started',
'item/autoApprovalReview/completed',
'guardianWarning',
+ 'warning', // thread 级提示 (如 WebSocket 回退到 HTTPS)
'error',
] as const;
@@ -185,6 +187,7 @@ export interface ThreadEventHandlers {
autoApprovalReviewStarted?: (params: ItemGuardianApprovalReviewStartedNotification) => void;
autoApprovalReviewCompleted?: (params: ItemGuardianApprovalReviewCompletedNotification) => void;
guardianWarning?: (params: GuardianWarningNotification) => void;
+ warning?: (params: WarningNotification['params']) => void;
error?: (params: ErrorNotification['params']) => void;
/**
* Host 被永久替换(强制退役,如账号切换 / auth 失效)时发给每个订阅者的结构化
@@ -1257,6 +1260,8 @@ export class AppServerHost {
}
return;
}
+ // Process-level warnings (config / feature notices) have no thread to route to.
+ if (method === 'warning') return;
this.logger.warn('notification missing threadId', { method });
return;
}
@@ -1677,6 +1682,7 @@ export class AppServerHost {
case 'item/autoApprovalReview/started': fn = handlers.autoApprovalReviewStarted as (p: never) => void; break;
case 'item/autoApprovalReview/completed': fn = handlers.autoApprovalReviewCompleted as (p: never) => void; break;
case 'guardianWarning': fn = handlers.guardianWarning as (p: never) => void; break;
+ case 'warning': fn = handlers.warning as (p: never) => void; break;
case 'error': fn = handlers.error as (p: never) => void; break;
}
if (!fn) {
diff --git a/packages/maker-core/src/agents/codex/app-server/protocol.ts b/packages/maker-core/src/agents/codex/app-server/protocol.ts
index 598ad10bf2..17d2c31d07 100644
--- a/packages/maker-core/src/agents/codex/app-server/protocol.ts
+++ b/packages/maker-core/src/agents/codex/app-server/protocol.ts
@@ -1182,6 +1182,12 @@ export interface GuardianWarningServerNotification {
params: GuardianWarningNotification;
}
+/** User-facing warning (v2 WarningNotification); threadId is set when it targets a thread. */
+export interface WarningNotification {
+ method: 'warning';
+ params: { message: string; threadId?: string | null };
+}
+
/**
* v2 ThreadItem 的 envelope — 至少有 id / type, 余字段按 type narrow。
* 完整 union 在 v2.rs ThreadItem (太大, 不在 Phase 1 全列)。translator 用
@@ -1213,6 +1219,7 @@ export type ServerNotification =
| ItemGuardianApprovalReviewStartedServerNotification
| ItemGuardianApprovalReviewCompletedServerNotification
| GuardianWarningServerNotification
+ | WarningNotification
| ErrorNotification;
// ── 方法名常量 (避免 string typo) ────────────────────────────────────────────
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index c66d0a11fb..5074a4d88f 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -31842,6 +31842,33 @@ describe('CodexAgent reconnect-stall watchdog', () => {
}
});
+ // #7055: after WebSocket retries Codex uploads the full history over HTTPS and emits
+ // nothing until the upload ends; on a slow link that exceeds the reconnect deadline.
+ it('HTTPS 回退开始后不再按重连 deadline 中断正在上传的请求', async () => {
+ vi.useFakeTimers();
+ try {
+ const agent = new CodexAgent(createDeps());
+ const { host, handle, handlers, seen } = await startReconnectTurn(agent, 'session-https-fallback');
+ emitReconnect(handlers, 1);
+ handlers.warning?.({
+ threadId: 'start-thread-id',
+ message: 'Falling back from WebSockets to HTTPS transport. stream disconnected before completion: ' +
+ 'websocket closed by server before response.completed',
+ });
+
+ await vi.advanceTimersByTimeAsync(RECONNECT_STALL_MS + 1);
+
+ expect(seen).not.toContainEqual(expect.objectContaining({
+ type: 'error', data: expect.objectContaining({ reason: 'codex_reconnect_stalled' }),
+ }));
+ expect(handle.isTurnRunning?.()).toBe(true);
+ expect(host.request.mock.calls.map(([method]) => method)).not.toContain(Method.TurnInterrupt);
+ await handle.close();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it.each([
{ cancelled: false, completion: undefined, rejectAck: false },
{ cancelled: true, completion: undefined, rejectAck: false },
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index 11d1eea36d..b91bd91e7e 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -1264,6 +1264,13 @@ const CODEX_UPSTREAM_IDLE_SUSPEND_GAP_MS = 30_000;
*/
const CODEX_RECONNECT_STALL_TIMEOUT_MS = RETRY_ESCALATION_MAX_ELAPSED_MS;
+/**
+ * WebSocket 重试用尽后 Codex 改走 HTTPS 时推的 `warning`。之后要先上传完整历史才有事件,
+ * 慢网下可达数分钟,不再属于重连序列:清掉重连 deadline,由 Codex 自身 HTTP 超时与
+ * upstream-idle 看门狗兜底。
+ */
+const CODEX_HTTPS_FALLBACK_WARNING_PREFIX = 'Falling back from WebSockets to HTTPS transport';
+
/** 只含空白、格式字符或控制字符的 text delta 不算重连已经恢复。 */
const CODEX_INVISIBLE_TEXT_PATTERN = /[\s\p{Cf}\p{Cc}]/gu;
@@ -8923,7 +8930,7 @@ assertRouteCurrent();
const stalledTurnGeneration = reconnectStallTurnGeneration;
const allowPendingTurnStart = !isTurnInFlight;
const stalledMessage =
- `Codex app-server has been reconnecting for ${Math.round(CODEX_RECONNECT_STALL_TIMEOUT_MS / 1000)}s ` +
+ `The model connection has been retrying for ${Math.round(CODEX_RECONNECT_STALL_TIMEOUT_MS / 1000)}s ` +
'without making progress; the turn was interrupted automatically. ' +
'You can send the next message to continue.';
const emitStalled = (reason: string, message: string): void => {
@@ -12900,6 +12907,12 @@ assertRouteCurrent();
// warning for diagnostics to avoid rendering a duplicate error card.
log.warn('Codex Guardian warning', { threadId: params.threadId, message: params.message });
},
+ warning: (params) => {
+ if (params.message.startsWith(CODEX_HTTPS_FALLBACK_WARNING_PREFIX)) {
+ log.info('codex fell back to HTTPS transport; reconnect deadline cleared', { threadId });
+ clearReconnectStall();
+ }
+ },
error: (params) => {
// buffered turn 的 error (含终态) 同样进队列等对账 (greptile R11 P1 +
// codex R12 P1): 合法 → 激活后重放走正常终端路径收口 send; 孤儿 →