diff --git a/internal/gateway/keepalive_masked_test.go b/internal/gateway/keepalive_masked_test.go new file mode 100644 index 000000000..961711f1a --- /dev/null +++ b/internal/gateway/keepalive_masked_test.go @@ -0,0 +1,111 @@ +package gateway + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/yetone/magpie/internal/middleware" + "github.com/yetone/magpie/internal/plugin" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" +) + +// codexShaped is a Responses request as codex-cli sends one: developer +// messages with its permissions (a writable root under the user's home) +// and the user's own, then the prompt. What Privacy masks in them is what +// made magpie wrap the reply to put the values back (#2402); a plain +// {"input": ""} has nothing to mask, and its reply went unwrapped. +const codexShaped = `{"model":"fixture/gpt-test","stream":true,"store":false,"instructions":"You are Codex.", + "input":[ + {"type":"message","role":"developer","content":[{"type":"input_text","text":"Filesystem sandboxing: workspace-write. Writable roots: /Users/moon/work. Git author moon.shard@proton.me"}]}, + {"type":"message","role":"developer","content":[{"type":"input_text","text":"default"}]}, + {"type":"message","role":"user","content":[{"type":"input_text","text":"think hard, then say hello"}]}], + "reasoning":{"effort":"xhigh"},"tool_choice":"auto","parallel_tool_calls":true}` + +// A Codex request through a Responses provider whose vendor sent +// response.created and then reasoned in silence: magpie wrote a +// ": keepalive" every keepaliveEvery, but with something in the request +// masked the reply went through the writer that puts the values back, and +// it held each comment for the event after it, as a part of that event. The +// six of 90s came together with the first words, and Cloudflare in front of +// magpie had hung up at 100s with a 524 (#2402, moonshardx). A JS +// middleware's onEvent wraps the reply the same way. The vendor here says +// nothing more until the agent has read a keepalive, so a held one waits +// out its 3s and fails. +func TestQuietCodexStreamKeptAliveThroughReplyWriters(t *testing.T) { + for _, tc := range []struct { + name string + masks, middleware bool + }{{"masked", true, false}, {"a middleware", false, true}} { + t.Run(tc.name, func(t *testing.T) { + fresh(t) + quietFast(t) + t.Cleanup(plugin.Settle) + heard := make(chan struct{}) + var timedOut atomic.Bool + var sent []byte + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + sent, _ = io.ReadAll(r.Body) + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, quietCreated) + w.(http.Flusher).Flush() + select { + case <-heard: + case <-time.After(3 * time.Second): + timedOut.Store(true) + case <-r.Context().Done(): + return + } + io.WriteString(w, quietDelta("hello")+quietDone) + })) + t.Cleanup(up.Close) + if err := provider.Save(provider.Provider{ID: "fixture", Name: "Fixture", Key: "k", Models: []string{"gpt-test"}, Responses: up.URL + "/v1"}); err != nil { + t.Fatal(err) + } + if err := settings.Save(settings.Settings{Redact: tc.masks, RedactPersonal: tc.masks}); err != nil { + t.Fatal(err) + } + if tc.middleware { + mw := filepath.Join(t.TempDir(), "upper.middleware.js") + os.WriteFile(mw, []byte(`export function onEvent(ev) { if (ev.delta) ev.delta = ev.delta.toUpperCase(); return ev; }`), 0o644) + b, _ := json.Marshal(plugin.List{Plugins: []plugin.Entry{{Spec: mw}}}) + os.MkdirAll(settings.Dir(), 0o755) + os.WriteFile(filepath.Join(settings.Dir(), "plugins.json"), b, 0o644) + middleware.Reload() + t.Cleanup(middleware.Reload) + } + + gw := httptest.NewServer(New().Handler()) + t.Cleanup(gw.Close) + resp, err := http.Post(gw.URL+"/v1/responses", "application/json", strings.NewReader(codexShaped)) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + body := readQuiet(resp.Body, heard, "") + + if tc.masks == strings.Contains(string(sent), "moon.shard@proton.me") { + t.Fatalf("masked %v, sent %s", tc.masks, sent) + } + alive, words := strings.Index(body, ": keepalive"), strings.Index(body, "response.output_text.delta") + if timedOut.Load() || resp.StatusCode != 200 || alive < 0 || words < alive { + t.Fatalf("the agent heard no keepalive while the vendor was quiet (held %v): %d %q", timedOut.Load(), resp.StatusCode, body) + } + hello := "hello" + if tc.middleware { + hello = "HELLO" + } + if !strings.Contains(body[alive:], hello) || !strings.Contains(body, "response.completed") { + t.Fatalf("the reply after the keepalives: %q", body) + } + }) + } +} diff --git a/internal/middleware/middleware_test.go b/internal/middleware/middleware_test.go index 16e70c6c9..3467cde68 100644 --- a/internal/middleware/middleware_test.go +++ b/internal/middleware/middleware_test.go @@ -307,6 +307,32 @@ func TestStreamUnchangedPassesBytes(t *testing.T) { } } +// A keepalive comment goes to the agent as it is written, not with the +// event after it: held, a proxy in front of magpie heard nothing while the +// vendor reasoned silently and hung up (#2402). +func TestStreamKeepaliveNotHeld(t *testing.T) { + use(t, file(t, `export function onEvent(ev) { ev.seen = true; return ev; }`)) + r := Begin(info()) + defer r.End() + rec := httptest.NewRecorder() + w, done := r.Wrap(rec) + w.Header().Set("Content-Type", "text/event-stream") + w.WriteHeader(200) + for i, s := range []string{": keepalive\n", ": keepalive\r\n", "\n", "data: {\"a\":1}\n", ": keep"} { + w.Write([]byte(s)) + if want := []int{1, 2, 2, 2, 2}[i]; strings.Count(rec.Body.String(), ": keepalive") != want { + t.Fatalf("after %q: %q", s, rec.Body.String()) + } + } + w.Write([]byte("alive\n\n")) + done() + // a comment inside an event stays in it, the event changed around it + want := ": keepalive\n: keepalive\r\n\n" + `data: {"a":1,"seen":true}` + "\n: keepalive\n\n" + if got := rec.Body.String(); got != want { + t.Fatalf("got %q, want %q", got, want) + } +} + func TestWholeResponse(t *testing.T) { use(t, file(t, ` export function onResponse(body, ctx) { body.status = ctx.status; body.n = (body.n || 0) + 1; return body; }`)) diff --git a/internal/middleware/run.go b/internal/middleware/run.go index 94d2ba226..a8deae38c 100644 --- a/internal/middleware/run.go +++ b/internal/middleware/run.go @@ -276,6 +276,18 @@ func (rw *writer) Write(p []byte) (int, error) { rw.buf.Write(p) for { b := rw.buf.Bytes() + // a comment between two events (": keepalive") goes on as it + // comes, as no onEvent sees it: held for the event after it, an + // agent behind a proxy heard nothing while its vendor reasoned + // silently, and the proxy hung up (#2402) + if c := commentLines(b); c > 0 { + _, err := rw.w.Write(b[:c]) + rw.buf.Next(c) + if err != nil { + return len(p), err + } + continue + } i, n := eventEnd(b) if i < 0 { break @@ -359,6 +371,21 @@ func (rw *writer) event(ev []byte) error { return err } +// commentLines is how long the whole comment lines (": keepalive") and +// blank lines at the start of b are: b starts where an event does, so none +// of them is part of one. +func commentLines(b []byte) int { + n := 0 + for n < len(b) && (b[n] == ':' || b[n] == '\n' || b[n] == '\r') { + i := bytes.IndexByte(b[n:], '\n') + if i < 0 || b[n] == '\r' && i != 1 { + break + } + n += i + 1 + } + return n +} + // eventEnd is where the first complete event in b ends, and the length of // the blank line that ends it. func eventEnd(b []byte) (int, int) { diff --git a/internal/redact/restore_test.go b/internal/redact/restore_test.go index 78d48d175..1e73f224e 100644 --- a/internal/redact/restore_test.go +++ b/internal/redact/restore_test.go @@ -154,3 +154,45 @@ func TestWriterStreamToolArgsRewritten(t *testing.T) { t.Fatalf("args %q: %v", js.String(), err) } } + +// A keepalive comment goes to the agent as it is written, not with the +// event after it, even while an event is held for the rest of a +// placeholder: held, a proxy in front of magpie heard nothing while the +// vendor reasoned silently and hung up (#2402). The placeholder split +// around it still comes back whole. +func TestWriterStreamKeepaliveNotHeld(t *testing.T) { + const phone = "13987654321" + p := phonePlaceholder(t, phone) + chat := func(s string) string { + b, _ := json.Marshal(s) + return `data: {"choices":[{"index":0,"delta":{"content":` + string(b) + `}}]}` + "\n\n" + } + rec := httptest.NewRecorder() + rec.Header().Set("Content-Type", "text/event-stream") + w := NewWriter(rec) + w.WriteHeader(200) + for i, s := range []string{": keepalive\n", chat("call " + p[:5]), ": keepalive\r\n", ": keep"} { + w.Write([]byte(s)) + if want := []int{1, 1, 2, 2}[i]; strings.Count(rec.Body.String(), ": keepalive") != want { + t.Fatalf("after %q: %q", s, rec.Body.String()) + } + } + w.Write([]byte("alive\n")) + w.Write([]byte(chat(p[5:] + " now"))) + w.Finish() + var text strings.Builder + for _, line := range strings.Split(rec.Body.String(), "\n") { + if d, ok := strings.CutPrefix(line, "data: "); ok { + var e struct { + Choices []struct{ Delta struct{ Content string } } + } + if err := json.Unmarshal([]byte(d), &e); err != nil { + t.Fatalf("event %q: %v", d, err) + } + text.WriteString(e.Choices[0].Delta.Content) + } + } + if text.String() != "call "+phone+" now" || strings.Count(rec.Body.String(), ": keepalive") != 3 { + t.Fatalf("text %q in %q", text.String(), rec.Body.String()) + } +} diff --git a/internal/redact/writer.go b/internal/redact/writer.go index a4058e61e..e11510b3b 100644 --- a/internal/redact/writer.go +++ b/internal/redact/writer.go @@ -90,6 +90,18 @@ func (rw *Writer) Write(p []byte) (int, error) { rw.buf.Write(p) for { b := rw.buf.Bytes() + // a comment between two events (": keepalive") goes on as it + // comes: held for the event after it, an agent behind a proxy + // heard nothing while its vendor reasoned silently, and the + // proxy hung up (#2402). It carries nothing to put back, and an + // event held for its placeholder's tail goes on after it as well. + if c := commentLines(b); c > 0 { + if _, err := rw.w.Write(b[:c]); err != nil { + return len(p), err + } + rw.buf.Next(c) + continue + } i, n := eventEnd(b) if i < 0 { break @@ -103,6 +115,21 @@ func (rw *Writer) Write(p []byte) (int, error) { return len(p), nil } +// commentLines is how long the whole comment lines (": keepalive") and +// blank lines at the start of b are: b starts where an event does, so none +// of them is part of one. +func commentLines(b []byte) int { + n := 0 + for n < len(b) && (b[n] == ':' || b[n] == '\n' || b[n] == '\r') { + i := bytes.IndexByte(b[n:], '\n') + if i < 0 || b[n] == '\r' && i != 1 { + break + } + n += i + 1 + } + return n +} + // eventEnd is where the first complete event in b ends, and the length of // the blank line that ends it. func eventEnd(b []byte) (int, int) {