Files
magpie/internal/gateway/opencode_session_test.go
yetone d1f57b70ee provider: every request to OpenCode's gateway names its conversation's session, at any port, lists, decisions, usage and the probe too, Codex's thread by its prompt_cache_key (luci on Discord)
OpenCode Go, added as a custom provider and asked from Codex, answered some
users 400 "Request is missing x-opencode-session and cannot be routed
efficiently", the Test button's probe too; a static header on the provider
stopped the 400 but put every conversation on one backend.

OpenCode's own client (packages/core, 4397ee4) sends x-opencode-session =
SessionAffinity (parentID ?? fork ?? id) on every model request, and a
fresh session for stateless calls; the console's inference proxy routes
every /zen and /zen/go path, models and usage included, by it.

- OpenCodeURL/openCodeHost: opencode.ai or a subdomain, by hostname, so a
  base URL naming a port (https://opencode.ai:443/zen/go/v1) is OpenCode's;
  IsOpenCode, OpenCodeFreeURL and openCodeRoot share it. Before, the turn's
  session was set only when p.Host() matched without a port.
- gateway: the turn's seed is the client's own x-opencode-session, else
  sessionOf (X-Magpie-Session, Codex's session_id, …), else the body's
  prompt_cache_key, else conversationID. Without the cache key two Codex
  conversations opened in one folder (same environment message) were one
  session.
- Sign: a request to OpenCode's gateway that names no session gets a fresh
  one (OpenCodeSession), so System One decisions and anything else signed
  are never refused; the user's own header still wins.
- Model lists (FetchURL, FetchAtListed, FetchGemini) get a fresh session
  via listHeadersAt, Go's usage windows via planWindows, the probe a
  session of its own.
- A 4xx/5xx from OpenCode's gateway logs host, path, the sent headers'
  names (never values), x-opencode-session's first 8 chars or "missing",
  and whether the provider's own header pinned it.

Run (worktree, -tags nogui -p 1):
- go test ./internal/gateway -run TestOpenCodeGoSessionPerConversation and
  -run 'OpenCode|Zen|Session|Conversation|Decide|SystemOne|UserHeader|Kilo|Cline|Gemini': ok
- go test ./internal/provider -run TestOpenCodeSessionOnEveryCall and
  -run 'OpenCode|Zen|Sign|Header|Fetch|Model|Probe|PlanQuota|Quota|Decide|Detect|Kilo|Cline|UserAgent': ok
- gofmt -l clean; go vet -tags nogui GOOS=darwin/linux/windows on both
  packages: ok
Broken by hand: seed back to conversationID -> red (threads c and d one
session); old IsOpenCode -> red (port provider's turns two sessions);
Sign's backstop removed -> red; list session removed -> red. The probe's
own OpenCodeClient removed stays green: Sign's backstop gives it a fresh
session anyway.
Not run: the full suite; no request to the real OpenCode gateway; why
luci's users miss the header (port, proxy/mirror host, a client header) is
not confirmed, the new log line will tell.

Full suite: SUITE_LINE
2026-10-15 23:08:04 +08:00

141 lines
6.1 KiB
Go

package gateway
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// openCodeMissing is what OpenCode's gateway answers a request that names
// no session (luci on Discord).
const openCodeMissing = `{"type":"error","error":{"type":"invalid_request_error","message":"Request is missing x-opencode-session and cannot be routed efficiently"}}`
// fakeOpenCode answers as OpenCode's gateway does: 400 openCodeMissing
// without x-opencode-session, a Responses or chat reply with it. It keeps
// the session each request named, by its host, "" for none.
type fakeOpenCode struct {
mu sync.Mutex
sessions map[string][]string
}
func (f *fakeOpenCode) RoundTrip(r *http.Request) (*http.Response, error) {
if r.Body != nil {
io.Copy(io.Discard, r.Body)
r.Body.Close()
}
s := r.Header.Get("x-opencode-session")
f.mu.Lock()
f.sessions[r.URL.Host] = append(f.sessions[r.URL.Host], s)
f.mu.Unlock()
h := http.Header{"Content-Type": {"application/json"}}
if s == "" && strings.Contains(r.URL.Host, "opencode.ai") {
return &http.Response{StatusCode: 400, Header: h, Body: io.NopCloser(strings.NewReader(openCodeMissing)), Request: r}, nil
}
reply := `{"id":"c","object":"chat.completion","model":"glm-5.3","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}]}`
if strings.HasSuffix(r.URL.Path, "/responses") {
reply = `{"id":"resp_1","object":"response","status":"completed","model":"glm-5.3","output":[{"type":"message","id":"msg_1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"ok","annotations":[]}]}],"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}}`
}
return &http.Response{StatusCode: 200, Header: h, Body: io.NopCloser(strings.NewReader(reply)), Request: r}, nil
}
func (f *fakeOpenCode) got(host string) []string {
f.mu.Lock()
defer f.mu.Unlock()
return append([]string(nil), f.sessions[host]...)
}
// luci on Discord: OpenCode Go, added as a custom provider and asked from
// Codex, answered 400 "Request is missing x-opencode-session and cannot
// be routed efficiently", and a session set on the provider by hand put
// every conversation on one backend. Every request to OpenCode's gateway
// names its conversation's session: the turns of one conversation the
// same, two conversations two — whether the client names its session
// (Codex's session_id) or only its thread (prompt_cache_key), and
// whatever port the provider's URL gives. Nobody else is sent one.
func TestOpenCodeGoSessionPerConversation(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
for _, p := range []provider.Provider{
{ID: "ocgo", Name: "OpenCode Go", Key: "k", Responses: "https://opencode.ai/zen/go/v1", Models: []string{"glm-5.3"}},
{ID: "ocport", Name: "OpenCode Go 443", Key: "k", Chat: "https://opencode.ai:443/zen/go/v1", Models: []string{"glm-5.3"}},
{ID: "other", Name: "Other", Key: "k", Responses: "https://other.test/v1", Models: []string{"glm-5.3"}},
} {
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
}
f := &fakeOpenCode{sessions: map[string][]string{}}
s := New()
s.client = &http.Client{Transport: f}
// a Codex turn: its environment message first, the same in every
// conversation opened in one folder, then the task
turn := func(path, model, task string, h http.Header, cacheKey string) {
t.Helper()
body := `{"model":"` + model + `","input":[{"role":"user","content":"<environment_context><cwd>/w</cwd></environment_context>"},{"role":"user","content":"` + task + `"}]`
if path == "/v1/chat/completions" {
body = `{"model":"` + model + `","messages":[{"role":"user","content":"` + task + `"}]`
}
if cacheKey != "" {
body += `,"prompt_cache_key":"` + cacheKey + `"`
}
req := httptest.NewRequest("POST", path, strings.NewReader(body+"}"))
req.Header.Set("User-Agent", "codex_cli_rs/0.130.0 (Mac OS 26.2.0; arm64)")
req.Header.Set("originator", "codex_cli_rs")
for k, v := range h {
req.Header[k] = v
}
rec := httptest.NewRecorder()
s.Handler().ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("%s %s: %d %s", model, task, rec.Code, rec.Body)
}
}
// Codex naming its session
a := http.Header{"Session_id": {"019a0000-0000-7000-8000-00000000000a"}}
b := http.Header{"Session_id": {"019a0000-0000-7000-8000-00000000000b"}}
turn("/v1/responses", "ocgo/glm-5.3", "task a", a, "")
turn("/v1/responses", "ocgo/glm-5.3", "task a, turn 2", a, "")
turn("/v1/responses", "ocgo/glm-5.3", "task b", b, "")
// Codex naming only its thread, in the body
turn("/v1/responses", "ocgo/glm-5.3", "task c", nil, "thread-c")
turn("/v1/responses", "ocgo/glm-5.3", "task c, turn 2", nil, "thread-c")
turn("/v1/responses", "ocgo/glm-5.3", "task d", nil, "thread-d")
// the client's own x-opencode-session, in OpenCode's form, goes as it is
turn("/v1/responses", "ocgo/glm-5.3", "task e", http.Header{"X-Opencode-Session": {"ses_ecc5d8f28ffe9Cy14V8Em7lI2u"}}, "")
got := f.got("opencode.ai")
if len(got) != 7 {
t.Fatalf("requests to opencode.ai: %q", got)
}
for i, v := range got {
if !strings.HasPrefix(v, "ses_") {
t.Fatalf("request %d named session %q", i, v)
}
}
if got[0] != got[1] || got[0] == got[2] {
t.Errorf("session_id: conversation a %q %q, b %q", got[0], got[1], got[2])
}
if got[3] != got[4] || got[3] == got[5] || got[3] == got[0] || got[5] == got[2] {
t.Errorf("prompt_cache_key: thread c %q %q, d %q (a %q, b %q)", got[3], got[4], got[5], got[0], got[2])
}
if got[6] != "ses_ecc5d8f28ffe9Cy14V8Em7lI2u" {
t.Errorf("the client's own session went as %q", got[6])
}
// a provider whose URL names OpenCode's port
turn("/v1/chat/completions", "ocport/glm-5.3", "task p", a, "")
turn("/v1/chat/completions", "ocport/glm-5.3", "task p, turn 2", a, "")
if p := f.got("opencode.ai:443"); len(p) != 2 || p[0] == "" || p[0] != p[1] {
t.Errorf("opencode.ai:443: %q", p)
}
turn("/v1/responses", "other/glm-5.3", "task o", a, "")
if o := f.got("other.test"); len(o) != 1 || o[0] != "" {
t.Errorf("another vendor was sent x-opencode-session: %q", o)
}
}