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/main589e4ba6d: 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 on1bfa8d5a1(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/main1bfa8d5a1is 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 at1bfa8d5a1too. - old-webkit.test.cjs: 2 reds (guideback.js not in the lazy list, Safari 15.0 styles), the same on origin/main1bfa8d5a1run 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
283 lines
11 KiB
Go
283 lines
11 KiB
Go
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
|
|
// <id> 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)
|
|
}
|
|
}
|
|
|
|
// 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())
|
|
}
|
|
}
|