Every forward went with User-Agent magpie/<version>. A coding plan that serves only the agents it names (pi, OpenCode, Claude Code…) knows them by their User-Agent, so it turned magpie away. What changed - provider: PassUserAgent (passUserAgent in providers.json), off by default. PassesUserAgent takes it only for a key+URL provider: never a signed-in account, a plugin's, or a vendor whose own client magpie goes as (OwnClient: OpenCode, Cline, Kilo, another magpie). A copy keeps it. - gateway: userAgentFor in forwardOnce (chat, Anthropic, Responses, Gemini, count_tokens) sends the inbound User-Agent unchanged where the provider passes it on. It sends magpie's where it doesn't, where the agent sent none, and on magpie's own requests (magpiesOwn: magpie/…, magpie-router/vision/search, the image tool's "<client> magpie-image/1", which is built from MCP clientInfo, not a User-Agent). magpie never invents another client's. The claude-cli/Codex header copies, the OpenCode/Cline/Kilo overrides and account signing run after it as before, and the user's header.User-Agent is put on at signing, so it wins. - gateway: embeddings, images and videos (retrieveFrom, sendWith, remoteVideoContent) now stamp the same for a key+URL provider through stampUA, from the caller's User-Agent kept on the request ctx (caller.ua, withCaller). Before, they went with Go's default (Go-http-client/1.1). Account and remote-magpie paths are untouched. - cli: `magpie provider set <id> user-agent=agent|magpie`, refused for a signed-in account; `magpie provider <id>` shows it. - gui: the provider editor's User-Agent row, "Send the agent's own User-Agent", with an explanation, for a provider with a key only (the JSON says ownClient for presets and providers); en/zh/zh-TW/ja/de. The TUI only adds presets, so it has no field for this. - docs: reference.md (provider set) and subsystems/gateway-routing.md. What was run - gofmt -l clean; go vet ./... on darwin, GOOS=linux -tags nogui and GOOS=windows. - go test -count=1 ./internal/gateway ./internal/provider ./internal/cli ./internal/gui: all ok (sandbox HOME, private GOCACHE). - TestUserAgentPassedOn covers 7 routes (messages, count_tokens, chat, responses, gemini, embeddings, images) x off / on / on with no UA / on with magpie-router/1 / on with the image tool's UA / the user's header with it on and off. TestUserAgentAccountUntouched: a Factory account with passUserAgent in providers.json is still asked as factory-cli/. Also TestUserAgentClaudeCodeAsBefore, TestUserAgentFor, TestPassesUserAgent, TestAddCopyPassUserAgent, TestProviderUserAgentPair. - Broken by hand, each went red: forwardOnce back to magpie's UA (5 routes red); stampUA removed from embeddings/draw (both red, seen as Go-http-client/1.1); PassesUserAgent ignoring accounts/OwnClient; magpiesOwn dropped (the internal UAs leaked on all 7 routes); the GUI row shown for OpenCode and Save not posting it. - provider-user-agent.test.cjs: 60/60 in chromium and webkit, en, zh, zh-TW, ja, de, at 900 and 440 wide. The provider/editor/add/i18n GUI tests in chromium: 244/244. Not run - Not tried against a real coding plan that checks User-Agent, nor with a real agent through a live gateway. Videos have no test of their own (they go through sendWith, which the images test covers). - The GUI suite was not run in full; the Windows box was not used.
262 lines
11 KiB
Go
262 lines
11 KiB
Go
package gateway
|
|
|
|
import (
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/catalog"
|
|
"github.com/yetone/magpie/internal/provider"
|
|
)
|
|
|
|
// uaVendor is a key+URL vendor on every API magpie forwards to one: it
|
|
// keeps the User-Agent each path was asked with, and answers each as its
|
|
// API does.
|
|
type uaVendor struct {
|
|
mu sync.Mutex
|
|
got map[string]string
|
|
}
|
|
|
|
func (v *uaVendor) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
io.Copy(io.Discard, r.Body)
|
|
v.mu.Lock()
|
|
v.got[r.URL.Path] = r.Header.Get("User-Agent")
|
|
v.mu.Unlock()
|
|
w.Header().Set("Content-Type", "application/json")
|
|
switch p := r.URL.Path; {
|
|
case strings.HasSuffix(p, "/count_tokens"):
|
|
io.WriteString(w, `{"input_tokens":5}`)
|
|
case p == "/v1/messages":
|
|
io.WriteString(w, `{"id":"m","type":"message","role":"assistant","model":"m1","content":[{"type":"text","text":"hi"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`)
|
|
case p == "/v1/chat/completions":
|
|
io.WriteString(w, `{"id":"c","object":"chat.completion","model":"m1","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`)
|
|
case p == "/v1/responses":
|
|
io.WriteString(w, `{"id":"r1","object":"response","status":"completed","model":"m1","output":[{"type":"message","id":"msg1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"hi","annotations":[]}]}],"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}}`)
|
|
case strings.HasSuffix(p, ":streamGenerateContent"):
|
|
w.Header().Set("Content-Type", "text/event-stream")
|
|
io.WriteString(w, "data: "+`{"candidates":[{"content":{"role":"model","parts":[{"text":"hi"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":1,"candidatesTokenCount":1,"totalTokenCount":2}}`+"\n\n")
|
|
case p == "/v1/embeddings":
|
|
io.WriteString(w, `{"object":"list","data":[{"object":"embedding","index":0,"embedding":[0.1,-0.2]}],"model":"embed-1","usage":{"prompt_tokens":1,"total_tokens":1}}`)
|
|
case p == "/v1/images/generations":
|
|
io.WriteString(w, `{"created":1,"data":[{"b64_json":"`+base64.StdEncoding.EncodeToString(pngBytes)+`"}]}`)
|
|
default:
|
|
w.WriteHeader(404)
|
|
}
|
|
}
|
|
|
|
func (v *uaVendor) sent(path string) (string, bool) {
|
|
v.mu.Lock()
|
|
defer v.mu.Unlock()
|
|
ua, ok := v.got[path]
|
|
delete(v.got, path)
|
|
return ua, ok
|
|
}
|
|
|
|
// uaRoutes are the routes a request reaches a key+URL provider by: what an
|
|
// agent posts magpie, and the path the vendor is asked at.
|
|
var uaRoutes = []struct{ name, path, body, upstream string }{
|
|
{"anthropic", "/v1/messages", `{"model":"ua/m1","max_tokens":8,"messages":[{"role":"user","content":"hi"}]}`, "/v1/messages"},
|
|
{"count_tokens", "/v1/messages/count_tokens", `{"model":"ua/m1","messages":[{"role":"user","content":"hi"}]}`, "/v1/messages/count_tokens"},
|
|
{"chat", "/v1/chat/completions", `{"model":"ua/m1","messages":[{"role":"user","content":"hi"}]}`, "/v1/chat/completions"},
|
|
{"responses", "/v1/responses", `{"model":"ua/m1","input":"hi"}`, "/v1/responses"},
|
|
{"gemini", "/v1beta/models/ug/m1:generateContent", `{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`, "/v1beta/models/m1:streamGenerateContent"},
|
|
{"embeddings", "/v1/embeddings", `{"model":"ua/embed-1","input":"hi"}`, "/v1/embeddings"},
|
|
{"images", "/v1/images/generations", `{"model":"ua/gpt-image-1","prompt":"a magpie"}`, "/v1/images/generations"},
|
|
}
|
|
|
|
// uaSetup saves a key+URL provider "ua" on every API, at a uaVendor, with
|
|
// pass for its PassUserAgent and headers for the user's own, and "ug" the
|
|
// same on Gemini's API alone.
|
|
func uaSetup(t *testing.T, pass bool, headers map[string]string) *uaVendor {
|
|
t.Helper()
|
|
fresh(t)
|
|
v := &uaVendor{got: map[string]string{}}
|
|
up := httptest.NewServer(v)
|
|
t.Cleanup(up.Close)
|
|
p := provider.Provider{ID: "ua", Name: "UA", Key: "k", Chat: up.URL + "/v1", Responses: up.URL + "/v1", Anthropic: up.URL, Gemini: up.URL + "/v1beta",
|
|
Models: []string{"m1", "embed-1", "gpt-image-1"}, PassUserAgent: pass, Headers: headers}
|
|
if err := provider.Save(p); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := catalog.SaveLive("ua", up.URL+"/v1", []catalog.Model{{ID: "m1"}, {ID: "embed-1"}, {ID: "gpt-image-1"}}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
// Gemini's own wire, which a provider on Chat too isn't asked on
|
|
g := provider.Provider{ID: "ug", Name: "UG", Key: "k", Gemini: up.URL + "/v1beta", Models: []string{"m1"}, PassUserAgent: pass, Headers: headers}
|
|
if err := provider.Save(g); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return v
|
|
}
|
|
|
|
// askAs posts body to path as an agent whose User-Agent is ua ("" sends
|
|
// none).
|
|
func askAs(t *testing.T, s *Server, path, body, ua string) {
|
|
t.Helper()
|
|
rec := httptest.NewRecorder()
|
|
req := httptest.NewRequest("POST", path, strings.NewReader(body))
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Del("User-Agent")
|
|
if ua != "" {
|
|
req.Header.Set("User-Agent", ua)
|
|
}
|
|
s.Handler().ServeHTTP(rec, req)
|
|
if rec.Code != 200 {
|
|
t.Fatalf("%s: status %d: %s", path, rec.Code, rec.Body)
|
|
}
|
|
}
|
|
|
|
// A key+URL provider set to pass the agent's User-Agent on (#1851) is
|
|
// asked with the one the agent sent, on every route that reaches it: a
|
|
// coding plan that serves only agents it names knows them by it. Off, the
|
|
// default, it is asked as magpie; so it is when the agent sent none, and
|
|
// on magpie's own requests (its classifier's, the image tool's), which no
|
|
// agent sent. A User-Agent the user set in the provider's headers stands
|
|
// over both.
|
|
func TestUserAgentPassedOn(t *testing.T) {
|
|
const pi = "pi-coding-agent/0.9.1 (darwin; arm64)"
|
|
magpie := "magpie/" + Version
|
|
for _, tt := range []struct {
|
|
name string
|
|
pass bool
|
|
headers map[string]string
|
|
ua string // what the agent sent
|
|
want string
|
|
}{
|
|
{"off", false, nil, pi, magpie},
|
|
{"on", true, nil, pi, pi},
|
|
{"on, the agent sent none", true, nil, "", magpie},
|
|
{"on, magpie's classifier", true, nil, RouterAgent, magpie},
|
|
{"on, magpie's image tool", true, nil, "claude-code/2.1.0 " + DrawAgent, magpie},
|
|
{"on, the user's own header", true, map[string]string{"User-Agent": "mine/1"}, pi, "mine/1"},
|
|
{"off, the user's own header", false, map[string]string{"User-Agent": "mine/1"}, pi, "mine/1"},
|
|
} {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
v := uaSetup(t, tt.pass, tt.headers)
|
|
s := New()
|
|
for _, r := range uaRoutes {
|
|
askAs(t, s, r.path, r.body, tt.ua)
|
|
got, ok := v.sent(r.upstream)
|
|
if !ok {
|
|
t.Fatalf("%s: the vendor wasn't asked at %s", r.name, r.upstream)
|
|
}
|
|
if got != tt.want {
|
|
t.Errorf("%s: the vendor was asked as %q, want %q", r.name, got, tt.want)
|
|
}
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// Claude Code's and Codex's own headers still go on to a key+URL provider
|
|
// as before (#179, #1758), whether it passes the agent's User-Agent or
|
|
// not: the passing on is the same User-Agent.
|
|
func TestUserAgentClaudeCodeAsBefore(t *testing.T) {
|
|
const cc = "claude-cli/2.1.0 (external, cli)"
|
|
for _, pass := range []bool{false, true} {
|
|
v := uaSetup(t, pass, nil)
|
|
askAs(t, New(), "/v1/messages", uaRoutes[0].body, cc)
|
|
if got, _ := v.sent("/v1/messages"); got != cc {
|
|
t.Errorf("pass %v: Claude Code's request went as %q", pass, got)
|
|
}
|
|
}
|
|
}
|
|
|
|
// A signed-in account keeps the identity its own signing gives, whatever
|
|
// is set: Factory's is asked as droid, never as the agent, nor does the
|
|
// flag stick to it when saved.
|
|
func TestUserAgentAccountUntouched(t *testing.T) {
|
|
home := t.TempDir()
|
|
t.Setenv("HOME", home)
|
|
t.Setenv("USERPROFILE", home)
|
|
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
|
|
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
|
|
t.Setenv("XDG_DATA_HOME", filepath.Join(home, ".local", "share"))
|
|
f := &fake{t: t, ctype: "application/json", reply: `{"id":"c","object":"chat.completion","model":"m","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}]}`}
|
|
up := httptest.NewServer(f)
|
|
t.Cleanup(up.Close)
|
|
t.Cleanup(provider.FactoryBaseForTest(up.URL, up.URL+"/eu"))
|
|
auth, _ := json.Marshal(map[string]any{
|
|
"accessToken": "tok", "refreshToken": "r",
|
|
"expiresAt": time.Now().Add(time.Hour).UnixMilli(),
|
|
"orgId": "org_D", "activeOrganizationId": "fac_D", "email": "d@example.com",
|
|
})
|
|
dir := filepath.Dir(provider.Path())
|
|
if err := os.MkdirAll(dir, 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
raw, _ := json.Marshal([]map[string]any{{"agent": "factory", "user": "d@example.com", "plan": "pro", "on": true, "auth": json.RawMessage(auth)}})
|
|
if err := os.WriteFile(filepath.Join(dir, "logins.json"), raw, 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
// set as the file would hold it, past the editor and the CLI
|
|
if err := os.WriteFile(provider.Path(), []byte(`{"providers":[{"id":"factory","passUserAgent":true}]}`), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
p, err := provider.Find("factory")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if p.PassesUserAgent() {
|
|
t.Fatal("a signed-in account passes the agent's User-Agent on")
|
|
}
|
|
for _, r := range []struct{ path, body string }{
|
|
{"/v1/chat/completions", `{"model":"factory/deepseek-v4.1-flash","messages":[{"role":"user","content":"hi"}]}`},
|
|
{"/v1/messages", `{"model":"factory/deepseek-v4.1-flash","max_tokens":8,"messages":[{"role":"user","content":"hi"}]}`},
|
|
} {
|
|
f.head = nil
|
|
rec := httptest.NewRecorder()
|
|
req := httptest.NewRequest("POST", r.path, strings.NewReader(r.body))
|
|
req.Header.Set("User-Agent", "pi-coding-agent/0.9.1")
|
|
New().Handler().ServeHTTP(rec, req)
|
|
if f.head == nil {
|
|
t.Fatalf("%s: Factory wasn't asked: %d %s", r.path, rec.Code, rec.Body)
|
|
}
|
|
if ua := f.head.Get("User-Agent"); !strings.HasPrefix(ua, "factory-cli/") {
|
|
t.Errorf("%s: Factory was asked as %q, not as droid", r.path, ua)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Which providers pass it on: a key+URL one set to, and not a signed-in
|
|
// account (ZCode's Coding Plan signs without a User-Agent of its own, and
|
|
// goes as magpie), a plugin's, a vendor's own client's gateway (OpenCode,
|
|
// Cline, Kilo) or another magpie, each of which goes as the client it
|
|
// signs as.
|
|
func TestUserAgentFor(t *testing.T) {
|
|
const pi = "pi/1"
|
|
magpie := "magpie/" + Version
|
|
for _, tt := range []struct {
|
|
name string
|
|
p provider.Provider
|
|
want string
|
|
}{
|
|
{"key", provider.Provider{Chat: "https://api.example.com/v1", PassUserAgent: true}, pi},
|
|
{"key, off", provider.Provider{Chat: "https://api.example.com/v1"}, magpie},
|
|
{"account", provider.Provider{Chat: "https://api.z.ai/api/coding/paas/v4", PassUserAgent: true, Account: &provider.Account{Agent: "zcode"}}, magpie},
|
|
{"opencode", provider.Provider{Chat: "https://opencode.ai/zen/v1", PassUserAgent: true}, magpie},
|
|
{"cline", provider.Provider{Preset: "clinepass", Chat: "https://api.cline.bot/api/v1", PassUserAgent: true}, magpie},
|
|
{"kilo", provider.Provider{Preset: "kilo", Chat: "https://api.kilo.ai/api/gateway", PassUserAgent: true}, magpie},
|
|
{"remote magpie", provider.Provider{Preset: provider.RemoteMagpiePreset, Chat: "http://10.0.0.2:3425/v1", PassUserAgent: true}, magpie},
|
|
} {
|
|
if got := userAgentFor(tt.p, pi); got != tt.want {
|
|
t.Errorf("%s: %q, want %q", tt.name, got, tt.want)
|
|
}
|
|
}
|
|
// an account's own request headers are its signing's: stampUA leaves
|
|
// them as they are
|
|
h := http.Header{}
|
|
stampUA(t.Context(), provider.Provider{PassUserAgent: true, Account: &provider.Account{Agent: "zcode"}}, h)
|
|
if h.Get("User-Agent") != "" {
|
|
t.Errorf("an account's request was stamped %q", h.Get("User-Agent"))
|
|
}
|
|
}
|