provider: OpenAI's own API sends Responses turns over the WebSocket by default, only the new input each turn (KawaiiZapic on X)

KawaiiZapic's screenshot showed 6.4 GB up for 799 MB down: every turn
went out whole. What each leg sends, checked in the code:

- Codex on a ChatGPT subscription: the kept upstream socket already
  sends previous_response_id and only the new input (codex_socket*.go).
- A Responses provider with socket=auto/on: the same, but socket was
  off unless someone ticked it, so an OpenAI API key provider sent the
  whole conversation each turn over HTTP.
- A client's own previous_response_id is kept for api.openai.com,
  Azure and Ark (prevKeeps); other relays get the expanded whole turn,
  since they can't be trusted to hold the chain.
- Claude Messages, Chat Completions and Gemini have no incremental
  protocol; those always send whole (prompt caching is what saves there).
- The ↑ counter (upbytes.go) counts each upstream write once; no double
  count found.

Change: a Responses provider at https://api.openai.com with no socket
set now goes over the WebSocket (provider.SocketByDefault, mirroring
codex-rs's create_openai_provider supports_websockets: true). socket=off
is now stored, so unticking it there sticks; elsewhere unticked is still
"". The CLI shows "auto (default)" and takes socket=off|default. The
editor's WebSocket row moved into socketrow.js (imported as the editor
draws), so app.js and the core shrink by 165 bytes and their budgets
drop with them. Caveat: an OpenAI provider saved unticked before this
(socket "") now goes over the socket until it is unticked again; the
docs say so.

Measured (fake api.openai.com over TLS, sandbox HOME, 20 turns of a 4KB
user message each): socket off 20 HTTP posts, 876,345 bytes up;
default 0 posts, 20 socket turns on one handshake, 84,928 bytes up
(Traffic().Up equal to the socket bytes, so no double count).

Run (mica). At this head, rebased on origin/main 589e4ba6d: the go
test -run line below ok (budgets included), gofmt clean,
provider-socket.test.cjs 80/80 and old-webkit's same 2 reds. The rest
ran at the tree rebased on 1bfa8d5a1 (main since touched only plugin
assets and docs outside these files):
- go test -run 'Socket|Budget|OpenAI' ./internal/gui ./internal/provider
  ./internal/cli ./internal/gateway: ok.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows
  for provider, cli, gateway, gui: ok.
