[Bug] Codex 官方模型经 Magpie 返回 502:WebSocket 收到 StatusMessageTooBig 关闭帧
现象
macOS 上,Codex 经 Magpie 使用官方模型 gpt-5.6-luna 时出现以下错误:
unexpected status 502 Bad Gateway: OpenAI can't be reached (Post "https://chatgpt.com/backend-api/codex/responses": codex websocket: failed to get reader: received close frame: status = StatusMessageTooBig and reason = ""). gpt-5.6-luna is one of Codex's own models, which goes to OpenAI with Codex's own sign-in: pick one of magpie's models in Codex (provider/model, or set it in magpie's Agents view), or let Codex reach OpenAI, url: http://127.0.0.1:3425/backend-api/codex/responses
已核实环境
- 本机检查时 Magpie 版本:
0.1.1364,系统为 macOS。 - Codex 配置:
openai_base_url = "http://127.0.0.1:3425/backend-api/codex"。 - Magpie 正在监听 3425;
GET /v1/models正常,包含codex/gpt-5.6-luna。模型列表正常不代表推理调用成功。
尚未确认
未记录触发请求大小、聊天长度及附件情况;尚无稳定最小复现,也未完成空白短会话、绕过 Magpie 直连或 HTTP/SSE 对照。不能确定触发的是哪一端大小限制,暂不归因为上下文超限或 Magpie 缺陷。
希望协助
请确认 StatusMessageTooBig 的来源,检查是否存在已知的 WebSocket 大消息处理问题,并提供适用的修复版本或规避方式。如需补充日志,请指出必要的脱敏字段。
检索到 #2332、#3135、#3377,但它们的错误形式不同,暂不能视为同一问题。
补充一个已完成的合成数据对照复现:相同像素、相同图片尺寸、相同模型,仅增加 PNG 的无意义 ancillary 元数据,就能重复触发本 issue 的 502 / StatusMessageTooBig。 不需要长会话或真实文档。
本次测试环境
- Magpie CLI 报告版本:
0.1.1349(与 issue 正文的报告环境独立)。 - Codex CLI:
0.164.0;macOS:27.0.1,Apple Silicon。 - 模型:
gpt-6-astra,探针使用reasoning.effort=low。 - 入口:
POST http://127.0.0.1:3425/backend-api/codex/responses,本机已有 ChatGPT 登录。 - 日期:2026-10-24。没有改动网关配置、重启 Magpie,也没有提交真实图片或会话原文。
实测对照
每个请求都独立包含一张 64×64 RGB 合成 PNG 和一句“Reply OK”,stream=true, store=false,没有历史或工具。大图增加 13 MiB 的合法私有 ancillary PNG chunk,像素不变。
两种 PNG 均用 Pillow 完整解码验证,尺寸均为 64×64,解码后像素 SHA-256 完全相同:
8d70651877bd728ff25aa4d4d20ae3d3467e8f47c4d519ccfa240144781bf87d。
| 测试 | PNG 字节数 | 发送给 Magpie 的 JSON 字节数 | 结果 | 耗时 |
|---|---|---|---|---|
| 小请求 1 | 179 | 566 | 200,response.completed | 3.16 s |
| 大请求 1 | 13,631,679 | 18,175,898 | 502,StatusMessageTooBig | 0.905 s |
| 大请求 2 | 13,631,679 | 18,175,898 | 502,StatusMessageTooBig | 1.329 s |
| 小请求 2 | 179 | 566 | 200,response.completed | 2.247 s |
两个大请求均命中下面相同的错误链;没有 Unauthorized 或 usage_limit_reached。小请求在大请求实验前后均成功。
502 Bad Gateway
OpenAI can't be reached
codex websocket: failed to get reader: received close frame:
status = StatusMessageTooBig and reason = ""
这验证了本机经 Magpie 的路径上存在可重复的编码体积相关失败。它没有定位具体哪台远端组件设置了限制,也没有测出精确阈值;18,175,898 是发送给 Magpie 的 JSON 字节数,不是抓包测得的上游 WebSocket 最终消息长度。
用户侧影响
实际工作中,新会话在一轮页面核验里累计查看 15 张次 PNG 后发生同一错误;本地会话记录内图片 data URL 合计约 20.74 MB(这同样不是请求抓包大小)。对该会话尝试 /compact 时,也再次显示同样错误并重连,已中止重试。因此“新开会话”或“出错后再压缩”并不能单独防止重演。
源码定位与建议(尚未提交或验证修复)
核对了公开源码提交 dd1e8822d916;这是当前公开源码的分析,不声称它与本机安装版本逐字一致:
internal/gateway/codex_socket.go:Magpie 会把客户端的流式 HTTP 请求转换为上游 WebSocket。RoundTrip只在收到errCodexSocketFallBack时回退 HTTP;发送后/prelude 读取到 close 1009 的错误会直接返回,没有对应的大小错误分类或恢复分支。internal/gateway/codex_backend.go:该错误最终被包装为 “OpenAI can't be reached” 和切换模型/检查连接的提示,容易让用户误判为网络或账号问题。
希望考虑:
- 对最终未压缩消息做发送前字节检查,并明确说明这是消息大小问题;不要用 token 估算替代传输字节预算。
- 单独识别
websocket.StatusMessageTooBig,避免把确定性的大小失败作为普通连接错误不断重试。 - 对尚未收到任何响应事件的请求,评估有界的 HTTP/SSE 回退;需要另行验证大请求是否能走通该路径,不能假定 HTTP 必然成功,也不应在流已开始后盲目重放。
- 加回归测试:小/大编码请求对照、pre-response close 1009、错误信息和重试次数。若加入图片压缩策略,应明确质量影响,并保留原始用户文件。
相关上游报告:openai/codex#55317。这里只将其作为相关线索;本评论的数据来自上述独立实测,没有据此声称所有环境都有固定 16 MiB 上限。
最小探针
下面是本次实际运行的脚本(只使用 Python 标准库)。它读取本机已有的 Codex 登录,凭据仅在进程内使用,不输出、不写进结果文件;只发送合成图片。会产生真实模型请求,请在自己的测试账号/环境运行。
python3 synthetic_probe.py --output small-1.json
python3 synthetic_probe.py --padding-mib 13 --output large-1.json
python3 synthetic_probe.py --padding-mib 13 --output large-2.json
python3 synthetic_probe.py --output small-2.json
synthetic_probe.py
#!/usr/bin/env python3
"""Opt-in synthetic inference probe through the user's existing Magpie gateway.
Only synthetic pixels/metadata are transmitted. Auth stays in process memory.
Results omit tokens, account identifiers, and response headers. No config edits.
"""
import argparse
import base64
import hashlib
import http.client
import json
import struct
import time
import zlib
from pathlib import Path
def chunk(kind, data):
return struct.pack('!I', len(data)) + kind + data + struct.pack('!I', zlib.crc32(kind + data) & 0xffffffff)
def png(padding):
# Same 64x64 RGB pixels; npAD is a valid ancillary, private PNG chunk.
header = struct.pack('!2I5B', 64, 64, 8, 2, 0, 0, 0)
pixels = (b'\x00' + bytes([70, 120, 180]) * 64) * 64
return (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', header)
+ chunk(b'IDAT', zlib.compress(pixels))
+ (chunk(b'npAD', b'\x00' * padding) if padding else b'') + chunk(b'IEND', b''))
def probe(model, padding, auth, timeout):
image = png(padding)
body = json.dumps({
'model': model, 'instructions': 'Reply with only OK. Do not use tools.',
'input': [{'role': 'user', 'content': [
{'type': 'input_text', 'text': 'This is a synthetic transport test. Reply OK.'},
{'type': 'input_image', 'image_url': 'data:image/png;base64,' + base64.b64encode(image).decode(), 'detail': 'high'}]}],
'reasoning': {'effort': 'low'}, 'stream': True, 'store': False,
}, separators=(',', ':')).encode()
headers = {'Content-Type': 'application/json', 'Accept': 'text/event-stream',
'Authorization': 'Bearer ' + auth['access_token'],
'ChatGPT-Account-Id': auth['account_id'], 'Originator': 'codex_cli_rs',
'User-Agent': 'codex_cli_rs/0.164.0'}
conn = http.client.HTTPConnection('127.0.0.1', 3425, timeout=timeout)
start = time.monotonic()
result = {'model': model, 'padding_bytes': padding, 'png_bytes': len(image),
'json_request_bytes': len(body), 'png_sha256': hashlib.sha256(image).hexdigest()}
try:
conn.request('POST', '/backend-api/codex/responses', body, headers)
response = conn.getresponse()
result['http_status'] = response.status
if response.status != 200:
# Only publish the known error classifier, never arbitrary server data.
error = response.read(32768).decode('utf-8', 'replace')
result['error_flags'] = {key: key in error for key in [
'StatusMessageTooBig', 'codex websocket', 'OpenAI can\'t be reached',
'Unauthorized', 'usage_limit_reached']}
else:
events = []
while time.monotonic() - start < timeout:
line = response.readline()
if not line:
break
if not line.startswith(b'data: '):
continue
try:
event = json.loads(line[6:])
except (ValueError, TypeError):
continue
kind = event.get('type')
if kind in ['response.created', 'response.completed', 'response.failed', 'error']:
events.append(kind)
if kind in ['response.completed', 'response.failed', 'error']:
break
result['terminal_events'] = events
except Exception as error:
result['exception_class'] = type(error).__name__
finally:
conn.close()
result['elapsed_seconds'] = round(time.monotonic() - start, 3)
return result
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--model', default='gpt-6-astra')
parser.add_argument('--padding-mib', type=int, default=0)
parser.add_argument('--timeout', type=int, default=45)
parser.add_argument('--output', type=Path, required=True)
args = parser.parse_args()
auth = json.loads((Path.home() / '.codex/auth.json').read_text())['tokens']
result = probe(args.model, args.padding_mib * 1024 * 1024, auth, args.timeout)
text = json.dumps(result, indent=2)
args.output.write_text(text + '\n')
print(text)
if __name__ == '__main__':
main()
报告由 Codex 协助整理;上面的状态码、完成事件、字节数和耗时均为实际运行结果。未完成绕过 Magpie 的直连 HTTP/SSE 对照,未对本机网关打补丁。
补充本轮新的关键对照:同一个 gpt-6.1-sol、同一现有登录、完全相同的大请求,Magpie 返回 502/1009,官方 HTTP/SSE 正常完成;安装的 Codex 原生客户端还能自动回退 HTTP 完成大图请求。
这补齐了上一条评论中“尚未做官方 HTTP/SSE 对照”的缺口。本次全部为合成图片,没有提交真实会话、工作文件或截图,也未修改运行配置、重启网关。
环境与对照结果
- macOS / Apple Silicon
- Magpie 0.1.1364;本次查询 latest release 也是 v0.1.1364。
- Codex CLI 0.164.0;模型 gpt-6.1-sol,
reasoning.effort=low。 - Magpie 入口:
POST http://127.0.0.1:3425/backend-api/codex/responses。 - 官方 HTTP 入口:
POST https://chatgpt.com/backend-api/codex/responses。 - 两组使用同一请求体、同一认证、同一网络环境;
stream=true, store=false,无历史、无工具。
图片均为 64×64 RGB PNG;大图仅加入 13 MiB 合法的私有 ancillary chunk,像素数据不变。
| 请求 | JSON 字节数 | 经 Magpie | 官方 HTTP/SSE |
|---|---|---|---|
| 小图,PNG 179 B | 567 | HTTP 200,response.completed,OK;2.082 s | HTTP 200,response.completed,OK;1.844 s |
| 大图,PNG 13,631,679 B | 18,175,899 | HTTP 502,StatusMessageTooBig;0.915 s | HTTP 200,response.completed,OK;7.509 s |
两组大请求原始 JSON 的 SHA-256 相同:
e7d902505eb3ee54d1fc5b18c4685ba6970deeb5a4c87a4deec2ab86b5470bd8。
Magpie 大请求错误同时含 codex websocket、StatusMessageTooBig 和 OpenAI can't be reached;没有 Unauthorized / usage_limit_reached。
Codex 原生客户端的进一步验证
用临时 -c 'openai_base_url="https://chatgpt.com/backend-api/codex"' 绕过 Magpie,保留内置 OpenAI provider、现有 ChatGPT 登录、同一模型和默认传输策略,运行 ephemeral、read-only 的合成大图请求。没有改动持久配置。
codex debug prompt-input保留的图片 data URL 为 18,175,594 字节,渲染的提示 JSON 为 18,317,128 字节。因此不是客户端先缩小图片后才通过。- 执行出现 4 条错误事件;日志含
falling back to HTTP。 - 随后返回预期文本
NATIVE_LARGE_OK,turn.completed,进程退出码 0,工具调用 0,耗时 26.429 s。 - 原生短请求也完成,退出码 0。
上述 JSON/提示大小不是上游 WebSocket 抓包大小;没有测量精确限制,也不声称所有环境都有固定 16 MiB 阈值。原始故障会话的最终请求没有抓包,此处是独立合成复现。
源码与建议
核对 v0.1.1364 对应的固定提交 dd1e8822d916:
- codex_socket.go L97–110 仅在返回
errCodexSocketFallBack时走 HTTP。 - L260 已明确
c.SetReadLimit(-1),不应解释成本地 WebSocket 默认 32 KB 读取限制。 - L280–291 在响应前读取 close 1009 后直接返回错误;未分类为上述 HTTP 回退。
- codex_backend.go L1536 随后附上“选择 Magpie 模型/让 Codex 连接 OpenAI”的通用文案。短请求同模型成功且官方大请求成功,说明这段文案容易把大小相关失败误导成模型或鉴权配置错误。
希望优先考虑:
- 对尚未收到任何响应事件的 close 1009 做准确分类,并评估一次有界的 HTTP/SSE 回退;本轮实测表明该路径对这份大请求可用。
- 已开始返回模型或工具事件的流不应盲目重放;回退失败应保留真实错误,不形成无限重试。
- 明确显示“上游 WebSocket 消息大小相关失败”及是否已回退,避免只有通用网络/模型提示。
- 回归测试覆盖:小/大编码请求对照、response 前 close 1009、一次成功回退、回退失败次数有界、已开始流时不重放。
复现方式
可复用上一条评论的 synthetic_probe.py,模型改为 --model gpt-6.1-sol,先跑小图与 --padding-mib 13。官方 HTTP 对照只将连接改为:
conn = http.client.HTTPSConnection("chatgpt.com", timeout=45)
路径、请求体和认证头保持相同。建议分别保存 HTTP 状态、response.completed、JSON 字节数和请求 SHA-256;不要输出认证信息。
此补充由 Codex 协助整理;表格中的状态、字节数、完成事件和耗时来自本轮实际执行。目前没有替换本机 Magpie 二进制或验证修复版本。
Taking this. Direction to verify first: the 502 body — Post "https://chatgpt.com/backend-api/codex/responses": codex websocket: ... StatusMessageTooBig — reads as magpie's own upstream fetch failing over a WebSocket transport, which matches your A/B (the same large request completes over official HTTP/SSE, and a native Codex client falls back). Will locate that ws round-trip and its message-size ceiling, then either fragment/raise it or fall back to HTTP/SSE; patch to follow on my fork.
StatusMessageTooBig 的来源确认了:是 chatgpt.com 后端 WebSocket 的单条消息大小上限。修复分支:https://github.com/skygunner/magpie/tree/fix/issue-batch-1024pm(commit b834f286,基于 main dd1e8822)。
链路:0.1.1349 起(a2e98cd7,修 #3377 那道 121 秒墙)magpie 把流式 Codex 轮次作为一条 response.create 帧发进后端的 WebSocket。@xiaoan17 的对照复现说得很清楚:像素相同、仅 PNG 无关元数据把请求撑到 18 MB 时,后端收完消息就以 1009(StatusMessageTooBig)关闭帧回绝;566 字节的同一张图正常。这是「一条帧太大」,与上下文长度无关。magpie 之前把这个关闭帧原样变成 502 死路,重试也只能重撞。
修复:发送消息时、或回包首帧到来前收到 StatusMessageTooBig 关闭帧的,这一轮改走 HTTP(该路径没有单帧上限,也是 WebSocket 之前的老路径),并且不把主机拉黑——小的轮次继续走 WebSocket。测试用一个假 ws 后端先复现了你的 502 原文(旧代码红),修复后同一轮从 HTTP 完整回来;连续两轮都是先试 WebSocket 再回退,证明没有误拉黑(TestCodexSocketMessageTooBigGoesOverHTTP)。
边界:如果 HTTP 也扛不住这么大的请求体(#3441 那类 16 MB 上传本来就又慢又易断),仍会失败——那属于另一层的问题;这一层的确定性 502 已消除。真实 ChatGPT 后端未调用,麻烦在你的环境用带长图历史的会话验证一轮。
The leg that fails is magpie's own to chatgpt.com. Since a2e98cd7 a streamed Codex turn goes to the backend over its WebSocket (internal/gateway/codex_socket.go), as Codex's own client sends it — the client-facing route stays HTTP. The ceiling is not magpie's: the socket's read limit is off (c.SetReadLimit(-1)) and the write side has none, so the StatusMessageTooBig close frame is the backend's answer to a turn message over what its socket takes. Your A/B is exactly that: the same 18.2 MB request that dies on the socket clears over the HTTP route, and the native client's log names the same remedy (falling back to HTTP).
Until now that close frame was fatal. It arrives while the transport reads ahead for the reply's head, and the error — codex websocket: failed to get reader: received close frame: status = StatusMessageTooBig — was not the kind of failure the socket retries over HTTP (errCodexSocketFallBack): it fell through to the gateway's "OpenAI can't be reached" 502, which reads as a network or sign-in fault. The fix reads the frame for what it is: a close StatusMessageTooBig before the reply began means the backend took nothing of the turn, so the turn goes over HTTP as it was — the fallback a refused handshake already takes. The host is not shunned for it (a message size is not the host refusing sockets), so the next, small turn is on the socket again. A close after the reply began stays a cut stream, as before — nothing replays once events have gone out.
Independent work, same fix: skygunner's patch posted above (b834f286, first) classifies the frame the same way and stands as the earlier one; the patch below is my own take, kept as a second, independent one for the maintainer to pick from. The deltas: theirs also guards the socket's write leg, which the library's writer cannot see a close frame on (the frame arrives on the read-ahead leg, in both); their test has the fake refuse every message, so it proves two consecutive fallbacks, mine refuses only big ones, so it also pins a small turn going whole over the socket right after a big one was refused — either stands.
What changed
internal/gateway/codex_socket.go(+7): in the prelude read for the reply's head, a close frame withwebsocket.StatusMessageTooBigreturnserrCodexSocketFallBack, the fallback the RoundTrip already takes for a refused handshake. No setting, no shun, no retry loop.internal/gateway/codex_socket_test.go(+37): the fake backend learnstooBig— which turns it answers with a closeStatusMessageTooBiginstead of a reply — andTestCodexSocketTooBigGoesOverHTTPpins the behavior: a turn whose message is over 1 MiB is answered over HTTP after its socket try (200, the SSE events, noMessageTooBigreaching Codex), and the next, small turn is on the socket again (1 HTTP post, 2 sockets).
Verification
(darwin/arm64, Go 1.26, base dd1e8822 + the commit below)
| Check | Result |
|---|---|
RED, product hunk reverted (test kept), fake backend closes the socket with StatusMessageTooBig after a >1 MiB turn message |
FAIL: the big turn: 502 ... OpenAI can't be reached (Post ...: codex websocket: failed to get reader: received close frame: status = StatusMessageTooBig and reason = "") — the reported signature |
| GREEN, fix in | pass: the big turn over HTTP (200, the SSE events, no MessageTooBig in the reply), then the small turn whole over the socket — 1 post, 2 sockets |
| ablation on the committed tree (revert: red again; restore: green) | red and green as above; working tree clean after |
go test -tags nogui ./internal/gateway/ (whole package) |
ok 357.6s |
go test -tags nogui -race over the six codex-socket tests |
pass (2.4s) |
gofmt -l on the two touched files |
clean |
go vet -tags nogui ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./... |
pass (darwin vet prints a pre-existing cgo -Wenum-conversion warning in internal/gui/trayimage_darwin.go, untouched here, exit 0) |
go build, GOOS=linux go build -tags nogui, GOOS=windows go build |
pass |
Not verified
- The backend's exact socket ceiling: not probed live (no real ChatGPT calls from here). The fake keys the close to a 1 MiB turn message — the frame is what the fix reads, not any threshold; your probes put the real one between 13 and 18 MB and the reported session hit it there.
- A mid-stream close 1009, after events have gone out, is not covered by a test: it stays a cut stream as before, and nothing replays it. Not observed in either report.
- zstd-encoded turn bodies take the same socket path (the message is decoded before the socket, so the prelude read and this fix see it the same); not separately tested with the close frame.
Attribution: AI-written; I've read the whole diff and the tests pass. Please keep the author (ggbdpq) or add Co-authored-by: ggbdpq <[email protected]>.
patch: hunt76-b-ws-message-too-big (#3444) — git am applies it as is; SHA-256 first 16: 6defde704d4fe1b3
From dd8ee62c4731b6c19ac41d9606ff1ea36b9d47b0 Mon Sep 17 00:00:00 2001
From: ggbdpq <[email protected]>
Date: Sat, 24 Oct 2026 14:30:19 +0800
Subject: [PATCH] gateway: a turn the Codex socket refuses as too big goes over
HTTP
The ChatGPT backend closes its WebSocket with a StatusMessageTooBig
close frame when a turn's message is over what the socket takes, and
magpie turned that into a 502 that read as OpenAI being down (#3444).
A turn the backend refuses so, before its reply begins, goes over HTTP
as it was, as Codex's own client makes it; the host isn't shunned for
it, so the next, small turn is on the socket again.
Run: go test -tags nogui ./internal/gateway/ (TestCodexSocketTooBigGoesOverHTTP red before the fix, green after; the package green, -race on the codex socket tests green)
Fixes #3444
Generated-by: GLM-5.3-Flash (ZCode)
---
internal/gateway/codex_socket.go | 7 +++++
internal/gateway/codex_socket_test.go | 37 +++++++++++++++++++++++++++
2 files changed, 44 insertions(+)
diff --git a/internal/gateway/codex_socket.go b/internal/gateway/codex_socket.go
index 4a926389..2616c0fd 100644
--- a/internal/gateway/codex_socket.go
+++ b/internal/gateway/codex_socket.go
@@ -288,6 +288,13 @@ func (t codexSocket) socket(req *http.Request, msg []byte) (*http.Response, erro
if errors.Is(err, io.EOF) && len(body.pending) == 0 {
return nil, errors.New("codex websocket: closed before the reply began")
}
+ if websocket.CloseStatus(err) == websocket.StatusMessageTooBig {
+ // the backend refused the turn's message as more than
+ // its socket takes, before the reply began: nothing of
+ // it was taken, and the same turn clears over HTTP, as
+ // Codex's own client makes it (#3444)
+ return nil, errCodexSocketFallBack
+ }
return nil, err
}
if frame == nil { // dropped
diff --git a/internal/gateway/codex_socket_test.go b/internal/gateway/codex_socket_test.go
index b9102727..5cd90889 100644
--- a/internal/gateway/codex_socket_test.go
+++ b/internal/gateway/codex_socket_test.go
@@ -33,6 +33,10 @@ type fakeSocketBackend struct {
posts int
refuse int
frames func(socketTurn) []string
+ // tooBig says which turns the backend refuses with a close
+ // StatusMessageTooBig, as it does a message over its socket's
+ // ceiling (#3444)
+ tooBig func(socketTurn) bool
}
func (f *fakeSocketBackend) ServeHTTP(w http.ResponseWriter, r *http.Request) {
@@ -59,6 +63,10 @@ func (f *fakeSocketBackend) ServeHTTP(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
f.sockets = append(f.sockets, turn)
f.mu.Unlock()
+ if f.tooBig != nil && f.tooBig(turn) {
+ c.Close(websocket.StatusMessageTooBig, "")
+ return
+ }
for _, fr := range f.frames(turn) {
if c.Write(r.Context(), websocket.MessageText, []byte(fr)) != nil {
return
@@ -282,6 +290,35 @@ func TestCodexSocketClosedEarlyIsCut(t *testing.T) {
}
}
+// A turn whose message the backend refuses with a close
+// StatusMessageTooBig — a large one, over the socket's ceiling, which the
+// same request clears over HTTP — goes over HTTP as it was, as Codex's own
+// client makes it, and the host isn't shunned for it: the next, small turn
+// is on the socket again (#3444).
+func TestCodexSocketTooBigGoesOverHTTP(t *testing.T) {
+ socketOn(t)
+ f := &fakeSocketBackend{frames: wholeReply, tooBig: func(turn socketTurn) bool {
+ return len(turn.msg) > 1<<20
+ }}
+ chatgpt(t, f.ServeHTTP)
+
+ big := `{"model":"gpt-5.5","stream":true,"input":"` + strings.Repeat("x", 2<<20) + `"}`
+ code, body := codexPost(t, big)
+ if code != 200 || !strings.Contains(body, `"delta":"po"`) {
+ t.Fatalf("the big turn: %d %s", code, body[:min(len(body), 400)])
+ }
+ if strings.Contains(body, "MessageTooBig") {
+ t.Errorf("the big turn's size reached Codex: %s", body[:min(len(body), 400)])
+ }
+ code, body = codexPost(t, `{"model":"gpt-5.5","stream":true,"input":"ping"}`)
+ if code != 200 || !strings.Contains(body, "pong") || !strings.Contains(body, "response.completed") {
+ t.Fatalf("the small turn: %d %s", code, body)
+ }
+ if posts, sockets := f.counts(); posts != 1 || sockets != 2 {
+ t.Fatalf("%d posts, %d sockets; want the big turn over HTTP after its socket, the small one on a socket", posts, sockets)
+ }
+}
+
// A request that isn't a streamed turn goes over HTTP as before.
func TestCodexSocketOnlyForStreamedTurns(t *testing.T) {
socketOn(t)
--
2.50.1 (Apple Git-155)
Branch with the commit: hunt76-b-ws-message-too-big (head dd8ee62c4731b6c19ac41d9606ff1ea36b9d47b0).
补充本次独立完成的精确字节边界探测和一份发送前分流的修复补丁,供维护者选择。已阅读上面 skygunner 和 ggbdpq 的修复讨论;这里补充提前选择传输方式的实现和对应边界验证。
真实上游探测
日期:2026-10-24;macOS / Apple Silicon;本机 Magpie v0.1.1364(构建 commit dd1e8822d916);本机 Codex CLI 0.163.0。
使用不存在的模型、stream=true, store=false,在 JSON 对象内部添加空白,使 最终 WebSocket response.create 消息的 UTF-8 字节数精确达到目标。空白不进入模型输入,也没有发送真实会话、截图或工作数据。
| 传输方式 | 消息/HTTP正文的字节数 | 结果 |
|---|---|---|
| WebSocket | 16,777,215 | 可解析,返回 model_not_found |
| WebSocket | 16,777,216 | 可解析,返回 model_not_found |
| WebSocket | 16,777,217 | 远端 Close 1009,空 reason |
| HTTP | 16,777,217 | HTTP 400 / model_not_found,通过传输层 |
WebSocket 协商了 permessage-deflate;TLS 校验开启,证书 subject 为 chatgpt.com、issuer 为 Google Trust Services / WE1。以上可以定位到远端 ChatGPT TLS 服务入口,不能从客户端进一步区分其内部前置网关和应用后端。16 MiB 是本次连接的实测边界,不声称这是所有环境或未来版本的公开契约。
修复
基于本次准备时的 main:7d9165d842f75fbbd59f3710fe8df7f6ecf83534。
在 codexSocketMessage(req) 完成解压、补充 client_metadata 和构造 response.create 之后,以最终 len(msg) 判断:大于 16 << 20 时,在 Dial / Write 之前直接交给已有的 HTTP transport。小于等于上限的请求继续用 WebSocket。
- 原 HTTP 正文、zstd 编码和请求头保持不变;
GetBody读取副本,不消费原正文。 - 不裁剪图片或历史;不修改主机的 socket shun 状态。
- 不增加发送失败后的重试,不重放任何已开始的响应流。
- 更新子系统说明,并新增六个本地回归场景:小请求、上限前一字节、恰好上限、超过一字节、zstd 压缩超限、元数据注入导致超限。
已实际完成的验证
- 在上述
main基线上保留新增测试、恢复旧传输选择逻辑:above、compressed_above、metadata_crosses_limit三个场景失败,错误包含received close frame ... StatusMessageTooBig;恢复修复后通过。 go test -tags nogui ./internal/gateway -run '^TestCodex' -count=1 -timeout=5m:通过,25.827 s。- WebSocket 相关测试的
-race:通过。 go vet -tags nogui ./internal/gateway、gofmt -l、git diff --check:通过。CGO_ENABLED=0 go build -tags nogui:通过。- 隔离网关使用独立监听端口和独立 XDG / CODEX_HOME,真实上游验证 16,777,217 字节 HTTP 正文可正常到达参数校验;随后使用有效模型
gpt-6.1-sol、仅要求回复OK的合成请求:HTTP 200、response.completed=true、输出严格为OK,2.74 s。隔离网关已停止,运行中的桌面 Magpie 未修改。
未验证:全仓库及跨平台发布验收、桌面版签名安装、原故障会话完整续跑,以及大请求走 HTTP 后超过 120 秒的长回复。补丁不替代现有小请求 WebSocket 路径。本次没有加入根据 Close 1009 动态回退的实现;如果远端未来降低上限,仍需重新评估该阈值或结合维护者选定的回退方案。
下面的补丁可保存为 .patch 后用 git am 应用;包含生产修改、测试和子系统说明。AI 协助编写,所列检查与真实探测均已实际执行,不含凭据或业务数据。
可应用的完整修复补丁:发送前按 16 MiB 选择传输方式
From 62377764e73328ac8aec5cc02e71e602fc032925 Mon Sep 17 00:00:00 2001
From: machenbin315-design
<[email protected]>
Date: Sat, 24 Oct 2026 16:01:04 +0800
Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=20Codex=20=E5=A4=A7=E6=B6=88?=
=?UTF-8?q?=E6=81=AF=E8=B6=85=E8=BF=87=20WebSocket=20=E4=B8=8A=E9=99=90?=
=?UTF-8?q?=E6=97=B6=E7=9A=84=E4=BC=A0=E8=BE=93=E9=80=89=E6=8B=A9?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
按最终 response.create 消息的解压后字节数判断传输方式,超过 16 MiB 时在发送前使用原 HTTP 请求;保留小请求的 WebSocket 路径和 zstd 正文,避免错误后的重放。新增边界、压缩和元数据跨界回归测试。
---
docs/subsystems/providers-accounts.md | 2 +
internal/gateway/codex_socket.go | 6 +-
internal/gateway/codex_socket_size_test.go | 108 +++++++++++++++++++++
3 files changed, 115 insertions(+), 1 deletion(-)
create mode 100644 internal/gateway/codex_socket_size_test.go
diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md
index ba2bc78..9b9eef0 100644
--- a/docs/subsystems/providers-accounts.md
+++ b/docs/subsystems/providers-accounts.md
@@ -212,6 +212,8 @@ and `TestHistoricalWindowHoldsUsesEachWindowsOwnReading`.
- A Codex account is known by its email, with the plan for a workspace seat (`codexUser`), and a second seat of one email in another workspace by that name with its workspace after it (`codexName`): `[email protected] · Team · ws-two`. The account Codex is signed in to goes by the name it is saved under (`codexLiveName`) everywhere: its provider's `Account.User` (`codexAccount`), `liveLogin`, and its session identity (`SessionIdentities`). Its allowance, rests and sticks (`restKey`), cap, proxy, model list, a gateway key's account list (`LoginID`) and the Routing page all go by that name, so two seats of one email are never read as one (#1424).
- Every request to the ChatGPT backend (`CodexBase`'s host) goes over HTTP/1.1, as Codex itself speaks to it: each transport [`netproxy.Dispatch`](../../internal/netproxy/netproxy.go) makes (`http.DefaultClient`'s, the gateway's) sends a request `netproxy.HTTP1` names through an HTTP/1.1 copy of itself whose TLS hello offers no h2, and the provider package sets `HTTP1` to `codexBackend` ([codex_http1.go](../../internal/provider/codex_http1.go)). That covers the gateway's turns, the models list, the warm-up, the allowance, its resets and spending one, through the proxy in force, an account's own included. Every other vendor is still offered HTTP/2.
- A streamed turn to the ChatGPT backend (POST `CodexBase`/responses with `"stream":true`) goes over the backend's WebSocket, as Codex's own client sends it, and comes back as the server-sent events the HTTP route answers with (`codexSocket` in [codex_socket.go](../../internal/gateway/codex_socket.go), first in the gateway's `upstreamTransport`, so Codex's own sign-in passed through and magpie's ChatGPT accounts both take it, through the proxy in force). On some networks a streamed HTTP reply from chatgpt.com is cut at about 120 s, before `response.completed`, while the WebSocket runs to the end (brickhao on Discord). The handshake carries the turn's headers with `OpenAI-Beta: responses_websockets=2026-02-06`, without `x-codex-turn-state` and the responses-lite header, which go in the message's `client_metadata` as Codex puts them; the message is the body with `"type":"response.create"` ahead of it (a zstd body is decoded first). `codex.rate_limits` and `codex.response.metadata`, read ahead of the reply, are also told as the `x-codex-*` and `x-codex-turn-state` headers the HTTP route carries; `responsesapi.websocket_timing` is dropped. An `error` frame ahead of the reply is that status with its error as the body; `websocket_connection_limit_reached`, a refused handshake or a body that isn't a streamed turn goes over HTTP instead, and a host that refused the handshake (other than 401, 429 or 5xx) is spoken HTTP for 10 minutes (`codexSocketShun`). A socket closed before the reply's end reads as a cut stream (`io.ErrUnexpectedEOF`). Codex still speaks HTTP to magpie: magpie answers its WebSocket handshake 426, and Codex falls back for the session; only the leg to the vendor changed. The gateway's tests turn it off in TestMain (`codexSocketOff`); codex_socket_test's fakes speak it.
+
+ 发送前按最终 `response.create` 消息的字节数选择传输方式:超过 16 MiB(`codexSocketMessageLimit`)直接发送原 HTTP 请求,保留其 zstd 编码和请求头;大小包含解压后的正文、`type` 和新增的 `client_metadata`。2026-10-24 的真实上游探测中,16,777,216 字节可以解析,多 1 字节即收到 Close 1009,同样大小的 HTTP 请求可以解析。该选择不重发已开始的请求、不改变小请求的 WebSocket 路径,也不修改按主机保存的握手回退状态。`TestCodexSocketMessageSizeTransport` 覆盖边界、压缩和元数据使消息超限的情况。
- A provider the user added may have its certificate left unchecked (`InsecureTLS`, the editor's Certificate row, #2383: a vLLM on the LAN, Ollama behind a self-signed cert, a company CA). Only one with a base URL of the user's own takes it (`TakesInsecureTLS`: no account, no preset, not Vertex, not a subscription's or plugin's id); `Save` refuses it on any other, and one written into providers.json by hand is ignored. `Provider.Via` then adds `netproxy.WithUncheckedTLS` with the hosts of its own base URLs (`UncheckedHosts`: Chat, Responses, Anthropic, Gemini, Decide), so every request made on its behalf through a `Dispatch` transport (the gateway's turns, count_tokens, models, test and detect, balance) skips the check for those hosts alone, on a transport kept apart for each (`route.unchecked`). A redirect or a models, balance or image URL on another host is checked, and `netproxy.With` drops the leave for a request made for another provider. An `https://` proxy would be dialled with the same TLS config, so its certificate would go unchecked too: such a request is refused (`ErrUncheckedOverHTTPSProxy`); an `http://` or `socks5://` proxy is taken. Backup, export and sync carry the field with the provider; an import link doesn't.
- The Copilot account the editors and CLI keep is read by `copilotLogin` ([account.go](../../internal/provider/account.go)): an editor's github.com sign-in in `~/.config/github-copilot/apps.json` or `hosts.json` first, then the Copilot CLI's, then an editor's on GHE.com. When GitHub refuses the editor token's trade for a session token (401 or 403, `copilotRefusals`, retried after an hour), the CLI's sign-in of the same login on the same host takes its place, sent as the CLI sends it, from that request on and on the Usage card (`copilotStandIn`); a CLI signed in to another account is never used for it, and the error names the editors' file (#1238). A sign-in from magpie of the account whose editor token is refused is kept and stands for it (`copilotProbeEditor`, `addCopilotLogin`); while the editor token works, it is let go as the agent's own, as before.
- A keychain read that may have shown the user a dialog is not asked again for ten minutes after it was refused (`keychainDeniedTTL` in [account.go](../../internal/provider/account.go)): Copilot's token read backs a denial off (`copilotCLISecret`), and the Cursor token (`cursorKeychainToken`) and Claude Code's item (`readClaudeKeychainItem`, through `claudeCredential`'s cache) do too (#2408). 44, the item not being there, is no refusal and keeps the short TTL, so a sign-in made in the agent is still seen within it; a sign-in or out in magpie reads afresh (`forgetCursorStatus`, `forgetClaudeCredential`), backoff or not.
diff --git a/internal/gateway/codex_socket.go b/internal/gateway/codex_socket.go
index 4a92638..b0c2404 100644
--- a/internal/gateway/codex_socket.go
+++ b/internal/gateway/codex_socket.go
@@ -64,6 +64,10 @@ var codexSocketDial = 30 * time.Second
// for headers before the reply is handed on.
const codexSocketPrelude = 8
+// 上游在解压后的单条消息超过 16 MiB 时发送 Close 1009;HTTP 接受同样的请求。
+// 在发送前选择 HTTP,避免连接关闭后重发一个可能已经开始执行的请求。
+const codexSocketMessageLimit = 16 << 20
+
var (
codexShunMu sync.Mutex
codexShun = map[string]time.Time{}
@@ -100,7 +104,7 @@ func (t codexSocket) RoundTrip(req *http.Request) (*http.Response, error) {
return t.next.RoundTrip(req)
}
msg, ok := codexSocketMessage(req)
- if !ok {
+ if !ok || len(msg) > codexSocketMessageLimit {
return t.next.RoundTrip(req)
}
res, err := t.socket(req, msg)
diff --git a/internal/gateway/codex_socket_size_test.go b/internal/gateway/codex_socket_size_test.go
new file mode 100644
index 0000000..8d47dd5
--- /dev/null
+++ b/internal/gateway/codex_socket_size_test.go
@@ -0,0 +1,108 @@
+package gateway
+
+import (
+ "bytes"
+ "crypto/sha256"
+ "io"
+ "net/http"
+ "strings"
+ "sync/atomic"
+ "testing"
+
+ "github.com/coder/websocket"
+
+ "github.com/yetone/magpie/internal/provider"
+)
+
+func TestCodexSocketMessageSizeTransport(t *testing.T) {
+ const limit = 16 << 20
+ for _, tc := range []struct {
+ name string
+ size int
+ compressed bool
+ turnState bool
+ wantSocket bool
+ }{
+ {"small", 1024, false, false, true},
+ {"below", limit - 1, false, false, true},
+ {"at", limit, false, false, true},
+ {"above", limit + 1, false, false, false},
+ {"compressed_above", limit + 1, true, false, false},
+ {"metadata_crosses_limit", limit - 1, false, true, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ socketOn(t)
+ base := `{"model":"gpt-5.5","stream":true,"input":""}`
+ body := strings.TrimSuffix(base, `"}`) + strings.Repeat("x", tc.size-len(base)-len(`"type":"response.create",`)) + `"}`
+ wantHash := sha256.Sum256([]byte(body))
+ var posts, sockets atomic.Int32
+ chatgpt(t, func(w http.ResponseWriter, r *http.Request) {
+ if strings.EqualFold(r.Header.Get("Upgrade"), "websocket") {
+ sockets.Add(1)
+ c, err := websocket.Accept(w, r, nil)
+ if err != nil {
+ return
+ }
+ defer c.CloseNow()
+ c.SetReadLimit(limit)
+ if _, _, err := c.Read(r.Context()); err != nil {
+ return
+ }
+ for _, frame := range wholeReply(socketTurn{}) {
+ if c.Write(r.Context(), websocket.MessageText, []byte(frame)) != nil {
+ return
+ }
+ }
+ c.Close(websocket.StatusNormalClosure, "")
+ return
+ }
+ posts.Add(1)
+ encoding := r.Header.Get("Content-Encoding")
+ if tc.compressed && encoding != "zstd" {
+ t.Errorf("HTTP body lost its zstd encoding: %q", encoding)
+ }
+ rd, err := decodedBody(r)
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ defer rd.Close()
+ got, err := io.ReadAll(rd)
+ if err != nil || sha256.Sum256(got) != wantHash {
+ t.Errorf("HTTP fallback changed the request: %v", err)
+ }
+ w.Header().Set("Content-Type", "text/event-stream")
+ for _, frame := range wholeReply(socketTurn{}) {
+ io.WriteString(w, "data: "+frame+"\n\n")
+ }
+ })
+ req, err := http.NewRequest(http.MethodPost, provider.CodexBase+"/responses", bytes.NewReader([]byte(body)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if tc.turnState {
+ req.Header.Set("X-Codex-Turn-State", "state-added-to-client-metadata")
+ }
+ if tc.compressed {
+ defer provider.CodexZstdForTests(true)()
+ provider.CodexCompressed(req, []byte(body))
+ }
+ res, err := New().client.Do(req)
+ if err != nil {
+ t.Fatalf("turn failed instead of choosing a transport that accepts its size: %v", err)
+ }
+ defer res.Body.Close()
+ reply, err := io.ReadAll(res.Body)
+ if err != nil || !strings.Contains(string(reply), "response.completed") {
+ t.Fatalf("reply did not finish: %v, %.200s", err, reply)
+ }
+ wantPosts, wantSockets := int32(1), int32(0)
+ if tc.wantSocket {
+ wantPosts, wantSockets = 0, 1
+ }
+ if posts.Load() != wantPosts || sockets.Load() != wantSockets {
+ t.Errorf("%d HTTP posts and %d sockets, want %d and %d", posts.Load(), sockets.Load(), wantPosts, wantSockets)
+ }
+ })
+ }
+}
补充一组独立实测:v0.1.1364 下,带 zstd 编码的大上下文请求经 Magpie 返回 502 / StatusMessageTooBig,同一份请求直连官方 HTTP/SSE 则完整完成。
已阅读前面的合成图片对照及补丁讨论;这次补充的是从实际故障聊天历史重建的大请求和 zstd 编码路径。
环境与测试方法
- macOS / arm64;Magpie
0.1.1364,已通过安装二进制的 Go build info 核实构建提交为dd1e8822d916f8aeb085db4db93fc3d79e2263ed。 - 模型
gpt-6.1-sol,reasoning.effort=xhigh,stream=true,store=false。 - 两条路径使用同一现有 ChatGPT 登录、相同 JSON 请求体及相同 zstd 编码载荷,仅改变目标连接。
- 原始失败 HTTP 包没有保存;重建时保留原聊天历史,省略顶层工具声明(
tools: []),并补上标准 Responses 参数。因此这不是原故障请求的逐字抓包重放,但下面两次对比的请求体逐字一致。返回的工具调用没有执行。
结果(2026-10-24)
原始 JSON:16,835,798 字节;zstd 编码后:6,190,187 字节。
两次请求原始 JSON 的 SHA-256 均为:
b441d933580321453f1b8c998bf719ad21a767b6cce4698a89c969e03150badc
| 路径 | 结果 | 耗时 |
|---|---|---|
POST http://127.0.0.1:3425/backend-api/codex/responses |
HTTP 502,StatusMessageTooBig |
2.185 s |
POST https://chatgpt.com/backend-api/codex/responses |
HTTP 200,收到 response.completed,最终 status=completed |
11.420 s |
直连完成事件报告 input_tokens=308082。不仅收到 200 响应头,也实际检查了最终完成事件。
Magpie 错误链:
OpenAI can't be reached
codex websocket: failed to get reader: received close frame:
status = StatusMessageTooBig and reason = ""
这组数据再次支持前面提出的 HTTP 回退/发送前分流方向:客户端到 Magpie 的 zstd 载荷约 6.19 MB,解压后的 JSON 约 16.84 MB;同体直连 HTTP 可完成,而本机 v0.1.1364 的 WebSocket 转发路径失败。本次没有测量最终上游 WebSocket 帧大小或精确阈值,也没有安装/验证讨论中的修复补丁。
测试未修改持久配置、替换 Magpie 二进制或重启网关。此处仅提交脱敏的错误片段和汇总数据,不附聊天原文、图片、请求正文或认证信息。报告由 Codex 协助整理,所列状态码、字节数、完成事件及耗时均来自实际执行。
Thanks both — qiuyu21's zstd measurement lands exactly on the one face our patch left Not verified, so I went and closed it.
zstd is covered, now confirmed. The decode happens before the socket: codexSocketMessage (codex_socket.go L125-133) decodes a Content-Encoding: zstd body before building the response.create message, so a zstd-carried turn produces the same over-ceiling WS message, the backend's 1009 close lands on the same prelude read the fix watches, and the HTTP leg re-sends the turn with its body zstd, as Codex sent it. qiuyu21's numbers are that chain live: 6.19 MB on the wire, ~16.84 MB decoded, close over the socket, the identical body completing over direct HTTP/SSE. A quick injection test on our branch (local only) pins it: a zstd-encoded turn whose decoded message a fake backend refuses with 1009 comes back 200 over HTTP (the big turn: 1 post after its refused socket; the next, small turn rides a socket again), and with the fix reverted it reproduces qiuyu21's exact 502 — OpenAI can't be reached ... status = StatusMessageTooBig.
machenbin's pre-send routing is a third shape, not a rival diagnosis. Ours and skygunner's classify the close frame after one failed round trip and assume no threshold; theirs probes the boundary (16 MiB on their connection, 2026-10-24) and picks the transport before dialing — saving that round trip if the boundary holds, at the cost of pinning today's ceiling, which they themselves flag as needing re-evaluation if the backend changes it. Choose-before-send vs. fall-back-after-close: two honest trade-offs, and either shape stands alone.
@yetone three patches now share one diagnosis — the ceiling is the backend's, and a turn it refuses belongs on HTTP: skygunner's post-close fallback (b834f286, first), our post-close fallback (dd8ee62c), machenbin's pre-send router. The choice of shape is yours; happy to rebase or withdraw ours to fit.
Gap filled: I've now read machenbin's patch itself — the inline git am block in their comment (commit 62377764, based on 7d9165d8) — not just its description.
The shape, from the code. One gate in codexSocket.RoundTrip: after codexSocketMessage builds the final response.create message — zstd decoded, client_metadata injected — any final message over 16<<20 (codexSocketMessageLimit) goes to the existing HTTP leg before any dial. Because the check reads the final message, zstd-decoded growth and metadata injection are both inside it (their compressed_above and metadata_crosses_limit scenarios pin exactly that); the HTTP leg re-sends the original request untouched (their test hashes the body and asserts Content-Encoding: zstd survives), and no socket is dialed, no shun state written, no started stream replayed. For oversized turns there is no mid-stream 1009 left to classify — the message never enters the socket. The residual face is the opposite one: a turn ≤ 16 MiB that some backend edge refuses lower still surfaces as an error, since the patch deliberately ships no post-close fallback (they say so themselves). Bodies over the pre-existing 512 MiB read limit already went HTTP, so the new gate refines an existing chain.
The boundary, as they state it. 16 MiB comes from their 2026-10-24 probe (16,777,216 parses, one more byte closes, same-size HTTP passes); they flag it as a measured edge on one connection, not a public contract, needing re-evaluation if the backend moves.
It composes with ours. I cherry-picked our dd8ee62c onto their patch: the two touch different hunks of codex_socket.go (theirs in RoundTrip, ours in socket's prelude read), the test files don't collide (theirs adds codex_socket_size_test.go, ours extends codex_socket_test.go), the auto-merge was clean, and go test -tags nogui ./internal/gateway -run '^TestCodex' passes with both in (22.7s), including both new tests. Together: the pre-send router covers today's ceiling, the post-close fallback catches a lowered one.
So the three patches stand as: skygunner's post-close fallback (b834f286), ours (dd8ee62c), machenbin's pre-send router (62377764) — one diagnosis, two after-close shapes and one before-send shape, and ours and machenbin's compose. @yetone the choice is still yours; happy to rebase or withdraw ours to fit.
Update: our patch above (dd8ee62c, branch hunt76-b-ws-message-too-big) is superseded by upstream 3e9efe1d ("a Codex turn chatgpt.com's WebSocket refuses as too big goes over HTTP") — withdrawing it; the branch stays for the record.
I've read the two diffs side by side. Same trigger, same mechanism: a close StatusMessageTooBig arriving before any frame of the reply was handed on becomes errCodexSocketFallBack, the gateway re-posts the same body over the HTTP leg, and the caller gets the HTTP answer — nothing of the turn or its size leaks to Codex, which is what our patch did with its 7-line check in the prelude read. The shared boundary is the same too: a close after the reply began stays a cut stream and is not asked again (TestCodexSocketTooBigMidReplyIsCut, green on both trees).
Upstream's shape is a strict superset of ours, with nothing of ours left to rebase:
- it classifies not just 1009 but every end of the socket before the reply — 1001, 1008, 1011, 1012, 1013, 1006, a dropped connection, a normal close with no reply — and a failed write, where ours covered the 1009 close alone;
- a 1009 also records the message's size for that host (
codexTooBig): a message at least that big skips the socket forcodexSocketShun(10 min), so a long conversation isn't uploaded twice each turn. Ours kept no memory and let every big turn lose one socket round trip first — the same client-visible 200 either way, theirs just gets there sooner.
Verified by run, not by reading alone. Our branch's contract test (the 1 post, 2 sockets pair: the big turn served over HTTP after one refused socket, the small turn back on a socket, no MessageTooBig text reaching Codex) applied onto 39fed471 — renamed TestCodexSocketTooBigFallsBackEachTurn, since 3e9efe1d took the original name for its own size-remembering shape — passes on upstream's fix as is. With the product file reverted to its pre-fix state (dd1e8822, the v0.1.1364 build this issue reports against) that same test fails with the issue's own text — 502 ... received close frame: status = StatusMessageTooBig — so the red-green pair brackets the fix, and the counts our patch pinned hold on theirs. At this head: upstream's three socket tests green, the whole internal/gateway package green (-tags nogui, 355 s), the socket family green under -race, gofmt clean.
No commit after 3e9efe1d up to current upstream/main (5e0d7c05) touches codex_socket.go or its tests. So #3444 is fixed on main from our side too — the issue can be closed whenever you like; happy to see it fixed.
Branch kept for the record, no longer proposed: hunt76-b-ws-message-too-big (head dd8ee62c).
Written with GLM-5.3-Flash (ZCode); the verdict above comes from the runs listed, run on this machine.