diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index adca00446..d3364fe62 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -346,6 +346,7 @@ and `TestHistoricalWindowHoldsUsesEachWindowsOwnReading`. - 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 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 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 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` (`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 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. @@ -422,6 +423,8 @@ 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' +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 node --test internal/gui/tests/account-alias.test.cjs diff --git a/internal/cli/providers_cli.go b/internal/cli/providers_cli.go index c4d012e09..a8a33c92f 100644 --- a/internal/cli/providers_cli.go +++ b/internal/cli/providers_cli.go @@ -62,6 +62,9 @@ const providerUsage = `usage: while it is busy or briefly rate limited, asking again after a pause (at most 4m); patience=off hands the agent the error at once; 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 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 @@ -905,6 +908,9 @@ func showProviderAsking(p provider.Provider, ask bool) error { if p.NativeCompaction { kv("compaction", "native"+muted.Render(" Codex's own, sealed by the key or account that answers it")) } + if p.Socket != "" { + kv("socket", p.Socket) + } switch { case p.Account != nil: who := p.AccountShown(p.Account.User) @@ -1229,6 +1235,15 @@ func applyPairs(p *provider.Provider, pairs []string) error { default: return fmt.Errorf("additional-tools=on|off|default, not %q", v) } + case "socket": + // its Responses turns over the Responses WebSocket magpie + // speaks to chatgpt.com (#5781): auto leaves a host that + // 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) + } + p.Socket = s case "patience": // how long a request to the provider alone is kept while it // is busy, as a group's Patience (zoecats on Discord) @@ -1374,6 +1389,9 @@ func applyPairs(p *provider.Provider, pairs []string) error { return fmt.Errorf("unknown field %q\n\n%s", k, providerUsage) } } + if p.Socket != "" && !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() { return fmt.Errorf("compaction=native: %s can't carry Codex's own compaction; only a provider with a Responses API (responses=), a ChatGPT account or GitHub Copilot can", p.Name) } diff --git a/internal/cli/socket_cli_test.go b/internal/cli/socket_cli_test.go new file mode 100644 index 000000000..e83421744 --- /dev/null +++ b/internal/cli/socket_cli_test.go @@ -0,0 +1,34 @@ +package cli + +import ( + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// socket= sends a Responses provider's turns over the Responses WebSocket +// (#5781, matrix0487 on Discord): auto, on, or off for HTTP alone. One +// 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", ""}} { + 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) + } + } + p.Socket = "auto" + if err := applyPairs(&p, []string{"socket=sometimes"}); err == nil || p.Socket != "auto" { + t.Fatalf("socket=sometimes taken: %v, %q", err, p.Socket) + } + chat := provider.Provider{ID: "chat", Name: "Chat", Key: "k", Chat: "https://relay.example/v1"} + if err := applyPairs(&chat, []string{"socket=auto"}); err == nil { + t.Fatal("a provider without a Responses URL took socket=auto") + } + if err := applyPairs(&chat, []string{"socket=off"}); err != nil { + t.Fatalf("socket=off refused: %v", err) + } + a := provider.Provider{ID: "codex", Name: "Codex", Account: &provider.Account{}, Responses: "https://x/v1"} + if err := applyPairs(&a, []string{"socket=on"}); err == nil { + t.Fatal("an account took socket=on") + } +} diff --git a/internal/gateway/codex_socket.go b/internal/gateway/codex_socket.go index 6f6e24ef5..e42b863be 100644 --- a/internal/gateway/codex_socket.go +++ b/internal/gateway/codex_socket.go @@ -133,14 +133,32 @@ func shunCodexSocket(host string, why string) { } // codexSocket sends a streamed turn to the ChatGPT backend over its -// WebSocket, and every other request through next. +// WebSocket, and one to a Responses provider whose Socket is set over +// the same WebSocket at its Responses URL (#5781); every other request +// goes through next. type codexSocket struct{ next http.RoundTripper } func (t codexSocket) RoundTrip(req *http.Request) (*http.Response, error) { - if codexSocketOff.Load() || req.Method != http.MethodPost || req.GetBody == nil || - !provider.CodexTurnURL(req.URL) || codexShunned(req.URL.Host) { + if codexSocketOff.Load() || req.Method != http.MethodPost || req.GetBody == nil { return t.next.RoundTrip(req) } + turn, shun := provider.SocketTurn(req) + if !turn || (shun && codexShunned(req.URL.Host)) { + return t.next.RoundTrip(req) + } + res, err := t.overSocket(req, shun) + if res != nil && res.StatusCode == http.StatusOK && res.Header.Get("Content-Type") == "" && + !provider.CodexTurnURL(req.URL) { + // what a Responses provider's stream is said to be over HTTP; + // chatgpt.com's turns go on as they always have + res.Header.Set("Content-Type", "text/event-stream") + } + return res, err +} + +// overSocket is RoundTrip for a turn that may go over the socket; shun +// says a refused handshake leaves the host to HTTP for a while. +func (t codexSocket) overSocket(req *http.Request, shun bool) (*http.Response, error) { body, ok := codexSocketMessage(req) if !ok { return t.next.RoundTrip(req) @@ -172,7 +190,7 @@ func (t codexSocket) RoundTrip(req *http.Request) (*http.Response, error) { if codexMessageTooBig(req.URL.Host, len(msg)) { return t.next.RoundTrip(req) } - res, err := t.socket(req, msg, key, shape) + res, err := t.socket(req, msg, key, shape, shun) if errors.Is(err, errCodexSocketFallBack) { return t.next.RoundTrip(req) } @@ -299,8 +317,10 @@ func codexSocketHeaders(req *http.Request) http.Header { } // socket opens a socket for the turn and sends msg on it; one that -// carries on with key's conversation is kept for its next turn. -func (t codexSocket) socket(req *http.Request, msg []byte, key string, shape *codexTurnShape) (*http.Response, error) { +// carries on with key's conversation is kept for its next turn. A host +// that refuses the handshake is left to HTTP for a while when shun says +// so (a provider's Socket "on" never is). +func (t codexSocket) socket(req *http.Request, msg []byte, key string, shape *codexTurnShape, shun bool) (*http.Response, error) { // the socket may outlive the request, kept for the next turn: only // the handshake ends with it ctx, cancel := context.WithCancel(context.WithoutCancel(req.Context())) @@ -320,6 +340,8 @@ func (t codexSocket) socket(req *http.Request, msg []byte, key string, shape *co return nil, req.Context().Err() } switch { + case !shun: + // tried again next turn case hs == nil: shunCodexSocket(u.Host, err.Error()) case hs.StatusCode == http.StatusUnauthorized || hs.StatusCode == http.StatusTooManyRequests || diff --git a/internal/gateway/codex_socket_keep.go b/internal/gateway/codex_socket_keep.go index 8abc70f70..3505bed15 100644 --- a/internal/gateway/codex_socket_keep.go +++ b/internal/gateway/codex_socket_keep.go @@ -109,7 +109,9 @@ func codexKeepKey(req *http.Request, body []byte) string { } h := sha256.New() for _, v := range []string{ - req.URL.Host, req.URL.Path, req.Header.Get("Authorization"), req.Header.Get("Chatgpt-Account-Id"), + req.URL.Scheme, req.URL.Host, req.URL.Path, req.Header.Get("Authorization"), req.Header.Get("Chatgpt-Account-Id"), + // a Responses provider's key may be said in either (#5781) + req.Header.Get("X-Api-Key"), req.Header.Get("Api-Key"), sid, tid, req.Header.Get("X-Openai-Subagent"), req.Header.Get("X-Codex-Parent-Thread-Id"), } { h.Write([]byte(v)) diff --git a/internal/gateway/codex_socket_test.go b/internal/gateway/codex_socket_test.go index c6a6a06b7..8010d6aa5 100644 --- a/internal/gateway/codex_socket_test.go +++ b/internal/gateway/codex_socket_test.go @@ -1,6 +1,7 @@ package gateway import ( + "cmp" "errors" "io" "net/http" @@ -45,10 +46,14 @@ type fakeSocketBackend struct { // keep reads the socket's next turn after a reply, as the backend // does, until the client closes it keep bool + // path is the Responses path it answers at, chatgpt.com's when ""; + // whole has its HTTP reply run to response.completed + path string + whole bool } func (f *fakeSocketBackend) ServeHTTP(w http.ResponseWriter, r *http.Request) { - if !strings.HasSuffix(r.URL.Path, "/backend-api/codex/responses") { + if !strings.HasSuffix(r.URL.Path, cmp.Or(f.path, "/backend-api/codex/responses")) { http.NotFound(w, r) return } @@ -102,6 +107,14 @@ func (f *fakeSocketBackend) ServeHTTP(w http.ResponseWriter, r *http.Request) { f.mu.Lock() f.posts++ f.mu.Unlock() + if f.whole { + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse( + `event: response.created`+"\n"+`data: {"type":"response.created","response":{"id":"h1"}}`, + `event: response.output_text.delta`+"\n"+`data: {"type":"response.output_text.delta","delta":"pong"}`, + `event: response.completed`+"\n"+`data: {"type":"response.completed","response":{"id":"h1","usage":{"input_tokens":7,"output_tokens":1}}}`)) + return + } w.Header()["Content-Type"] = nil io.WriteString(w, sse( `event: response.created`+"\n"+`data: {"type":"response.created","response":{"id":"r1"}}`, diff --git a/internal/gateway/responses_socket_test.go b/internal/gateway/responses_socket_test.go new file mode 100644 index 000000000..52fefbeb3 --- /dev/null +++ b/internal/gateway/responses_socket_test.go @@ -0,0 +1,211 @@ +package gateway + +import ( + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync/atomic" + "testing" + + "github.com/coder/websocket" + "github.com/tidwall/gjson" + + "github.com/yetone/magpie/internal/provider" +) + +// faithleysath (#5781, from matrix0487 on Discord): a Responses API +// provider, a relay that speaks the Responses WebSocket as chatgpt.com +// does, can have its turns go over that socket with `magpie provider set +// socket=auto|on`. These tests are those turns against a fake +// upstream on this computer. + +// relaySocket adds a Responses provider "relay" at the fake upstream f +// answers (counting every handshake asked for, a refused one's too) with +// Socket sock, and returns the upstream. +func relaySocket(t *testing.T, f *fakeSocketBackend, sock string) (*httptest.Server, *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.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.EqualFold(r.Header.Get("Upgrade"), "websocket") { + asked.Add(1) + } + f.ServeHTTP(w, r) + })) + t.Cleanup(up.Close) + addRelay(t, "relay", up.URL, sock) + return up, &asked +} + +func addRelay(t *testing.T, id, base, sock string) { + t.Helper() + p := provider.Provider{ID: id, Name: id, Key: "sk-" + id, Models: []string{"m1"}, Responses: base + "/v1", Socket: sock} + if err := provider.Save(p); err != nil { + t.Fatal(err) + } +} + +func relayPost(t *testing.T, body string) *httptest.ResponseRecorder { + t.Helper() + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/v1/responses", strings.NewReader(body)) + New().Handler().ServeHTTP(rec, req) + if rec.Code != 200 || !strings.Contains(rec.Body.String(), "pong") || + !strings.Contains(rec.Body.String(), "event: response.completed\n") { + t.Fatalf("%d, a reply without its end: %s", rec.Code, rec.Body.String()) + } + return rec +} + +const relayPing = `{"model":"relay/m1","stream":true,"input":"ping"}` + +func TestResponsesProviderTurnGoesOverWebSocket(t *testing.T) { + socketOn(t) + f := &fakeSocketBackend{whole: true} + f.frames = keptReply(f) + relaySocket(t, f, provider.SocketAuto) + + rec := relayPost(t, relayPing) + if posts, sockets := f.counts(); posts != 0 || sockets != 1 { + t.Fatalf("%d HTTP posts, %d socket turns; want the turn on the socket", posts, sockets) + } + if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "text/event-stream") { + t.Errorf("Content-Type %q, want the stream's", ct) + } + turn := f.turn(0) + if got := turn.header.Get("Authorization"); got != "Bearer sk-relay" { + t.Errorf("handshake Authorization %q, want the provider's key", got) + } + if got := turn.header.Get("OpenAI-Beta"); got != codexSocketBeta { + t.Errorf("OpenAI-Beta %q", got) + } + m := gjson.ParseBytes(turn.msg) + if m.Get("type").String() != "response.create" || m.Get("model").String() != "m1" || m.Get("input").String() != "ping" { + t.Errorf("message %s", turn.msg) + } +} + +// A provider without Socket never dials one, the default; not even +// when another provider on the same host has it set. +func TestResponsesProviderWithoutSocketNeverDials(t *testing.T) { + socketOn(t) + f := &fakeSocketBackend{whole: true} + f.frames = keptReply(f) + up, asked := relaySocket(t, f, "") + addRelay(t, "near", up.URL, provider.SocketOn) + + relayPost(t, relayPing) + if posts, _ := f.counts(); posts != 1 || asked.Load() != 0 { + t.Fatalf("%d posts, %d handshakes; want HTTP alone", posts, asked.Load()) + } + relayPost(t, strings.Replace(relayPing, "relay/m1", "near/m1", 1)) + if posts, sockets := f.counts(); posts != 1 || sockets != 1 { + t.Fatalf("the provider with Socket: %d posts, %d socket turns", posts, sockets) + } + relayPost(t, relayPing) + if posts, _ := f.counts(); posts != 2 || asked.Load() != 1 { + t.Fatalf("after the other's socket: %d posts, %d handshakes; want HTTP alone", posts, asked.Load()) + } +} + +// auto: a refused handshake has the turn go over HTTP, and the host's +// next turns too for a while, unasked. +func TestResponsesProviderSocketRefusedAutoShuns(t *testing.T) { + socketOn(t) + f := &fakeSocketBackend{whole: true, refuse: http.StatusForbidden} + up, asked := relaySocket(t, f, provider.SocketAuto) + relayPost(t, relayPing) + relayPost(t, relayPing) + if posts, _ := f.counts(); posts != 2 || asked.Load() != 1 { + t.Fatalf("%d posts, %d handshakes; want both over HTTP after one refusal", posts, asked.Load()) + } + if u, _ := url.Parse(up.URL); !codexShunned(u.Host) { + t.Error("the host isn't left to HTTP") + } +} + +// on: a refused handshake has the turn go over HTTP, and the next turn +// asks for the socket again. +func TestResponsesProviderSocketRefusedOnTriesAgain(t *testing.T) { + socketOn(t) + f := &fakeSocketBackend{whole: true, refuse: http.StatusForbidden} + up, asked := relaySocket(t, f, provider.SocketOn) + relayPost(t, relayPing) + relayPost(t, relayPing) + if posts, _ := f.counts(); posts != 2 || asked.Load() != 2 { + t.Fatalf("%d posts, %d handshakes; want both over HTTP, each asking first", posts, asked.Load()) + } + if u, _ := url.Parse(up.URL); codexShunned(u.Host) { + t.Error("on left the host to HTTP") + } +} + +// A socket that closes before the reply's first event has the turn go +// over HTTP, nothing of it lost. +func TestResponsesProviderSocketClosedEarlyGoesOverHTTP(t *testing.T) { + socketOn(t) + f := &fakeSocketBackend{whole: true, closeWith: websocket.StatusTryAgainLater} + f.frames = func(socketTurn) []string { return nil } + relaySocket(t, f, provider.SocketAuto) + rec := relayPost(t, relayPing) + if posts, sockets := f.counts(); posts != 1 || sockets != 1 { + t.Fatalf("%d posts, %d socket turns; want the socket tried, then HTTP", posts, sockets) + } + if n := strings.Count(rec.Body.String(), "event: response.created\n"); n != 1 { + t.Errorf("%d response.created; want the HTTP reply alone: %s", n, rec.Body.String()) + } +} + +// A conversation's next turn goes on its kept socket as a delta after +// previous_response_id, as chatgpt.com's does. +func TestResponsesProviderKeptSocketSendsTheDelta(t *testing.T) { + socketOn(t) + f := &fakeSocketBackend{keep: true, whole: true} + f.frames = keptReply(f) + relaySocket(t, f, provider.SocketAuto) + + relayPost(t, keptTurn("conv-1", "relay/m1", userPing)) + relayPost(t, keptTurn("conv-1", "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 turns on one socket", posts, sockets, f.opened()) + } + 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) + } +} + +// The socket's reply is said to be the event stream it is, as the +// provider's HTTP reply is, for whatever reads its headers. +func TestResponsesProviderSocketReplyIsAStream(t *testing.T) { + socketOn(t) + f := &fakeSocketBackend{whole: true, path: "/v1/responses"} + f.frames = keptReply(f) + up := httptest.NewServer(f) + t.Cleanup(up.Close) + p := provider.Provider{ID: "relay", Key: "k", Responses: up.URL + "/v1", Socket: provider.SocketAuto} + body := relayPing + req, err := http.NewRequestWithContext(p.Via(t.Context()), "POST", up.URL+"/v1/responses", strings.NewReader(body)) + if err != nil { + t.Fatal(err) + } + res, err := codexSocket{next: http.DefaultTransport}.RoundTrip(req) + if err != nil { + t.Fatal(err) + } + defer res.Body.Close() + if _, sockets := f.counts(); sockets != 1 { + t.Fatalf("%d socket turns", sockets) + } + if ct := res.Header.Get("Content-Type"); ct != "text/event-stream" { + t.Errorf("Content-Type %q", ct) + } +} diff --git a/internal/gateway/upstream_transport.go b/internal/gateway/upstream_transport.go index 40dbcd6e9..553e98a8e 100644 --- a/internal/gateway/upstream_transport.go +++ b/internal/gateway/upstream_transport.go @@ -23,7 +23,8 @@ var upstreamTLS *tls.Config // upstreamTransport is the gateway's transport to the vendors: a provider // with a proxy of its own is sent through a transport kept for that proxy // (#237), and the ChatGPT backend over HTTP/1.1 (netproxy.HTTP1), a -// streamed turn to it over its WebSocket (codexSocket). Every +// streamed turn to it over its WebSocket (codexSocket), as one to a +// Responses provider whose Socket is set is (#5781). Every // other vendor is spoken HTTP/2 to wherever it offers it. A large body // whose connection was dropped for a lost ping goes again through a // transport that does not ping (#3909), and so do the large bodies after diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index e329b4523..2a7a0b65b 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -6076,13 +6076,7 @@ function providersWhileFetching() { }, 2500); } -// What the vendors' own status pages say of the APIs the providers call -// (#971, emo172): a vendor's API degraded or down is marked on its -// providers' rows and usage cards, so its outage isn't taken for a sign-in -// or quota problem. The gateway reads each page at most once in five -// minutes; it is asked when the Providers or Usage page loads, and again -// every five minutes while one stays open. A page that couldn't be read -// marks nothing: unknown is not "all well", and not an outage either. +// vendors' status pages (#971): an API down is marked on its rows; unread marks nothing let upstream = null, upstreamAsking = null; function loadUpstream() { if (upstreamAsking) return upstreamAsking; @@ -7979,7 +7973,7 @@ function advancedSet(d, p) { !!d.proxyMode || Object.values(d.accountProxies || {}).some((x) => x?.mode) || [d.concurrency, d.maxAccounts, d.queueLimit, d.queueWait, d.maxRPM, d.priceRate, d.contexts, d.outputs, d.compacts].some((v) => String(v ?? "").trim()) || !!d.rateWindows?.length || - !!(d.searches || d.authHeader || d.passUserAgent === false || d.unredacted || d.countFree || d.pinUpstream || d.nativeCompaction || d.balanceToken || d.limitRestOff || d.http1 || d.imageFilesOff || d.passErrors) || + !!(d.searches || d.authHeader || d.passUserAgent === false || d.unredacted || d.countFree || d.pinUpstream || d.nativeCompaction || d.balanceToken || d.limitRestOff || d.http1 || d.socket || d.imageFilesOff || d.passErrors) || !!d.fallback?.length || !!p?.balanceToken?.set; } function priceRateError(ed) { @@ -8179,13 +8173,7 @@ function accountProxiesOfDraft() { return { map: out }; } -// Custom request headers: the draft keeps them as an ordered [name, value, -// json?] list so a half-typed row (and its open JSON editor) survives a -// re-render; headersOf folds that back into the object the backend stores, -// dropping rows with an empty name or value (a suggested header left unfilled -// is not sent), keeping the last of two rows that name one header in any -// case, and minifying any value that parses as JSON — a header value is one -// line, so pretty-printing is display-only. +// headers as ordered [name, value, json?] rows that survive a redraw; headersOf folds them back function headerRows(obj) { return Object.entries(obj || {}).map(([k, v]) => [k, v, false]); } @@ -9265,7 +9253,7 @@ function baseAPIOf(p) { // draftOf is a saved provider as its editor's form holds it. function draftOf(p) { - return { id: p.id, name: p.name, preset: p.preset, chat: p.chat, responses: p.responses, anthropic: p.anthropic, gemini: p.gemini || "", catalog: p.catalog, decide: p.decide || "", key: "", api: baseAPIOf(p), chosen: pickedOf(p), none: !!p.noModels, best: !!p.bestInFamily, extra: [], headers: headerRows(p.headers), extraBody: extraBodyText(p.extraBody), replyHeaders: (p.replyHeaders || []).join(", "), passHeaders: (p.passHeaders || []).join(", "), icon: p.icon || "", iconFrom: p.iconFrom || "", fallback: [...(p.fallback || [])], unlisted: !!p.unlisted, hiddenDrawers: [...(p.hiddenDrawers || [])], hiddenVideomakers: [...(p.hiddenVideomakers || [])], searches: !!p.searches, unredacted: !!p.unredacted, countFree: !!p.countFree, insecureTLS: !!p.insecureTLS, http1: !!p.http1, limitRestOff: !!p.limitRestOff, passErrors: !!p.passErrors, imageFilesOff: !!p.imageFilesOff, nativeCompaction: !!p.nativeCompaction, passUserAgent: p.passUserAgent !== false, pinUpstream: !!p.pinUpstream, authHeader: p.authHeader || "", balanceURL: p.balanceURL || "", balancePath: p.balancePath || "", balanceMethod: p.balanceMethod || "", modelsURL: p.modelsURL || "", listOff: !!p.listOff, contexts: contextsText(p.contexts), outputs: contextsText(p.outputs), compacts: contextsText(p.compacts), keysUrl: p.keysUrl || "", ...proxyDraft(p), ...concurrencyDraft(p), rateWindows: (p.rateWindows || []).map((w) => ({ ...w })) }; + return { id: p.id, name: p.name, preset: p.preset, chat: p.chat, responses: p.responses, anthropic: p.anthropic, gemini: p.gemini || "", catalog: p.catalog, decide: p.decide || "", key: "", api: baseAPIOf(p), chosen: pickedOf(p), none: !!p.noModels, best: !!p.bestInFamily, extra: [], headers: headerRows(p.headers), extraBody: extraBodyText(p.extraBody), replyHeaders: (p.replyHeaders || []).join(", "), passHeaders: (p.passHeaders || []).join(", "), icon: p.icon || "", iconFrom: p.iconFrom || "", fallback: [...(p.fallback || [])], unlisted: !!p.unlisted, hiddenDrawers: [...(p.hiddenDrawers || [])], hiddenVideomakers: [...(p.hiddenVideomakers || [])], searches: !!p.searches, unredacted: !!p.unredacted, countFree: !!p.countFree, insecureTLS: !!p.insecureTLS, http1: !!p.http1, socket: p.socket || "", limitRestOff: !!p.limitRestOff, passErrors: !!p.passErrors, imageFilesOff: !!p.imageFilesOff, nativeCompaction: !!p.nativeCompaction, passUserAgent: p.passUserAgent !== false, pinUpstream: !!p.pinUpstream, authHeader: p.authHeader || "", balanceURL: p.balanceURL || "", balancePath: p.balancePath || "", balanceMethod: p.balanceMethod || "", modelsURL: p.modelsURL || "", listOff: !!p.listOff, contexts: contextsText(p.contexts), outputs: contextsText(p.outputs), compacts: contextsText(p.compacts), keysUrl: p.keysUrl || "", ...proxyDraft(p), ...concurrencyDraft(p), rateWindows: (p.rateWindows || []).map((w) => ({ ...w })) }; } // duplicateProvider opens the Add form on a copy of p, its key p's unless another is pasted (#268). @@ -9433,6 +9421,7 @@ function drawEditor(p, presetID) { // the Compaction row, shown while the provider has a Responses API // (Provider.CarriesCompaction): Codex's own compaction can go only there let showCompaction = () => {}; + let showSocket = () => {}; const carriesCompaction = () => !!((draft.responses ?? (isNew && pr ? pr.responses : "")) || "").trim(); if (custom) { name = input(draft.name, t("e.g. My Relay")); @@ -9474,6 +9463,7 @@ function drawEditor(p, presetID) { showTLS(); showAuth(); showCompaction(); + showSocket(); }; queueMicrotask(() => slide(seg, "api")); url = input(draft[apiField[draft.api]], urlHint(draft.api), "url"); @@ -9481,7 +9471,7 @@ function drawEditor(p, presetID) { url.oninput = () => { draft[apiField[draft.api]] = url.value; if (carried) { draft[carried.from] = carried.value; carried = null; fillEndpoints(); } - showSearch(); showLocal(); showTLS(); showAuth(); showCompaction(); + showSearch(); showLocal(); showTLS(); showAuth(); showCompaction(); showSocket(); }; const urlWrap = el("div", "stack"); urlWrap.append(seg, url); @@ -9639,7 +9629,7 @@ function drawEditor(p, presetID) { if (draft.chat === undefined) { draft.chat = p?.chat || ""; draft.responses = p?.responses || ""; } endpoint = input(draft.chat || draft.responses || "", pr.endpoint, "url"); endpoint.classList.add("endpoint"); - endpoint.oninput = () => { draft.chat = draft.responses = endpoint.value.trim(); refreshEndpoints(); showCompaction(); }; + endpoint.oninput = () => { draft.chat = draft.responses = endpoint.value.trim(); refreshEndpoints(); showCompaction(); showSocket(); }; ed.append(...field(t("Endpoint"), endpoint, pr.endpointHint ? t(pr.endpointHint) : "")); } @@ -9877,6 +9867,17 @@ function drawEditor(p, presetID) { ed.append(...row); advIn.append(...hrow); } + // Responses over WebSocket (#5781): auto, or the CLI's on kept + 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); + } // 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); @@ -10128,7 +10129,7 @@ function drawEditor(p, presetID) { const add = (label, key, ph, hint) => { if (apiField[draft.api] === key) return; const i = input(draft[key], ph, "url"); - i.oninput = () => { draft[key] = i.value; if (carried?.from === key) carried = null; showSearch(); showLocal(); showTLS(); showAuth(); showCompaction(); draft.onModelPrefs?.(); }; + i.oninput = () => { draft[key] = i.value; if (carried?.from === key) carried = null; showSearch(); showLocal(); showTLS(); showAuth(); showCompaction(); showSocket(); draft.onModelPrefs?.(); }; eps.append(...field(t(label), i, t(hint))); }; add("OpenAI URL", "chat", "https://…/v1", "if the vendor also serves chat completions"); @@ -10256,6 +10257,7 @@ function drawEditor(p, presetID) { body.unredacted = !!draft.unredacted && unmaskable(); body.countFree = !!draft.countFree; if (tlsTakes()) { body.insecureTLS = !!draft.insecureTLS && onHTTPS(); body.http1 = !!draft.http1 && onHTTPS(); } + if (socketable()) body.socket = draft.socket || ""; if (custom) body.limitRestOff = !!draft.limitRestOff; if (p?.takesImageFiles) body.imageFilesOff = !!draft.imageFilesOff; if (p ? p.takesPassErrors : custom) body.passErrors = !!draft.passErrors; @@ -15435,14 +15437,7 @@ function moveWhy(m, p) { return m.error || ""; } -// renderMove: which runs the subscription, magpie's built-in or its -// community plugin, and the move onto the plugin; the built-ins are -// retired, so a moved one has no way back. The editor stays open -// through it: the button says what it is doing, a failure is said under -// it, and on success the field turns over where the reader is. -// moveSaid keeps both through a redraw mid-move (an allowance landing): -// drawn from the provider alone, the button took presses again and the -// failure was said into a field drawn over. +// renderMove: the move onto the plugin; moveSaid keeps its state through a redraw const moveSaid = {}; // provider id → { busy } or { why } function renderMove(p) { const m = p.move; diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 9044f951c..cc78ea5ef 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -4164,6 +4164,8 @@ const I18N = { "Certificate": "证书", "For your own server with a self-signed certificate or one from your company's CA. magpie then can't tell it from another machine answering at its address: turn it on only on a network you trust.": "用于你自己的服务器,证书是自签名的或来自公司内部 CA。开启后 magpie 无法分辨应答的是它本身还是同一地址上的另一台机器:只在你信任的网络中开启。", "HTTP/1.1 only": "仅 HTTP/1.1", + "Send Responses turns over WebSocket": "通过 WebSocket 发送 Responses 请求", + "WebSocket": "WebSocket", "HTTP version": "HTTP 版本", "Codex compacts on this provider": "Codex 在此服务商上原生压缩", "Codex's compaction is asked of this provider as Codex sent it, and the summary it seals goes back to Codex unchanged. Off, magpie writes the summary. A conversation compacted this way continues only on this provider and account: another is refused with an error, never sent without the context.": "Codex 的压缩请求原样交给此服务商,它加密的摘要原样还给 Codex。关闭时由 magpie 写摘要。这样压缩过的对话只能在此服务商和账号上继续:换到别处会报错说明,绝不丢掉上下文发出。", @@ -8902,6 +8904,8 @@ const I18N = { "Certificate": "憑證", "For your own server with a self-signed certificate or one from your company's CA. magpie then can't tell it from another machine answering at its address: turn it on only on a network you trust.": "用於你自己的伺服器,憑證是自簽的或來自公司內部 CA。開啟後 magpie 無法分辨應答的是它本身還是同一位址上的另一台機器:只在你信任的網路中開啟。", "HTTP/1.1 only": "僅 HTTP/1.1", + "Send Responses turns over WebSocket": "透過 WebSocket 傳送 Responses 請求", + "WebSocket": "WebSocket", "HTTP version": "HTTP 版本", "Codex compacts on this provider": "Codex 在此服務商上原生壓縮", "Codex's compaction is asked of this provider as Codex sent it, and the summary it seals goes back to Codex unchanged. Off, magpie writes the summary. A conversation compacted this way continues only on this provider and account: another is refused with an error, never sent without the context.": "Codex 的壓縮請求原樣交給此服務商,它加密的摘要原樣還給 Codex。關閉時由 magpie 寫摘要。這樣壓縮過的對話只能在此服務商和帳號上繼續:換到別處會報錯說明,絕不丟掉上下文送出。", @@ -13656,6 +13660,8 @@ const I18N = { "Certificate": "証明書", "For your own server with a self-signed certificate or one from your company's CA. magpie then can't tell it from another machine answering at its address: turn it on only on a network you trust.": "自己署名証明書や社内 CA の証明書を使う自分のサーバー向けです。オンにすると、magpie はそのアドレスで応答しているのが本物か別のマシンかを見分けられません。信頼できるネットワークでのみオンにしてください。", "HTTP/1.1 only": "HTTP/1.1 のみ", + "Send Responses turns over WebSocket": "Responses のリクエストを WebSocket で送る", + "WebSocket": "WebSocket", "HTTP version": "HTTP バージョン", "Codex compacts on this provider": "Codex のコンパクションをこのプロバイダーで行う", "Codex's compaction is asked of this provider as Codex sent it, and the summary it seals goes back to Codex unchanged. Off, magpie writes the summary. A conversation compacted this way continues only on this provider and account: another is refused with an error, never sent without the context.": "Codex のコンパクション要求をそのままこのプロバイダーに送り、暗号化された要約をそのまま Codex に返します。オフのときは magpie が要約を書きます。こうしてコンパクションした会話は、このプロバイダーとアカウントでのみ続けられます。他へはエラーで断り、コンテキストを落として送ることはしません。", @@ -18425,6 +18431,8 @@ const I18N = { "Certificate": "Zertifikat", "For your own server with a self-signed certificate or one from your company's CA. magpie then can't tell it from another machine answering at its address: turn it on only on a network you trust.": "Für Ihren eigenen Server mit selbstsigniertem Zertifikat oder einem Ihrer Firmen-CA. magpie kann ihn dann nicht von einem anderen Rechner unterscheiden, der unter seiner Adresse antwortet: nur in einem Netzwerk einschalten, dem Sie vertrauen.", "HTTP/1.1 only": "Nur HTTP/1.1", + "Send Responses turns over WebSocket": "Responses-Anfragen über WebSocket senden", + "WebSocket": "WebSocket", "HTTP version": "HTTP-Version", "Codex compacts on this provider": "Codex kompaktiert bei diesem Anbieter", "Codex's compaction is asked of this provider as Codex sent it, and the summary it seals goes back to Codex unchanged. Off, magpie writes the summary. A conversation compacted this way continues only on this provider and account: another is refused with an error, never sent without the context.": "Codex’ Kompaktierung geht so an diesen Anbieter, wie Codex sie sendet, und die versiegelte Zusammenfassung kommt unverändert zu Codex zurück. Aus: magpie schreibt die Zusammenfassung. Ein so kompaktiertes Gespräch geht nur bei diesem Anbieter und Konto weiter: ein anderer wird mit einem Fehler abgelehnt, nie ohne den Kontext angefragt.", diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 8be27ca0f..7f4816df8 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -136,6 +136,11 @@ type providerJSON struct { // spoken HTTP/1.1 to, never HTTP/2 (provider.HTTP1); taken where // TakesInsecureTLS is HTTP1 bool `json:"http1"` + // its Responses turns over the Responses WebSocket (provider.Socket, + // #5781): auto, on or ""; TakesSocket: a provider of a key with a + // Responses URL + Socket string `json:"socket"` + TakesSocket bool `json:"takesSocket"` // asked as usual after a quota refusal or a 429, never set aside for // it (provider.LimitRestOff) LimitRestOff bool `json:"limitRestOff"` @@ -771,7 +776,7 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs ID: p.ID, Name: p.Name, Icon: p.Icon, IconFrom: p.IconFrom, Preset: p.Preset, Host: p.Host(), Chat: p.Chat, Responses: p.Responses, Anthropic: p.Anthropic, Gemini: p.Gemini, Decide: p.Decide, BaseAPI: p.BaseAPI, ModelTest: p.ModelTest(), TestsAs: p.TestClients(), DecideTest: p.AsksDecideModels(), MarksKinds: p.MarksKinds(), Catalog: p.Catalog, Website: p.Website, KeysURL: p.KeysURL, - Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountWindowAmounts: p.AccountWindowAmounts, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, ReplyHeaders: p.ReplyHeaders, PassHeaders: p.PassHeaders, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, CountFree: p.CountFree, InsecureTLS: p.InsecureTLS, TakesInsecureTLS: p.TakesInsecureTLS(), HTTP1: p.HTTP1, LimitRestOff: p.LimitRestOff, ImageFilesOff: p.ImageFilesOff, TakesImageFiles: p.TakesImageFiles(), NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: !p.MagpieUserAgent, OwnClient: p.OwnClient(), PassErrors: p.PassErrors, TakesPassErrors: p.TakesPassErrors(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, BalanceMethod: p.BalanceMethod, ModelsURL: p.ModelsURL, ListOff: p.ListsOff(), TakesListOff: p.Account == nil && !p.IsPlugin() && !p.DecideOnly(), TakesModelHeaders: p.Account == nil, DecideAPIKind: p.DecideAPIKind(), + Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountWindowAmounts: p.AccountWindowAmounts, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, ReplyHeaders: p.ReplyHeaders, PassHeaders: p.PassHeaders, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, CountFree: p.CountFree, InsecureTLS: p.InsecureTLS, TakesInsecureTLS: p.TakesInsecureTLS(), HTTP1: p.HTTP1, Socket: p.Socket, TakesSocket: p.TakesSocket(), LimitRestOff: p.LimitRestOff, ImageFilesOff: p.ImageFilesOff, TakesImageFiles: p.TakesImageFiles(), NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: !p.MagpieUserAgent, OwnClient: p.OwnClient(), PassErrors: p.PassErrors, TakesPassErrors: p.TakesPassErrors(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, BalanceMethod: p.BalanceMethod, ModelsURL: p.ModelsURL, ListOff: p.ListsOff(), TakesListOff: p.Account == nil && !p.IsPlugin() && !p.DecideOnly(), TakesModelHeaders: p.Account == nil, DecideAPIKind: p.DecideAPIKind(), Ready: p.Ready(), Chosen: p.PicksOf(avail), Agents: make([]providerAgent, 0, len(agents)), Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, UseFirst: p.UseFirst, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, RestartApp: p.RestartApp, Self: p.SelfAnswered(), KeepSelf: p.KeepSelf, CapStop: p.CapStop, CapCareful: p.CapCareful, Unlisted: p.Unlisted, NoModels: p.ServesNone(), BestInFamily: p.BestInFamily && len(p.Models) == 0 && !p.NoModels, Off: p.Off, Contexts: p.Contexts, MaxConcurrency: p.MaxConcurrency, PluginConcurrency: p.PluginConcurrency(), MaxAccounts: p.MaxAccounts, PluginAccounts: p.PluginAtOnce(), PriceRate: p.PriceRate, @@ -1530,6 +1535,10 @@ func providerRoutes(mux *http.ServeMux, w Windows) { // HTTP1 is whether its own hosts are spoken HTTP/1.1 to; a // 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 + // that leaves it out keeps it + Socket *string `json:"socket"` // LimitRestOff is whether a quota refusal or a 429 leaves it // asked as usual; a save that leaves it out keeps it LimitRestOff *bool `json:"limitRestOff"` @@ -1960,6 +1969,9 @@ func providerRoutes(mux *http.ServeMux, w Windows) { if req.HTTP1 != nil { in.HTTP1 = *req.HTTP1 } + if req.Socket != nil { + in.Socket, _ = provider.ParseSocket(*req.Socket) + } if req.LimitRestOff != nil { in.LimitRestOff = *req.LimitRestOff } @@ -2006,6 +2018,11 @@ func providerRoutes(mux *http.ServeMux, w Windows) { } else if old != nil { in.HTTP1 = old.HTTP1 } + if req.Socket != nil { + in.Socket, _ = provider.ParseSocket(*req.Socket) + } else if old != nil { + in.Socket = old.Socket + } if req.LimitRestOff != nil { in.LimitRestOff = *req.LimitRestOff } else if old != nil { diff --git a/internal/gui/socket_test.go b/internal/gui/socket_test.go new file mode 100644 index 000000000..a498d7034 --- /dev/null +++ b/internal/gui/socket_test.go @@ -0,0 +1,66 @@ +package gui + +import ( + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// #5781: a provider's Socket, set with `magpie provider set +// socket=on`, opens in the editor as set, a Save that leaves it out keeps +// it, and the editor's tick saves it either way. +func TestProviderSaveSocket(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + t.Setenv("USERPROFILE", os.Getenv("HOME")) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + mux := http.NewServeMux() + providerRoutes(mux, nil) + post := func(body string) { + t.Helper() + w := httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/provider/save", strings.NewReader(body))) + if w.Code != 200 { + t.Fatalf("%d %s", w.Code, w.Body.String()) + } + } + info := func(id string) providerJSON { + t.Helper() + p, err := provider.Find(id) + if err != nil { + t.Fatal(err) + } + in := providerInfo(*p, nil) + if in.Socket != p.Socket { + t.Fatalf("%s: the editor is shown %q, saved %q", id, in.Socket, p.Socket) + } + return in + } + if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "sk-r", Responses: "https://relay.example/v1", Socket: provider.SocketOn}); err != nil { + t.Fatal(err) + } + if got := info("relay"); !got.TakesSocket || got.Socket != "on" { + t.Fatalf("set on from the CLI: takes %v, shown %q", got.TakesSocket, got.Socket) + } + edit := `{"id":"relay","from":"relay","name":"Relay","key":"","responses":"https://relay.example/v1","models":[],"headers":{}` + post(edit + `}`) + if info("relay").Socket != "on" { + t.Fatal("a Save that left it out dropped the CLI's on") + } + post(edit + `,"socket":""}`) + if info("relay").Socket != "" { + t.Fatal("unticked in the editor, still saved") + } + post(edit + `,"socket":"auto"}`) + if info("relay").Socket != "auto" { + t.Fatal("ticked in the editor, not saved auto") + } + 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") + } +} diff --git a/internal/gui/tests/provider-socket.test.cjs b/internal/gui/tests/provider-socket.test.cjs new file mode 100644 index 000000000..1608d9983 --- /dev/null +++ b/internal/gui/tests/provider-socket.test.cjs @@ -0,0 +1,152 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// #5781 (faithleysath, from matrix0487 on Discord): a provider with a +// Responses URL has a "WebSocket" row under Advanced, beside "HTTP +// 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 +// language, wide and narrow. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const base = { + icon: "generic", chat: "", responses: "", anthropic: "", catalog: "", + models: [{ id: "gpt-6", name: "gpt-6", on: true }], agents: [], fallback: [], headers: {}, + key: { set: true, masked: "sk-…one" }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "", searches: false, +}; +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 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: "", + models: [{ id: "gpt-6", name: "GPT-6", on: true }], agents: [], fallback: [], headers: {}, keyList: [], + account: { agent: "codex", agentName: "Codex", user: "me@example.com", plan: "PLUS", logins: [{ user: "me@example.com", plan: "PLUS", active: true, on: true }] }, + proxy: "", takesSocket: false, +}; + +function serve(lang, posts) { + const providers = { providers: [relay, kept, 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()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state); + if (url.pathname === "/api/providers") return json(providers); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname.startsWith("/api/provider/") && route.request().method() === "POST") { + posts.push({ action: url.pathname.slice("/api/provider/".length), body: route.request().postDataJSON() }); + return json(providers); + } + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +const strings = ["WebSocket", "Send Responses turns over WebSocket"]; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + for (const width of [1100, 420]) { + const open = async (t, name) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + let page; + t.after(async () => { + if (process.env.ARTIFACT_DIR && page) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-${name}-socket.png`), fullPage: true }); + } + await browser.close(); + }); + page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const posts = []; + await page.route("**/*", serve(lang, posts)); + await page.goto("http://magpie.test/?view=providers"); + const w = await page.evaluate(([lang, ks]) => Object.fromEntries(ks.map((k) => [k, (I18N[lang] || {})[k] || k])), [lang, [...strings, "Save"]]); + await page.locator(".row.provider", { hasText: name }).click(); + await page.locator(".editor .bar").waitFor(); + return { page, errors, posts, w }; + }; + const adv = (page) => page.locator(".editor details.advanced"); + const unfold = async (page) => { + await adv(page).waitFor({ state: "attached" }); + if (!(await adv(page).evaluate((d) => d.open))) await adv(page).locator(":scope > summary").click(); + }; + const row = (page, w) => page.locator(".editor label.tick", { hasText: w["Send Responses turns over WebSocket"] }); + const box = (page, w) => row(page, w).locator("input"); + const save = async (page, posts, w) => { + const n = posts.length; + await page.locator(".editor .bar").getByRole("button", { name: w.Save, exact: true }).click(); + for (let i = 0; i < 50 && posts.length === n; i++) await page.waitForTimeout(50); + return posts.at(-1); + }; + + test(`${engine} ${lang} ${width}: a Responses provider's turns go over WebSocket from a tick under Advanced`, async (t) => { + const { page, errors, posts, w } = await open(t, "Relay Hub"); + if (lang !== "en") { + const missing = await page.evaluate(([lang, ks]) => ks.filter((k) => !(I18N[lang] || {})[k]), [lang, strings]); + assert.deepEqual(missing, [], `every string has its ${lang}`); + } + assert.equal(await adv(page).evaluate((d) => d.open), false, "Advanced stays shut while nothing in it is set"); + await unfold(page); + assert.equal(await adv(page).locator("label.tick", { hasText: w["Send Responses turns over WebSocket"] }).count(), 1, "the row is under Advanced"); + await box(page, w).scrollIntoViewIfNeeded(); + assert.equal(await row(page, w).isVisible(), true); + assert.equal(await box(page, w).isChecked(), false, "opens as saved"); + const r = await row(page, w).boundingBox(); + assert.ok(r.width > 60 && r.x >= 0 && r.x + r.width <= width, `the row fits: ${JSON.stringify(r)}`); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth), true, "no sideways scroll"); + await box(page, w).check(); + const saved = await save(page, posts, w); + assert.equal(saved.action, "save"); + assert.equal(saved.body.id, "relay"); + assert.equal(saved.body.socket, "auto"); + assert.deepEqual(errors, []); + }); + + test(`${engine} ${lang} ${width}: one set on opens Advanced ticked, keeps on, and is saved off unticked`, async (t) => { + const { page, errors, posts, w } = await open(t, "Kept Hub"); + await adv(page).waitFor({ state: "attached" }); + assert.equal(await adv(page).evaluate((d) => d.open), true, "Advanced opens when it holds a setting"); + assert.equal(await box(page, w).isChecked(), true); + let saved = await save(page, posts, w); + assert.equal(saved.body.socket, "on", "a Save leaves the CLI's on as it was"); + await page.locator(".editor .bar").waitFor({ state: "detached" }); + await page.locator(".row.provider", { hasText: "Kept Hub" }).click(); + await page.locator(".editor .bar").waitFor(); + await adv(page).waitFor({ state: "attached" }); + await box(page, w).scrollIntoViewIfNeeded(); + await box(page, w).uncheck(); + saved = await save(page, posts, w); + assert.equal(saved.body.id, "kept"); + 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"); + await unfold(page); + assert.equal(await row(page, w).isVisible(), false); + const saved = await save(page, posts, w); + assert.equal("socket" in saved.body, false, `sent: ${JSON.stringify(saved.body)}`); + assert.deepEqual(errors, []); + } + const { page, errors, w } = await open(t, "Codex"); + assert.equal(await row(page, w).isVisible(), false); + assert.deepEqual(errors, []); + }); + } + } +} diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 01dbc38b2..d338a00de 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -381,6 +381,16 @@ type Provider struct { // group's own. Patience int `json:"patience,omitempty"` + // Socket has a Responses API provider's turns go over the Responses + // WebSocket magpie speaks to chatgpt.com (#5781, matrix0487 on + // 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 + // socket=`. + Socket string `json:"socket,omitempty"` + // NativeCompaction has Codex's compaction_trigger go to the provider // as Codex sent it, and the compaction the provider writes back go to // Codex as it came (#1099), where magpie otherwise asks the model for @@ -1453,6 +1463,9 @@ func AddCopy(p Provider, from string) (string, error) { p.Unredacted = p.Unredacted || src.Unredacted p.CountFree = p.CountFree || src.CountFree p.NativeCompaction = p.NativeCompaction || src.NativeCompaction + if p.Socket == "" { + p.Socket = src.Socket + } p.MagpieUserAgent = p.MagpieUserAgent || src.MagpieUserAgent if p.Website == "" { p.Website = src.Website @@ -1683,6 +1696,11 @@ func normalize(p Provider) Provider { p.Patience = PatienceOff } p.Patience = min(p.Patience, PatienceLongest) + if v, ok := ParseSocket(p.Socket); ok { + p.Socket = v + } else { + p.Socket = "" + } p.Key = strings.TrimSpace(p.Key) p.Proxy = strings.TrimSpace(p.Proxy) p.AccountProxies = normalAccountProxies(p.AccountProxies) diff --git a/internal/provider/proxy.go b/internal/provider/proxy.go index 779b5750e..1059acbaf 100644 --- a/internal/provider/proxy.go +++ b/internal/provider/proxy.go @@ -16,7 +16,9 @@ import ( // its own proxy (ProxyChoice), or the global one when it has none. A // provider the user added and asked not to have its certificate checked // (InsecureTLS) has its own hosts' taken as they are, no other host's; -// one asked to be spoken HTTP/1.1 to (HTTP1) is, at its own hosts alone. +// one asked to be spoken HTTP/1.1 to (HTTP1) is, at its own hosts alone; +// one whose turns go over the Responses WebSocket (Socket) has them go +// there, at its Responses URL alone (SocketTurn). func (p Provider) Via(ctx context.Context) context.Context { ctx = netproxy.With(ctx, p.ProxyChoice()) if p.InsecureTLS && p.TakesInsecureTLS() { @@ -25,7 +27,7 @@ func (p Provider) Via(ctx context.Context) context.Context { if p.HTTP1 && p.TakesInsecureTLS() { ctx = netproxy.WithHTTP1(ctx, p.UncheckedHosts()...) } - return ctx + return withSocket(ctx, p) } // ProxyChoice is the proxy requests made on the provider's behalf go diff --git a/internal/provider/socket.go b/internal/provider/socket.go new file mode 100644 index 000000000..eb0ede48c --- /dev/null +++ b/internal/provider/socket.go @@ -0,0 +1,90 @@ +package provider + +import ( + "context" + "net/http" + "net/url" + "strings" +) + +// 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 "". +const ( + SocketAuto = "auto" + SocketOn = "on" +) + +// ParseSocket is the Socket v sets: auto, on, or "" for off (off, no, +// 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": + return "", true + } + return "", false +} + +// 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. +func (p Provider) TakesSocket() bool { + return p.Account == nil && p.Responses != "" && !p.IsVertex() +} + +type socketKey struct{} + +// socketAt is where a provider's Responses turns are, and whether a host +// that refuses the socket is left to HTTP for a while; zero for a provider +// whose turns go over HTTP alone. +type socketAt struct { + host, path string + shun bool +} + +// withSocket is ctx carrying where p's turns may go over the Responses +// WebSocket; one that has none hides any it carried before, so a +// provider never takes another's. +func withSocket(ctx context.Context, p Provider) context.Context { + at, ok := p.socketAt() + if !ok { + if _, had := ctx.Value(socketKey{}).(socketAt); had { + return context.WithValue(ctx, socketKey{}, socketAt{}) + } + return ctx + } + return context.WithValue(ctx, socketKey{}, at) +} + +func (p Provider) socketAt() (socketAt, bool) { + if p.Socket == "" || !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 +} + +// SocketTurn says req is a Responses turn that may go over the Responses +// WebSocket: one to chatgpt.com's Codex backend, or to the Responses URL +// of a provider whose Socket is set (its ctx made by Via). shun says a +// refused handshake leaves the host to HTTP for a while. +func SocketTurn(req *http.Request) (ok, shun bool) { + if req == nil || req.URL == nil { + return false, false + } + if codexTurnURL(req.URL) { + return true, true + } + at, _ := req.Context().Value(socketKey{}).(socketAt) + if at.host == "" || !strings.EqualFold(req.URL.Host, at.host) || req.URL.Path != at.path { + return false, false + } + return true, at.shun +} diff --git a/internal/provider/socket_test.go b/internal/provider/socket_test.go new file mode 100644 index 000000000..1952eae73 --- /dev/null +++ b/internal/provider/socket_test.go @@ -0,0 +1,62 @@ +package provider + +import ( + "context" + "net/http" + "testing" +) + +// #5781: a provider's turns go over the Responses WebSocket only at its +// own Responses URL, only with Socket set, and a nested provider without +// it never takes the one around it. +func TestSocketTurn(t *testing.T) { + turn := func(ctx context.Context, u string) (bool, bool) { + t.Helper() + req, err := http.NewRequestWithContext(ctx, "POST", u, nil) + if err != nil { + t.Fatal(err) + } + return SocketTurn(req) + } + relay := Provider{ID: "relay", Key: "k", Responses: "https://relay.example/v1/", Socket: SocketAuto} + ctx := relay.Via(context.Background()) + if ok, shun := turn(ctx, "https://relay.example/v1/responses"); !ok || !shun { + t.Errorf("auto: %v %v, want a turn that shuns", ok, shun) + } + for _, u := range []string{"https://relay.example/v1/chat/completions", "https://relay.example/v1/responses/compact", + "https://other.example/v1/responses", "https://relay.example/v2/responses"} { + if ok, _ := turn(ctx, u); ok { + t.Errorf("%s went over the socket", u) + } + } + on := relay + on.Socket = SocketOn + if ok, shun := turn(on.Via(context.Background()), "https://RELAY.example/v1/responses"); !ok || shun { + t.Errorf("on: %v %v, want a turn that never shuns", ok, shun) + } + off := relay + off.Socket = "" + if ok, _ := turn(off.Via(context.Background()), "https://relay.example/v1/responses"); ok { + t.Error("a provider without Socket went over the socket") + } + if ok, _ := turn(off.Via(ctx), "https://relay.example/v1/responses"); ok { + t.Error("a provider without Socket took the one around it") + } + acct := relay + acct.Account = &Account{} + if ok, _ := turn(acct.Via(context.Background()), "https://relay.example/v1/responses"); ok { + t.Error("an account went over the socket") + } + // chatgpt.com's Codex backend always may, and shuns + if ok, shun := turn(context.Background(), CodexBase+"/responses"); !ok || !shun { + t.Errorf("chatgpt.com: %v %v", ok, shun) + } +} + +func TestSocketKeptAsSet(t *testing.T) { + for v, want := range map[string]string{"auto": "auto", " On ": "on", "off": "", "": "", "maybe": ""} { + if got := normalize(Provider{ID: "x", Socket: v}).Socket; got != want { + t.Errorf("%q kept as %q, want %q", v, got, want) + } + } +}