- GUI: provider-socket.test.cjs 80/80 (chromium + webkit, 5 languages,
  2 widths). Every provider-*, i18n-* and old-webkit file in one
  run: 1793 pass, 76 red. Each red file run alone at this tree and at
  origin/main 1bfa8d5a1 is red the same or green at both:
  provider-fetch-again (#5057, #5232), provider-many-keys and
  provider-max-output (#6209), provider-models-rest, provider-picks-stay
  and provider-typed (#6532), provider-proxy (#7100), provider-remove
  (#7101); provider-advanced-fold 50/50, provider-env-paste,
  provider-add-gemini, -gemini, -at-once, -auth-header and -mask pass
  alone (load).
- Full suite, go test -count=1 -timeout 45m ./...: 99 packages ok, 4 red.
  Alone: TestSearchQueueKeepsCodexAlive (gateway) and
  TestWSLStoppedDistroKept (sessions) pass; TestGatewayModeListsNoOwnSessions
  (gui, #7064) and the dirent watch tests (#7031) are red at
  1bfa8d5a1 too.
- old-webkit.test.cjs: 2 reds (guideback.js not in the lazy list,
  Safari 15.0 styles), the same on origin/main 1bfa8d5a1 run alone;
  noted on #6570.

Broken by hand: SocketByDefault returning false turns
TestSocketByDefaultOnOpenAI and TestOpenAIProviderTurnsGoOverWebSocketByDefault
red ("2 HTTP posts, 0 socket turns on 0 handshakes").

Not tried: a real OpenAI API key, and a real Codex binary against an
API-key provider; the fake follows the Responses WebSocket protocol the
existing socket tests use.

Reported-by: KawaiiZapic on X
This commit is contained in:
yetone
2026-11-18 20:22:30 +08:00
parent 9314999a4a
commit e08dc0fe58
14 changed files with 251 additions and 38 deletions
+13 -6
View File
@@ -3232,12 +3232,19 @@ serves it on `/v1/responses`, `/responses` and the Codex backend's
- `Run`'s shutdown ends each socket going away (1001) once its turn is
answered, through `clientSockets.drain` beside `srv.Shutdown` (a hijacked
connection isn't the server's), and refuses new ones 503.
- Not covered: the leg to the vendor is the whole conversation each turn,
as before (for the ChatGPT backend, a socket per turn: see
[Providers and accounts](providers-accounts.md)); what is saved is
Codex's upload to magpie, and, when the provider is another magpie, the
leg between the two magpies (below). A socket's conversation doesn't
outlive the socket or the gateway.
- The leg to the vendor cuts its own delta where the vendor keeps a
turn for the next: the ChatGPT backend and a Responses provider that
speaks the socket (`Socket`; unset, OpenAI's own API does, as Codex's
built-in OpenAI provider does, KawaiiZapic on X) take a turn as its new
input after `previous_response_id` on a kept socket (see
[Providers and accounts](providers-accounts.md)); OpenAI's API, Azure
and Ark over HTTP take the client's own `previous_response_id`
(`prevKeeps`, below), which Codex never sends (`store: false`); another
magpie takes the delta between the two (below). Everything else
(Chat Completions, Messages, Gemini, a Responses provider over HTTP)
is sent the whole conversation each turn, since those protocols keep
nothing between requests. A socket's conversation doesn't outlive the
socket or the gateway.
## A Realtime session
+2 -2
View File
@@ -453,7 +453,7 @@ and `TestHistoricalWindowHoldsUsesEachWindowsOwnReading`.
- 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`).
- A provider may connect a host of its base URLs to addresses of the user's choosing, as `curl --resolve` (`Provider.Resolve`, a map of host name to places; quantum_lsfc on X, a managed network whose domains go to an internal L4 SNI gateway, where an IP in the base URL fails the certificate and `/etc/hosts` can't be edited). A place is an IP address (with `:port` if the gateway listens elsewhere) or `dns:<name>`, looked up at each new connection so a rotating record is followed. Only the TCP target changes: the URL's name is still the TLS server name and the `Host`. The places are tried in order, each given 8s (`resolveTry`); when none connects, the name is dialled as if there were no rule. `Via` puts the rule on the context (`netproxy.WithResolve`), `Dispatch` keeps one transport clone per rule and wraps its `DialContext` (`resolveTLS`). Through a proxy (the provider's, the global one, the environment's) the rule is not used: the proxy gets `CONNECT` with the original name and connects itself; `RoundTrip` marks a request direct (`directKey`) only when `t.Proxy` says none. `TakesResolve` is where `TakesInsecureTLS`, `TakesClientCert` or `PinHosts` hold: a provider the user added, Remote magpie, a preset at a host of the user's own; never a subscription's account or a vendor's own host. Plugins are not covered: a plugin's requests are `fetch` calls in the Bun plugin host, which has no hook for the connection's address, so a plugin's provider takes no rule (`TakesResolve` is false for an account). `Save` runs `netproxy.CheckResolve` (bare host names, IP or `dns:` places, at most 32 hosts and 16 places) and refuses a rule on a provider that doesn't take one. The gateway's offline check leaves such a provider's host out of the hosts it dials to tell whether the network is up (`otherHosts`), since it dials them by name. The editor's Advanced → Connect to is a box of `host = place, place` lines (`resolveRow` in tlscerts.js; `TestResolveSaved`, `TestResolveVia`, `TestOtherHostsSkipResolved`, `TestProviderSaveResolve`, the `netproxy` `TestResolve*` tests, `provider-resolve.test.cjs`).
- A provider the user added may be held to HTTP/1.1 (`HTTP1`, the editor's "HTTP version" row under Advanced, shown while an address is `https://`; kepner_53726 on Discord: a company gateway whose HTTP/2 streams broke mid-reply with "tls: bad record MAC" while a plain Go client held). It takes the same providers as `InsecureTLS` (`TakesInsecureTLS`), and `Save` refuses it on any other. `Provider.Via` adds `netproxy.WithHTTP1` with the hosts of its own base URLs, so a request made on its behalf to one of those hosts goes through the `Dispatch` transport's HTTP/1.1 copy (`route.h1`); another host, and a request made for another provider (`netproxy.With` drops it), are offered HTTP/2 as before (`TestHTTP1AskedOnlyItsHost`, `TestHTTP1OwnProviderOnly`, `TestProviderSaveHTTP1`). Without it, a TLS record error read on an HTTP/2 reply (`recordError`: "bad record MAC", "received record with version …", an oversized record) moves that host:port to HTTP/1.1 for 6 hours (`h2BrokenFor`; see [Gateway routing](gateway-routing.md)).
- A provider the user added with a Responses address may send its turns over the Responses WebSocket, as the ChatGPT leg above does (`Socket`, #5781, faithleysath; matrix0487 on Discord; `magpie provider set <id> socket=auto|on|off`, the editor's WebSocket row under Advanced). It takes a provider with no account, an `http(s)://` Responses address and not Vertex (`TakesSocket`); the CLI refuses it on any other. `Provider.Via` puts the provider's Responses host and path in the request's context (`withSocket`), and `codexSocket` speaks the socket only to a POST to that host at `<Responses>/responses` (`SocketTurn`); a provider without `Socket` hides a value an outer context carried, so it never dials a socket (`TestResponsesProviderWithoutSocketNeverDials`). Everything after is the ChatGPT leg's: the fallback to HTTP on a refused handshake or a socket that ends before the reply, the kept socket and its delta (keyed by scheme, `Authorization`, `X-Api-Key` and `Api-Key` too), and a server-sent-events reply. `auto` speaks HTTP to a host for 10 minutes once it refused the handshake; `on` tries the socket every turn and never shuns. Routing, keys, limits, usage and masking are the HTTP route's, since the socket replaces only the transport.
- A provider the user added with a Responses address may send its turns over the Responses WebSocket, as the ChatGPT leg above does (`Socket`, #5781, faithleysath; matrix0487 on Discord; `magpie provider set <id> socket=auto|on|off`, the editor's WebSocket row under Advanced). It takes a provider with no account, an `http(s)://` Responses address and not Vertex (`TakesSocket`); the CLI refuses it on any other. `Provider.Via` puts the provider's Responses host and path in the request's context (`withSocket`), and `codexSocket` speaks the socket only to a POST to that host at `<Responses>/responses` (`SocketTurn`); a provider without `Socket` hides a value an outer context carried, so it never dials a socket (`TestResponsesProviderWithoutSocketNeverDials`). Everything after is the ChatGPT leg's: the fallback to HTTP on a refused handshake or a socket that ends before the reply, the kept socket and its delta (keyed by scheme, `Authorization`, `X-Api-Key` and `Api-Key` too), and a server-sent-events reply. `auto` speaks HTTP to a host for 10 minutes once it refused the handshake; `on` tries the socket every turn and never shuns. Unset, a provider at `https://api.openai.com` (its Responses host exactly, no plugin) is `auto` (`SocketByDefault`, `SocketMode`), as Codex's built-in OpenAI provider speaks the socket there (codex-rs `create_openai_provider`, `supports_websockets: true`): Codex says `store: false`, so over HTTP every turn went up whole (KawaiiZapic on X, `TestOpenAIProviderTurnsGoOverWebSocketByDefault`); `off` is kept as set, so such a provider stays on HTTP, and the editor's tick opens ticked there, saving `off` unticked and unset ticked again. Before this an unticked tick saved unset, so a provider unticked then goes over the socket now until it is unticked again. Routing, keys, limits, usage and masking are the HTTP route's, since the socket replaces only the transport.
- A provider the user added may be set never to rest for a limit (`LimitRestOff`, `limitRestOff`; the editor's Advanced fold, "Set it aside when out of quota or rate limited", ticked by default; zoecats on Discord: a local aggregator's "quota exhausted" while it switches upstreams). Off, a quota, credit or rate refusal and any 429 rest none of its keys and the next request is sent to it as usual (`restAfterMarked` in the gateway, see [gateway routing](gateway-routing.md)). The editor offers it only to a provider the user added (`custom`); a save that leaves it out keeps it (`TestProviderSaveLimitRestOff`, `provider-limit-rest.test.cjs`).
- 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.
@@ -537,7 +537,7 @@ go test -tags nogui ./internal/provider ./internal/gateway ./internal/gui -run '
node --test internal/gui/tests/provider-many-keys.test.cjs internal/gui/tests/provider-many-keys-proxy.test.cjs
go test -tags nogui ./internal/provider -run 'TestCapHeld|TestCapReached|TestWindowCapHeld|TestSetWindowCap'
go test -tags nogui ./internal/netproxy ./internal/provider ./internal/gateway -run 'TestDispatchHTTP1|OverHTTP1|TestAccountProxy|TestUncheckedTLS|TestInsecureTLS|TestHTTP1|TestH2Record|TestRecordError'
go test -tags nogui ./internal/provider ./internal/gateway ./internal/cli ./internal/gui -run 'TestSocket|TestResponsesProvider|TestProviderSetSocket|TestProviderSaveSocket'
go test -tags nogui ./internal/provider ./internal/gateway ./internal/cli ./internal/gui -run 'TestSocket|TestResponsesProvider|TestOpenAIProvider|TestProviderSetSocket|TestProviderSaveSocket'
node --test internal/gui/tests/provider-socket.test.cjs
go test -tags nogui ./internal/provider -run 'TestSeat|TestPlanOfASignedInAccountShownOnce|TestGLMPlanMatchesZCodePlugin|TestAccountName'
go test -tags nogui . -run TestAccountsAlias
+6 -3
View File
@@ -71,7 +71,8 @@ const providerUsage = `usage:
patience=default, 1m
socket=auto sends its Responses turns over the Responses WebSocket,
over HTTP when it can't, and over HTTP alone for 10m once the host
refuses it; socket=on tries it every turn; socket=off, the default
refuses it; socket=on tries it every turn; socket=off sends them
over HTTP alone; socket=default, auto on api.openai.com, else off
errors=pass sends the agent its errors as the vendor sent them:
asked once, nothing read into them, no other provider tried;
errors=magpie, the default, has magpie handle them
@@ -975,6 +976,8 @@ func showProviderAsking(p provider.Provider, ask bool) error {
}
if p.Socket != "" {
kv("socket", p.Socket)
} else if p.SocketByDefault() {
kv("socket", "auto (default)")
}
switch {
case p.Account != nil:
@@ -1345,7 +1348,7 @@ func applyPairs(p *provider.Provider, pairs []string) error {
// refuses it to HTTP for a while, on tries it every turn
s, ok := provider.ParseSocket(v)
if !ok {
return fmt.Errorf("socket=auto|on|off, not %q", v)
return fmt.Errorf("socket=auto|on|off|default, not %q", v)
}
p.Socket = s
case "patience":
@@ -1564,7 +1567,7 @@ func applyPairs(p *provider.Provider, pairs []string) error {
return fmt.Errorf("unknown field %q\n\n%s", k, providerUsage)
}
}
if p.Socket != "" && !p.TakesSocket() {
if p.Socket != "" && p.Socket != provider.SocketOff && !p.TakesSocket() {
return fmt.Errorf("socket=%s: %s has no Responses API of its own to speak a WebSocket to; only a provider with responses= and a key can", p.Socket, p.Name)
}
if p.NativeCompaction && !p.CarriesCompaction() {
+1 -1
View File
@@ -11,7 +11,7 @@ import (
// without a Responses URL, or a signed-in account, takes none.
func TestProviderSetSocket(t *testing.T) {
p := provider.Provider{ID: "relay", Name: "Relay", Key: "k", Responses: "https://relay.example/v1"}
for _, c := range []struct{ v, want string }{{"auto", "auto"}, {"on", "on"}, {"off", ""}, {"AUTO", "auto"}, {"default", ""}} {
for _, c := range []struct{ v, want string }{{"auto", "auto"}, {"on", "on"}, {"off", "off"}, {"AUTO", "auto"}, {"default", ""}} {
if err := applyPairs(&p, []string{"socket=" + c.v}); err != nil || p.Socket != c.want {
t.Fatalf("socket=%s: %v, got %q", c.v, err, p.Socket)
}
+71
View File
@@ -209,3 +209,74 @@ func TestResponsesProviderSocketReplyIsAStream(t *testing.T) {
t.Errorf("Content-Type %q", ct)
}
}
// openAIAt adds "oai", a key's provider at OpenAI's own Responses URL
// with Socket sock, whose api.openai.com is connected to the fake f on
// this computer (Resolve, its test certificate let through), so nothing
// reaches the network. It returns the handshakes the fake was asked for.
func openAIAt(t *testing.T, f *fakeSocketBackend, sock string) *atomic.Int32 {
t.Helper()
noRests()
t.Cleanup(noRests)
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
f.path = "/v1/responses"
var asked atomic.Int32
up := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Host != "api.openai.com" {
http.Error(w, "host "+r.Host, http.StatusMisdirectedRequest)
return
}
if strings.EqualFold(r.Header.Get("Upgrade"), "websocket") {
asked.Add(1)
}
f.ServeHTTP(w, r)
}))
t.Cleanup(up.Close)
p := provider.Provider{ID: "oai", Name: "oai", Key: "sk-oai", Models: []string{"m1"}, Responses: "https://api.openai.com/v1", Socket: sock,
InsecureTLS: true, Resolve: map[string][]string{"api.openai.com": {up.Listener.Addr().String()}}}
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
return &asked
}
// KawaiiZapic on X: Codex on an OpenAI API key sent the whole
// conversation up every turn, since Codex says store false and only the
// Responses WebSocket keeps a turn for the next one then. Codex's own
// OpenAI provider speaks that socket to api.openai.com, and so does magpie
// now with Socket unset: the second turn is the new input alone after
// previous_response_id, on the first turn's socket.
func TestOpenAIProviderTurnsGoOverWebSocketByDefault(t *testing.T) {
socketOn(t)
f := &fakeSocketBackend{keep: true, whole: true}
f.frames = keptReply(f)
asked := openAIAt(t, f, "")
relayPost(t, keptTurn("conv-1", "oai/m1", userPing))
relayPost(t, keptTurn("conv-1", "oai/m1", userPing, asstPong, userAgain))
if posts, sockets := f.counts(); posts != 0 || sockets != 2 || asked.Load() != 1 {
t.Fatalf("%d HTTP posts, %d socket turns on %d handshakes; want both turns on one socket", posts, sockets, asked.Load())
}
second := gjson.ParseBytes(f.turn(1).msg)
if got := second.Get("previous_response_id").String(); got != "resp-1" {
t.Errorf("previous_response_id %q, want resp-1: %s", got, f.turn(1).msg)
}
if in := second.Get("input").Array(); len(in) != 1 || in[0].Get("content.0.text").String() != "again" {
t.Errorf("delta input %s, want only the new user message", second.Get("input").Raw)
}
}
// Set off, OpenAI's API is spoken HTTP alone, as before.
func TestOpenAIProviderSocketOffNeverDials(t *testing.T) {
socketOn(t)
f := &fakeSocketBackend{keep: true, whole: true}
f.frames = keptReply(f)
asked := openAIAt(t, f, provider.SocketOff)
relayPost(t, keptTurn("conv-1", "oai/m1", userPing))
relayPost(t, keptTurn("conv-1", "oai/m1", userPing, asstPong, userAgain))
if posts, _ := f.counts(); posts != 2 || asked.Load() != 0 {
t.Fatalf("%d posts, %d handshakes; want HTTP alone", posts, asked.Load())
}
}
+4 -10
View File
@@ -10115,17 +10115,11 @@ function drawEditor(p, presetID) {
// another editor's: no rows for it
const certDraft = draft;
import("./tlscerts.js").then(() => draft === certDraft && tlsCertRows({ p, pr, draft, at: certAt, certTakes, onHTTPS, addressOf, asTyped, show: (f) => { const was = showTLS; showTLS = () => { was(); f(); }; showTLS(); }, save: (f) => { pinBody = f; } }), statusErr);
// Responses over WebSocket (#5781): auto, or the CLI's on kept
// Responses over WebSocket (#5781), its row in socketrow.js
const socketable = () => !p?.account && (p?.preset || pr?.id) !== "google-vertex" && /^\s*https?:\/\//i.test(addressOf("responses"));
{
const [stk, scb] = tick(t("Send Responses turns over WebSocket"), !!draft.socket);
stk.classList.add("socket-tick");
scb.onchange = () => { draft.socket = scb.checked ? (p?.socket || "auto") : ""; };
const srow = field(t("WebSocket"), stk);
showSocket = () => { for (const e of srow) e.style.display = socketable() ? "" : "none"; };
showSocket();
advIn.append(...srow);
}
const sockAt = document.createComment("");
advIn.append(sockAt);
import("./socketrow.js").then(() => draft === certDraft && socketRow({ p, draft, at: sockAt, socketable, addressOf, show: (f) => { showSocket = f; f(); } }), statusErr);
// off, a 429 or quota refusal rests none of its keys (LimitRestOff, zoecats)
if (custom) {
const [rtk, rcb] = tick(t("Set it aside when out of quota or rate limited"), !draft.limitRestOff);
+19
View File
@@ -0,0 +1,19 @@
// A provider editor's WebSocket row under Advanced (#5781): its tick
// sends the Responses turns over the Responses WebSocket. Ticked it saves
// auto, or keeps the CLI's on; unticked it saves "", HTTP alone. OpenAI's
// own API goes over it unset (provider.SocketByDefault, KawaiiZapic on
// X), so there it opens ticked, saves off unticked and "" ticked again.
// app.js imports this when it draws the editor, so it weighs nothing on
// the core; show is handed the row's showSocket.
window.socketRow = function ({ p, draft, at, socketable, addressOf, show }) {
const def = () => /^\s*https:\/\/api\.openai\.com(?:[:/]|\s*$)/i.test(addressOf("responses"));
const [stk, scb] = tick(t("Send Responses turns over WebSocket"), draft.socket ? draft.socket !== "off" : def());
stk.classList.add("socket-tick");
scb.onchange = () => { draft.socket = scb.checked ? (p?.socket === "on" ? "on" : def() ? "" : "auto") : def() ? "off" : ""; };
const srow = field(t("WebSocket"), stk);
at.replaceWith(...srow);
show(() => {
for (const e of srow) e.style.display = socketable() ? "" : "none";
if (!draft.socket) scb.checked = def();
});
};
File diff suppressed because one or more lines are too long
+3 -2
View File
@@ -216,7 +216,8 @@ type providerJSON struct {
// (provider.PinHosts), a preset's pointed at their own server too
TakesServerPin bool `json:"takesServerPin,omitempty"`
// its Responses turns over the Responses WebSocket (provider.Socket,
// #5781): auto, on or ""; TakesSocket: a provider of a key with a
// #5781): auto, on, off or "" (auto on OpenAI's own API, HTTP
// elsewhere: provider.SocketMode); TakesSocket: a provider of a key with a
// Responses URL
Socket string `json:"socket"`
TakesSocket bool `json:"takesSocket"`
@@ -1926,7 +1927,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
// save that leaves it out keeps it
HTTP1 *bool `json:"http1"`
// Socket is how its Responses turns go over the Responses
// WebSocket (#5781): auto, on, or "" for HTTP alone; a save
// WebSocket (#5781): auto, on, off, or "" for its default; a save
// that leaves it out keeps it
Socket *string `json:"socket"`
// LimitRestOff is whether a quota refusal or a 429 leaves it
+14
View File
@@ -59,6 +59,20 @@ func TestProviderSaveSocket(t *testing.T) {
if info("relay").Socket != "auto" {
t.Fatal("ticked in the editor, not saved auto")
}
// KawaiiZapic on X: OpenAI's own API goes over the socket unset, so
// unticked there it is saved off, and ticked again unset
if err := provider.Save(provider.Provider{ID: "oai", Name: "OpenAI", Key: "sk-o", Responses: "https://api.openai.com/v1"}); err != nil {
t.Fatal(err)
}
oai := `{"id":"oai","from":"oai","name":"OpenAI","key":"","responses":"https://api.openai.com/v1","models":[],"headers":{}`
post(oai + `,"socket":"off"}`)
if info("oai").Socket != provider.SocketOff {
t.Fatal("unticked on OpenAI's API, not saved off")
}
post(oai + `,"socket":""}`)
if info("oai").Socket != "" {
t.Fatal("ticked again on OpenAI's API, not saved unset")
}
post(`{"id":"chat","name":"Chat","key":"sk-c","chat":"https://chat.example/v1","icon":"generic","new":true}`)
if info("chat").TakesSocket {
t.Error("a provider without a Responses URL is offered the socket")
+27 -2
View File
@@ -4,7 +4,9 @@
// version", whose tick sends its Responses turns over the Responses
// WebSocket. Ticked it saves auto; one set on from the CLI opens ticked
// and keeps on; unticked it saves off. One without a Responses URL and a
// signed-in account show none, and their Save sends none. Every
// signed-in account show none, and their Save sends none. KawaiiZapic on
// X: OpenAI's own API goes over it unset, so its row opens ticked with
// Advanced shut, unticked saves off and ticked again saves unset. Every
// language, wide and narrow.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
@@ -20,6 +22,7 @@ const base = {
};
const relay = { ...base, id: "relay", name: "Relay Hub", responses: "https://relay.example/v1", takesSocket: true, socket: "" };
const kept = { ...base, id: "kept", name: "Kept Hub", responses: "https://kept.example/v1", takesSocket: true, socket: "on" };
const oai = { ...base, id: "oai", name: "OpenAI Key", responses: "https://api.openai.com/v1", takesSocket: true, socket: "" };
const chat = { ...base, id: "chat", name: "Chat Hub", chat: "https://chat.example/v1", takesSocket: false };
const codex = {
id: "codex", name: "Codex", icon: "codex-color", chat: "", responses: "", anthropic: "", catalog: "",
@@ -29,7 +32,7 @@ const codex = {
};
function serve(lang, posts) {
const providers = { providers: [relay, kept, chat, codex], presets: [], excluded: [], gateway: { running: true, window: true } };
const providers = { providers: [relay, kept, oai, chat, codex], presets: [], excluded: [], gateway: { running: true, window: true } };
const state = { agents: [], profiles: [], settings: { lang, theme: "light" } };
return async (route) => {
const url = new URL(route.request().url());
@@ -134,6 +137,28 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.deepEqual(errors, []);
});
test(`${engine} ${lang} ${width}: OpenAI's own API opens ticked, saves off unticked and unset ticked again`, async (t) => {
const { page, errors, posts, w } = await open(t, "OpenAI Key");
assert.equal(await adv(page).evaluate((d) => d.open), false, "Advanced stays shut for a default");
await unfold(page);
await box(page, w).scrollIntoViewIfNeeded();
assert.equal(await box(page, w).isChecked(), true, "ticked by default");
await box(page, w).uncheck();
let saved = await save(page, posts, w);
assert.equal(saved.body.id, "oai");
assert.equal(saved.body.socket, "off");
await page.locator(".editor .bar").waitFor({ state: "detached" });
await page.locator(".row.provider", { hasText: "OpenAI Key" }).click();
await page.locator(".editor .bar").waitFor();
await unfold(page);
await box(page, w).scrollIntoViewIfNeeded();
await box(page, w).uncheck();
await box(page, w).check();
saved = await save(page, posts, w);
assert.equal(saved.body.socket, "");
assert.deepEqual(errors, []);
});
test(`${engine} ${lang} ${width}: a provider without a Responses URL and a sign-in have no row, nor send one`, async (t) => {
{
const { page, errors, posts, w } = await open(t, "Chat Hub");
+4 -3
View File
@@ -425,9 +425,10 @@ type Provider struct {
// Discord): SocketAuto tries it and falls back to HTTP, and leaves the
// host to HTTP for a while once it refuses the handshake, as
// chatgpt.com is; SocketOn tries it every time and falls back without
// that. "", the default, is HTTP alone. Only a provider of a key with a
// Responses URL takes it (TakesSocket). Set with `magpie provider set
// <id> socket=`.
// that; SocketOff is HTTP alone. "", the default, is auto on OpenAI's
// own API and HTTP alone elsewhere (SocketMode). Only a provider of a
// key with a Responses URL takes it (TakesSocket). Set with `magpie
// provider set <id> socket=`.
Socket string `json:"socket,omitempty"`
// NativeCompaction has Codex's compaction_trigger go to the provider
+42 -6
View File
@@ -9,26 +9,61 @@ import (
// The ways a provider's Socket is set: SocketAuto tries the Responses
// WebSocket and leaves a host that refuses its handshake to HTTP for a
// while; SocketOn tries it every turn. Off is "".
// while; SocketOn tries it every turn; SocketOff is HTTP alone, where
// the default would be the socket. "" is the default (SocketMode).
const (
SocketAuto = "auto"
SocketOn = "on"
SocketOff = "off"
)
// ParseSocket is the Socket v sets: auto, on, or "" for off (off, no,
// default or empty); ok is false for anything else.
// ParseSocket is the Socket v sets: auto, on, off (off, no or false), or
// "" for the default (default or empty); ok is false for anything else.
func ParseSocket(v string) (string, bool) {
switch strings.ToLower(strings.TrimSpace(v)) {
case SocketAuto:
return SocketAuto, true
case SocketOn, "yes", "true":
return SocketOn, true
case "", "off", "no", "false", "default":
case SocketOff, "no", "false":
return SocketOff, true
case "", "default":
return "", true
}
return "", false
}
// SocketMode is how p's Responses turns go: SocketAuto, SocketOn, or ""
// for HTTP alone. A Socket the user set is kept; unset, OpenAI's own API
// (an https Responses URL at api.openai.com) is auto, as Codex's built-in
// OpenAI provider speaks its WebSocket mode to it (supports_websockets in
// codex-rs's create_openai_provider). There a conversation's next turn
// goes as its new input after previous_response_id, even with store
// false, where HTTP sends the whole conversation every turn (KawaiiZapic
// on X). Any other address is HTTP alone unless set.
func (p Provider) SocketMode() string {
switch p.Socket {
case SocketOff:
return ""
case SocketAuto, SocketOn:
return p.Socket
}
if p.SocketByDefault() {
return SocketAuto
}
return ""
}
// SocketByDefault says p's turns go over the Responses WebSocket with
// Socket unset (SocketMode).
func (p Provider) SocketByDefault() bool {
if !p.TakesSocket() || p.PluginProvider() != "" {
return false
}
u, err := url.Parse(strings.TrimSpace(p.Responses))
return err == nil && u.Scheme == "https" && strings.EqualFold(u.Hostname(), "api.openai.com")
}
// TakesSocket says p can have its turns go over the Responses WebSocket
// (Socket): a provider of a key with a Responses URL. A signed-in account
// or a plugin's provider has its own way there.
@@ -61,14 +96,15 @@ func withSocket(ctx context.Context, p Provider) context.Context {
}
func (p Provider) socketAt() (socketAt, bool) {
if p.Socket == "" || !p.TakesSocket() {
mode := p.SocketMode()
if mode == "" || !p.TakesSocket() {
return socketAt{}, false
}
u, err := url.Parse(strings.TrimRight(strings.TrimSpace(p.Responses), "/"))
if err != nil || u.Host == "" || (u.Scheme != "https" && u.Scheme != "http") {
return socketAt{}, false
}
return socketAt{host: u.Host, path: u.Path + "/responses", shun: p.Socket != SocketOn}, true
return socketAt{host: u.Host, path: u.Path + "/responses", shun: mode != SocketOn}, true
}
// SocketTurn says req is a Responses turn that may go over the Responses
+43 -1
View File
@@ -54,9 +54,51 @@ func TestSocketTurn(t *testing.T) {
}
func TestSocketKeptAsSet(t *testing.T) {
for v, want := range map[string]string{"auto": "auto", " On ": "on", "off": "", "": "", "maybe": ""} {
for v, want := range map[string]string{"auto": "auto", " On ": "on", "off": "off", "no": "off", "": "", "default": "", "maybe": ""} {
if got := normalize(Provider{ID: "x", Socket: v}).Socket; got != want {
t.Errorf("%q kept as %q, want %q", v, got, want)
}
}
}
// KawaiiZapic on X: OpenAI's own API takes the Responses WebSocket, as
// Codex's built-in OpenAI provider speaks it, so with Socket unset its
// turns go there (auto); set off they don't, and any other host, a
// signed-in account or plain http stays HTTP alone unless set.
func TestSocketByDefaultOnOpenAI(t *testing.T) {
turn := func(p Provider, u string) (bool, bool) {
t.Helper()
req, err := http.NewRequestWithContext(p.Via(context.Background()), "POST", u, nil)
if err != nil {
t.Fatal(err)
}
return SocketTurn(req)
}
oai := Provider{ID: "openai", Key: "sk", Responses: "https://api.openai.com/v1"}
if got := oai.SocketMode(); got != SocketAuto {
t.Errorf("unset on api.openai.com: %q, want auto", got)
}
if ok, shun := turn(oai, "https://api.openai.com/v1/responses"); !ok || !shun {
t.Errorf("unset on api.openai.com: %v %v, want a turn that shuns", ok, shun)
}
off := oai
off.Socket = SocketOff
if ok, _ := turn(off, "https://api.openai.com/v1/responses"); ok || off.SocketMode() != "" {
t.Error("set off, OpenAI's turns went over the socket")
}
on := oai
on.Socket = SocketOn
if ok, shun := turn(on, "https://api.openai.com/v1/responses"); !ok || shun {
t.Errorf("set on: %v %v", ok, shun)
}
for _, p := range []Provider{
{ID: "relay", Key: "k", Responses: "https://relay.example/v1"},
{ID: "lookalike", Key: "k", Responses: "https://api.openai.com.example/v1"},
{ID: "plain", Key: "k", Responses: "http://api.openai.com/v1"},
{ID: "acct", Responses: "https://api.openai.com/v1", Account: &Account{}},
} {
if p.SocketMode() != "" || p.SocketByDefault() {
t.Errorf("%s: %q by default, want HTTP alone", p.ID, p.SocketMode())
}
}
}