diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 3339db420..db3f01e40 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -395,7 +395,7 @@ 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`): `me@example.com · 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). One ChatGPT sign-in reaches every workspace of its login with one refresh token, and the Codex app's workspace switch rewrites only `account_id` in `auth.json`, so two saved workspaces can share the sign-in Codex holds. Such an account is renewed where Codex holds it (`heldByCodex`, `codexHeldIn`) but its requests, allowance, plan and resets name its own workspace (`codexOwnWorkspace`), and a sign-in sync carries Codex's sign-in only on the record of its workspace (`codexWorkspacesApart` in `liveCodex` and `applyLogins`). Before, the account not in use read the one in use's (JdAZzzzzz on X: a Team seat read as the personal Prolite with its resets; `TestCodexAppWorkspaceSwitchReadsEachWorkspace`). - 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, except a provider held to HTTP/1.1 (`HTTP1`, below), a host whose HTTP/2 broke on a TLS record error, and the requests of a download trying again after its transfer broke off (`netproxy.OverHTTP1`, `AgainOverHTTP1`, `BrokeOff`: magpie's update, from where it stopped, the masking model's files, Bun, Claude Code and the Grok CLI; biubiu8802 on X: a proxy cut every HTTP/2 stream of the update part way, "unexpected EOF", while it carried HTTP/1.1 whole; `TestDownloadBrokenOverHTTP2TriesHTTP1`, `TestAgainOverHTTP1`). - A Codex Responses Lite request (an `additional_tools` input item, or `reasoning.context` `all_turns`; Codex 0.165 and on) carries its instructions in the input, and Codex sends it with no top-level `instructions` and no `reasoning.summary`. `codexBody` adds neither to it (`codexLite`): before, it added Codex's full instructions and `summary: "auto"`, about 4K input tokens a request more than the official client (legeling567 on X; `TestCodexBodyLiteGetsNoInstructions`). A request that isn't Lite still gets them. The backend's `x-codex-turn-state` stays with the account that issued it: the gateway keeps the state a reply gave for that account and turn (`client_metadata` `thread_id` and `turn_id`) and sends it on the turn's next request to the same account, as Codex over HTTP sends it back; a state Codex sends itself goes only to the account that issued it ([codex_turnstate.go](../../internal/gateway/codex_turnstate.go), `TestCodexPoolTurnStateStaysWithItsAccount`). -- 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 that ends, or won't take the message, before any frame of the reply was handed on (any close status, a dropped connection, a normal close with no reply) sends the same body over HTTP (`codexSocketEnded`): Lamrfu's long conversation was closed 1009 (message too big) by chatgpt.com and got a 502. A conversation's socket is kept between its turns, and a turn that carries on from the last goes on it as only its new input after `previous_response_id`, as Codex's own client sends it (`codexKept` in [codex_socket_keep.go](../../internal/gateway/codex_socket_keep.go); codex-rs `get_incremental_items`): rem_thank on X saw magpie send the whole conversation on a new socket every turn, which a long one meets as 1009. A socket is kept for a turn that names its conversation (`session-id` or `thread-id`, else `prompt_cache_key`) and ended `response.completed` with an id, keyed by the host, a digest of `Authorization` and `chatgpt-account-id`, the conversation's ids and the subagent headers (`codexKeepKey`), so another account's turn never finds it nor names its response; the next turn takes it out of the pool, so two turns at once each have a socket. It is let go after 10 minutes unused (`codexKeepIdle`), at 55 minutes from its handshake (`codexKeepAge`; the backend ends a connection at 60) and the oldest past 32 (`codexKeepMax`); the gateway's tests drain the pool in their cleanup (`codexKeepDrain`). The turn goes as a delta when every field but `input`, `client_metadata` and `stream_options` is as the last turn sent it, and its input begins with the last turn's input and then that turn's `response.output_item.done` items, each compared without its id, status, nulls, empty lists, annotations and logprobs (`codexSocketItem`); anything else goes whole on the kept socket. What is compared is the body as it goes, after masking and every translation, so a turn masked otherwise than the last goes whole. A kept socket that fails before the reply is handed on (closed while kept, the write fails, or an `error` frame first, such as `previous_response_not_found` or the connection limit) is closed and the turn goes whole on a new socket, and from there over HTTP as before (`errCodexSocketAgain`). A message at least as big as one a host closed 1009 goes to it over HTTP for 10 minutes (`codexTooBig`). A socket closed after the reply began reads as a cut stream (`io.ErrUnexpectedEOF`), and is not asked again. Codex speaks to magpie over its own WebSocket since #4058 ([A Responses WebSocket](gateway-routing.md#a-responses-websocket)), sending a turn as a delta after `previous_response_id`; magpie gives each turn the whole conversation before it goes on, and this leg cuts its own delta for the kept socket. The gateway's tests turn it off in TestMain (`codexSocketOff`); codex_socket_test's fakes speak it. +- 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 that ends, or won't take the message, before any frame of the reply was handed on (any close status, a dropped connection, a normal close with no reply) sends the same body over HTTP (`codexSocketEnded`): Lamrfu's long conversation was closed 1009 (message too big) by chatgpt.com and got a 502. A conversation's socket is kept between its turns, and a turn that carries on from the last goes on it as only its new input after `previous_response_id`, as Codex's own client sends it (`codexKept` in [codex_socket_keep.go](../../internal/gateway/codex_socket_keep.go); codex-rs `get_incremental_items`): rem_thank on X saw magpie send the whole conversation on a new socket every turn, which a long one meets as 1009. A socket is kept for a turn that names its conversation (`session-id` or `thread-id`, else `prompt_cache_key`) and ended `response.completed` with an id, keyed by the host, a digest of `Authorization` and `chatgpt-account-id`, the conversation's ids and the subagent headers (`codexKeepKey`), so another account's turn never finds it nor names its response; the next turn takes it out of the pool, so two turns at once each have a socket. It is let go after 10 minutes unused (`codexKeepIdle`), at 55 minutes from its handshake (`codexKeepAge`; the backend ends a connection at 60) and the oldest past 32 (`codexKeepMax`); the gateway's tests drain the pool in their cleanup (`codexKeepDrain`). The turn goes as a delta when every field but `input`, `client_metadata` and `stream_options` is as the last turn sent it, and its input begins with the last turn's input and then that turn's `response.output_item.done` items, each compared without its id, status, nulls, empty lists, annotations and logprobs (`codexSocketItem`); anything else goes whole on the kept socket. What is compared is the body as it goes, after masking and every translation, so a turn masked otherwise than the last goes whole. A kept socket that fails before the reply is handed on (closed while kept, the write fails, or an `error` frame first, such as `previous_response_not_found` or the connection limit) is closed and the turn goes whole on a new socket, and from there over HTTP as before (`errCodexSocketAgain`). A message at least as big as one a host closed 1009 goes to it over HTTP for 10 minutes (`codexTooBig`). A socket closed after the reply began reads as a cut stream (`io.ErrUnexpectedEOF`), and is not asked again. Codex speaks to magpie over its own WebSocket since #4058 ([A Responses WebSocket](gateway-routing.md#a-responses-websocket)), sending a turn as a delta after `previous_response_id`; magpie gives each turn the whole conversation before it goes on, and this leg cuts its own delta for the kept socket. A turn on the socket tells the try's client trace of itself as Go's client tells it of an HTTP request (`socketTrace`): on a kept socket it is a request on an open connection, on a new one the handshake's DNS, connect and TLS stand and its round trip is the wait for the connection; the message written is the request written and the first frame the reply's first byte. So the Routing page's "Where the time went" (`TryNet`) and the usage record's split have the vendor's wait for every socket turn, where a kept socket's turn had nothing but its masking and a new socket's put the backend's wait in its first token (buhaodeshiyehao on X, `TestSocketTurnTellsWhereItsTimeWent`). The gateway's tests turn it off in TestMain (`codexSocketOff`); codex_socket_test's fakes speak it. - 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. - A provider the user added may show a client certificate and trust a CA of its own (`ClientCert`, `ClientKey`, `ServerCA`: absolute PEM paths, a `~` taken as home, the editor's Client certificate rows under Advanced, shown while an address is `https://`; #5596, clxsh: Remote Magpie to a magpie or an Nginx asking for mTLS). It takes the same providers as `InsecureTLS` (`TakesClientCert`), and `Save` refuses half a pair, a pair that doesn't match and a CA file with no certificate (`netproxy.CheckClientCert`). `Provider.Via` adds `netproxy.WithClientCert` with the hosts of its own base URLs, so the gateway's turns, streaming, models and the connection test show the certificate to those hosts alone, on a transport kept apart for each (`clientRoute`), the gateway key still sent; another host, and a request made for another provider, never see it. Through an `https://` proxy such a request is refused (`ErrClientCertOverHTTPSProxy`). The route is keyed on the files' paths, mtimes and sizes, so a certificate renewed in place gets a new transport (`TestRemoteMagpieClientCert`, `TestClientCertSaveChecks`, the `clientcert_test.go` tests). - The same providers may instead pin their server's certificate (`ServerPin`: the SHA-256 of its DER, lower-case hex; Zhangzhangi on X, a Remote magpie on a domain with a self-signed certificate macOS calls not standards compliant). Off by default, per provider. The editor's Advanced → Server certificate asks `POST /api/provider/peekcert`, which reaches the form's first `https://` address through its proxy and client certificate with the certificate unchecked (`Provider.PeekServerCert`) and shows its fingerprint, names, dates and why this computer doesn't take it (`x509.Verify` with the system roots); Trust keeps the pin, and the row then says in red that the certificate isn't verified. `Via` passes the pin to `netproxy.WithClientCert`, whose transport for those hosts skips the chain, name and date checks and refuses in `VerifyConnection` any leaf whose SHA-256 isn't the pin (`pinTLS`, `PinMismatchError`). The hosts it applies at are `PinHosts`: every endpoint of a provider that takes a client certificate, and of a preset's only the `https://` addresses at a host neither the preset nor its regions name (Zhangzhangi on X, "建议对别的自签名域名也生效": LM Studio or Ollama on another computer), never a subscription's, Vertex or a vendor's own host; a client certificate and Server CA still go only where `TakesClientCert` holds. `TakesServerPin` is in `/api/providers`, and the editor shows the row while the form has such an address (`pinAddrs` in app.js). `Save` refuses a pin that isn't 64 hex digits, or on a provider with no such address (`TestServerPinRemoteMagpie`, `TestServerPinSaveChecks`, `TestServerPinPresetAtOwnServer`, `TestServerPinNoVendorHost`, `TestPinOnlyThatCertificate`, `provider-server-pin.test.cjs`). diff --git a/internal/gateway/codex_socket.go b/internal/gateway/codex_socket.go index e6f342146..8b404598e 100644 --- a/internal/gateway/codex_socket.go +++ b/internal/gateway/codex_socket.go @@ -9,6 +9,7 @@ import ( "io" "log" "net/http" + "net/http/httptrace" "strconv" "strings" "sync" @@ -422,15 +423,22 @@ func (t codexSocket) turn(req *http.Request, k *codexKept, msg []byte, shape *co } return err } + trace := socketTrace(req, reused) if err := k.c.Write(req.Context(), websocket.MessageText, msg); err != nil { k.close() return nil, ended(err) } wroteSocket(req.Context(), len(msg)) + if trace != nil && trace.WroteRequest != nil { + trace.WroteRequest(httptrace.WroteRequestInfo{}) + } header := k.header.Clone() body := &codexSocketBody{c: k.c, ctx: req.Context(), k: k, shape: shape} - for range codexSocketPrelude { + for i := range codexSocketPrelude { frame, err := body.frame() + if i == 0 && err == nil && trace != nil && trace.GotFirstResponseByte != nil { + trace.GotFirstResponseByte() + } if err != nil { body.Close() // nothing of the reply has been handed on yet @@ -484,6 +492,33 @@ func (t codexSocket) turn(req *http.Request, k *codexKept, msg []byte, shape *co }, nil } +// socketTrace tells req's client trace (TryNet, the usage record's +// split) of the turn going out on the socket, as Go's client tells it of +// an HTTP request: a turn on a kept socket is a request on an open +// connection, which has no handshake of its own, and the frames' first is +// the reply's first byte. Without it a kept socket's turn, nearly every +// Codex turn after a conversation's first, wrote no request the trace +// saw, and the Routing page's "Where the time went" said only its +// masking (buhaodeshiyehao on X, Codex through Lody). On a new socket +// the handshake went through the client and the trace has its DNS, +// connect and TLS; the socket is the connection, got once the handshake +// is answered, so the handshake's round trip is the wait for it. The +// caller tells it WroteRequest once the message is written, and +// GotFirstResponseByte at the first frame. +func socketTrace(req *http.Request, reused bool) *httptrace.ClientTrace { + trace := httptrace.ContextClientTrace(req.Context()) + if trace == nil { + return nil + } + if reused && trace.GetConn != nil { + trace.GetConn(req.URL.Host) + } + if trace.GotConn != nil { + trace.GotConn(httptrace.GotConnInfo{Reused: reused}) + } + return trace +} + // codexSocketEnded is the turn going over HTTP after the socket ended, // or failed to take the message, before any of the reply was handed on: // whatever the close (1009 message too big, 1011, 1012, 1013, a dropped diff --git a/internal/gateway/codex_socket_test.go b/internal/gateway/codex_socket_test.go index 8010d6aa5..1d5c51e88 100644 --- a/internal/gateway/codex_socket_test.go +++ b/internal/gateway/codex_socket_test.go @@ -10,6 +10,7 @@ import ( "sync" "sync/atomic" "testing" + "time" "github.com/coder/websocket" "github.com/tidwall/gjson" @@ -50,6 +51,9 @@ type fakeSocketBackend struct { // whole has its HTTP reply run to response.completed path string whole bool + // hold is how long a turn waits before its first frame, as the + // backend thinking before it answers + hold time.Duration } func (f *fakeSocketBackend) ServeHTTP(w http.ResponseWriter, r *http.Request) { @@ -87,6 +91,7 @@ func (f *fakeSocketBackend) ServeHTTP(w http.ResponseWriter, r *http.Request) { f.mu.Lock() f.sockets = append(f.sockets, turn) f.mu.Unlock() + time.Sleep(f.hold) for _, fr := range f.frames(turn) { if c.Write(r.Context(), websocket.MessageText, []byte(fr)) != nil { return diff --git a/internal/gateway/nettrace_test.go b/internal/gateway/nettrace_test.go index 7b801cd6a..81375d541 100644 --- a/internal/gateway/nettrace_test.go +++ b/internal/gateway/nettrace_test.go @@ -119,3 +119,97 @@ func TestSentBy(t *testing.T) { } } } + +// buhaodeshiyehao on X (Codex through Lody): the Routing page's "Where +// the time went" said only a turn's masking. Codex's turns to the +// ChatGPT backend, and to a Responses provider with Socket, go over a +// WebSocket, and a conversation's turns after its first go on the kept +// socket, with no HTTP request the try's trace saw, so the try had no +// timing. Each turn on a socket, a new one or a kept one, says where its +// time went: the backend's wait before the first frame is the vendor's. +func TestSocketTurnTellsWhereItsTimeWent(t *testing.T) { + const hold = 200 * time.Millisecond + holdMs := float64(hold.Milliseconds()) + check := func(t *testing.T, what string, try Try) { + t.Helper() + n := try.Net + if n == nil { + t.Fatalf("%s: no timing", what) + } + t.Logf("%s: %+v", what, *n) + if n.Wait < holdMs-1 || n.Wait > holdMs+5000 || n.Head < n.Wait { + t.Fatalf("%s: timing %+v for a %v hold", what, *n, hold) + } + if sum := n.Own + n.Before + n.Pool + n.DNS + n.Connect + n.TLS + n.Send + n.Wait; sum > n.Head+1 { + t.Fatalf("%s: steps %v over the %v to the first byte: %+v", what, sum, n.Head, *n) + } + if float64(try.Millis) < n.Head-1 { + t.Fatalf("%s: first byte %v after the end %d", what, n.Head, try.Millis) + } + } + t.Run("codex sign-in", func(t *testing.T) { + socketOn(t) + f := &fakeSocketBackend{keep: true, hold: hold} + f.frames = keptReply(f) + chatgpt(t, f.ServeHTTP) + s := New() + post := func(body string) Try { + t.Helper() + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(body)) + req.Header.Set("Authorization", "Bearer chatgpt-token") + req.Header.Set("chatgpt-account-id", "acct-1") + s.Handler().ServeHTTP(rec, req) + if rec.Code != 200 || !strings.Contains(rec.Body.String(), "pong") { + t.Fatalf("%d %s", rec.Code, rec.Body.String()) + } + r := lastRoute(s) + if len(r.Tries) != 1 { + t.Fatalf("tries %+v", r.Tries) + } + return r.Tries[0] + } + check(t, "a new socket", post(keptTurn("conv-1", "gpt-5.5", userPing))) + kept := post(keptTurn("conv-1", "gpt-5.5", userPing, asstPong, userAgain)) + if posts, sockets := f.counts(); posts != 0 || sockets != 2 || f.opened() != 1 { + t.Fatalf("%d posts, %d turns on %d sockets; want both on one", posts, sockets, f.opened()) + } + check(t, "the kept socket", kept) + if n := kept.Net; !n.Reused || n.DNS != 0 || n.Connect != 0 || n.TLS != 0 { + t.Fatalf("the kept socket dialed: %+v", *n) + } + }) + t.Run("responses provider", func(t *testing.T) { + socketOn(t) + f := &fakeSocketBackend{keep: true, hold: hold} + f.frames = keptReply(f) + relaySocket(t, f, provider.SocketOn) + s := New() + post := func(body string) Try { + t.Helper() + code, out := postProtoBody(t, s, "/v1/responses", body) + if code != 200 || !strings.Contains(out, "pong") { + t.Fatalf("%d %s", code, out) + } + r := lastRoute(s) + if len(r.Tries) != 1 { + t.Fatalf("tries %+v", r.Tries) + } + return r.Tries[0] + } + check(t, "a new socket", post(keptTurn("conv-2", "relay/m1", userPing))) + kept := post(keptTurn("conv-2", "relay/m1", userPing, asstPong, userAgain)) + if posts, sockets := f.counts(); posts != 0 || sockets != 2 || f.opened() != 1 { + t.Fatalf("%d posts, %d turns on %d sockets; want both on one", posts, sockets, f.opened()) + } + check(t, "the kept socket", kept) + }) +} + +func postProtoBody(t *testing.T, s *Server, path, body string) (int, string) { + t.Helper() + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", path, strings.NewReader(body)) + s.Handler().ServeHTTP(rec, req) + return rec.Code, rec.Body.String() +}