diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index ef156a4bd..81c0f5877 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -454,12 +454,22 @@ func codexHeader(k string) bool { // conversation, as Codex names it in x-openai-subagent: "guardian" (auto // review of an approval), "review", "compact", "memory_consolidation", // "thread_title", "collab_spawn"… A turn Codex sends on Luna Reserve, once -// the plan's own allowance is used up, is "luna_reserve". +// the plan's own allowance is used up, is "luna_reserve". A call Codex +// makes on a hidden thread of its own goes without x-openai-subagent: its +// x-codex-turn-metadata names the thread's source instead — "thread_title" +// for the title of a new chat (#314), "guardian_review". A web search +// magpie runs for a model that can't search is "web_search". func callKind(h http.Header) string { v := strings.TrimSpace(h.Get("x-openai-subagent")) if v == "" && h.Get("x-openai-memgen-request") != "" { v = "memgen" } + if v == "" { + v = threadSource(h.Get("x-codex-turn-metadata")) + } + if v == "" && h.Get("User-Agent") == SearchAgent { + v = "web_search" + } if v == "" && h.Get("x-openai-codex-luna-reserve") != "" { v = "luna_reserve" } @@ -469,6 +479,29 @@ func callKind(h http.Header) string { return v } +// threadSource is the source Codex's turn metadata gives the thread a call +// was made on, when that isn't the user's conversation or a subagent's +// (which x-openai-subagent names): a feature's own thread, as Codex's +// ThreadSource has it — "thread_title", "guardian_review", +// "memory_consolidation". +func threadSource(meta string) string { + if !strings.Contains(meta, "thread_source") { + return "" + } + var m struct { + Source string `json:"thread_source"` + } + if json.Unmarshal([]byte(meta), &m) != nil { + return "" + } + switch s := strings.TrimSpace(m.Source); s { + case "", "user", "subagent": + return "" + default: + return s + } +} + func copyHeaders(dst, src http.Header) { for k, vs := range src { if !hopHeader(k) && http.CanonicalHeaderKey(k) != "Host" { diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 92ff82755..2e26710be 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -159,7 +159,9 @@ type Call struct { Agent string `json:"agent"` // who called, from the client's User-Agent // Kind: what the agent made the call for, when it isn't its turn — // a Codex subagent's (callKind) — "" for a turn - Kind string `json:"kind,omitempty"` + Kind string `json:"kind,omitempty"` + // For: the request a call of magpie's own (a web search) was made for + For *CallFor `json:"for,omitempty"` Model string `json:"model"` Provider string `json:"provider"` From provider.Protocol `json:"from"` @@ -655,6 +657,9 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro w = capture call := Call{Time: start, From: from, Model: unprefixed(modelOf(body)), Agent: agentOf(r), Kind: callKind(r.Header), RequestBody: requestBody, RequestTruncated: requestTruncated} + if call.Kind == "web_search" { + call.For = searchFor(r.Context()) + } usage.Saw(call.Agent) finishCapture := func() { call.ResponseBody = capture.body.text() @@ -885,7 +890,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro if len(cands) == 1 { shown = nil // nobody else to stay away from } - tr := s.trace.begin(Route{Time: start, Agent: call.Agent, Kind: call.Kind, Model: call.Model, Effort: requestEffort(from, body), Provider: p.ID, Group: group, Rule: hit, Nested: nested, Affinity: shown, Order: pl.order, Left: pl.left}) + tr := s.trace.begin(Route{Time: start, Agent: call.Agent, Kind: call.Kind, For: call.For, Model: call.Model, Effort: requestEffort(from, body), Provider: p.ID, Group: group, Rule: hit, Nested: nested, Affinity: shown, Order: pl.order, Left: pl.left}) var skipped []string sent := "" // the reasoning the last try's model was asked for where := "" // the last try's provider.Where, for the usage diff --git a/internal/gateway/ir.go b/internal/gateway/ir.go index a90839504..9c0a20b1c 100644 --- a/internal/gateway/ir.go +++ b/internal/gateway/ir.go @@ -107,6 +107,10 @@ type Request struct { // id), which OpenAI, and relays in front of it, route a conversation by // to where its prompt is cached. CacheKey string + // Include is a Responses client's include, the extra output it asked + // for (Codex's reasoning.encrypted_content), which a Responses upstream + // is asked for too: a relay may refuse a request without it (#315). + Include []string // GeminiCompat is the upstream being Gemini's OpenAI-compatible API // (AI Studio's, or a proxy in front of it on this machine or the LAN), // which gives the model's thoughts only when asked in thinking_config. diff --git a/internal/gateway/responses.go b/internal/gateway/responses.go index ccbcf4b8a..390855c75 100644 --- a/internal/gateway/responses.go +++ b/internal/gateway/responses.go @@ -124,6 +124,7 @@ type rRequest struct { ParallelToolCalls *bool `json:"parallel_tool_calls,omitempty"` ServiceTier string `json:"service_tier,omitempty"` PromptCacheKey string `json:"prompt_cache_key,omitempty"` + Include []string `json:"include,omitempty"` Reasoning *struct { Effort string `json:"effort,omitempty"` Summary string `json:"summary,omitempty"` @@ -136,7 +137,7 @@ func parseResponses(body []byte) (*Request, error) { return nil, fmt.Errorf("invalid request: %v", err) } r := &Request{Model: q.Model, System: q.Instructions, MaxTokens: q.MaxOutputTokens, Temp: q.Temperature, - TopP: q.TopP, Stream: q.Stream, Parallel: q.ParallelToolCalls, Fast: q.ServiceTier == "priority", CacheKey: q.PromptCacheKey} + TopP: q.TopP, Stream: q.Stream, Parallel: q.ParallelToolCalls, Fast: q.ServiceTier == "priority", CacheKey: q.PromptCacheKey, Include: q.Include} if q.Reasoning != nil { r.Effort = effortOf(q.Reasoning.Effort) r.Thinking = true @@ -427,6 +428,19 @@ func buildResponses(r *Request, model, host string, rejectTemp bool) []byte { } else if r.Thinking { out["reasoning"] = map[string]any{"summary": "auto"} } + // the client's include goes on as the request would have without + // magpie. Sealed reasoning is asked for only with reasoning, as Codex + // asks for it: OpenAI refuses it of a model that doesn't reason. What + // comes back sealed goes no further than magpie, and the input's sealed + // reasoning isn't sent on this way, so no account or vendor is handed + // another's to refuse (withoutRefused, sealedKinds, on a relay). + var include []string + for _, v := range r.Include { + if v == "" || slices.Contains(include, v) || (v == "reasoning.encrypted_content" && out["reasoning"] == nil) { + continue + } + include = append(include, v) + } if len(r.Tools) > 0 || r.WebSearch { var tools []map[string]any for _, t := range r.Tools { @@ -440,8 +454,8 @@ func buildResponses(r *Request, model, host string, rejectTemp bool) []byte { tools = append(tools, map[string]any{"type": "web_search"}) // the pages it found, which a client of another protocol is // told of (OpenAI's option; xAI's API isn't known to take it) - if host != "api.x.ai" { - out["include"] = []string{"web_search_call.action.sources"} + if host != "api.x.ai" && !slices.Contains(include, "web_search_call.action.sources") { + include = append(include, "web_search_call.action.sources") } } out["tools"] = tools @@ -455,6 +469,9 @@ func buildResponses(r *Request, model, host string, rejectTemp bool) []byte { out["parallel_tool_calls"] = *r.Parallel } } + if len(include) > 0 { + out["include"] = include + } b, _ := json.Marshal(out) return b } diff --git a/internal/gateway/responses_include_test.go b/internal/gateway/responses_include_test.go new file mode 100644 index 000000000..769312b0d --- /dev/null +++ b/internal/gateway/responses_include_test.go @@ -0,0 +1,73 @@ +package gateway + +import ( + "encoding/json" + "slices" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// #315: a Responses request rebuilt by magpie asks for what its client's +// include did, as prompt_cache_key goes on: a strict Codex relay refuses +// one without reasoning.encrypted_content. magpie's own search sources are +// added to it once. +func TestResponsesKeepsInclude(t *testing.T) { + include := func(body, host string) []string { + t.Helper() + r, err := parseResponses([]byte(body)) + if err != nil { + t.Fatal(err) + } + var q struct { + Include []string `json:"include"` + } + json.Unmarshal(buildResponses(r, "m", host, false), &q) + return q.Include + } + for _, c := range []struct { + name, body, host string + want []string + }{ + {"sealed reasoning", `{"model":"m","input":"hi","reasoning":{"effort":"low"},"include":["reasoning.encrypted_content"]}`, "relay.example", []string{"reasoning.encrypted_content"}}, + {"with search sources", `{"model":"m","input":"hi","reasoning":{"effort":"low"},"include":["reasoning.encrypted_content"],"tools":[{"type":"web_search"}]}`, "relay.example", + []string{"reasoning.encrypted_content", "web_search_call.action.sources"}}, + {"sources once", `{"model":"m","input":"hi","include":["web_search_call.action.sources","web_search_call.action.sources"],"tools":[{"type":"web_search"}]}`, "relay.example", + []string{"web_search_call.action.sources"}}, + {"xAI keeps the client's only", `{"model":"m","input":"hi","reasoning":{"effort":"low"},"include":["reasoning.encrypted_content"],"tools":[{"type":"web_search"}]}`, "api.x.ai", + []string{"reasoning.encrypted_content"}}, + // OpenAI refuses sealed reasoning of a model that isn't reasoning + {"no reasoning, no sealed reasoning", `{"model":"m","input":"hi","include":["reasoning.encrypted_content","message.output_text.logprobs"]}`, "relay.example", + []string{"message.output_text.logprobs"}}, + {"none", `{"model":"m","input":"hi"}`, "relay.example", nil}, + } { + if got := include(c.body, c.host); !slices.Equal(got, c.want) { + t.Errorf("%s: include %q, want %q", c.name, got, c.want) + } + } +} + +// The way #315 met it: Codex offering web search to a Responses provider +// magpie doesn't know searches by itself goes through magpie's search, and +// the request its provider gets still asks for sealed reasoning. +func TestCodexSearchKeepsInclude(t *testing.T) { + f := &fake{t: t, reply: sse( + `data: {"type":"response.created","response":{"id":"resp_1","status":"in_progress","output":[]}}`, + `data: {"type":"response.output_item.done","output_index":0,"item":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"sunny"}]}}`, + `data: {"type":"response.completed","response":{"id":"resp_1","status":"completed","output":[],"usage":{"input_tokens":9,"output_tokens":2,"total_tokens":11}}}`)} + setup(t, provider.Responses, f) + code, body := codexPost(t, `{"model":"fake/m1","instructions":"You are Codex","stream":true,"store":false, + "include":["reasoning.encrypted_content"],"prompt_cache_key":"thread-1","reasoning":{"effort":"medium"}, + "tools":[{"type":"web_search"}],"input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"weather?"}]}]}`) + if code != 200 { + t.Fatalf("%d %s", code, body) + } + var q struct { + Include []string `json:"include"` + CacheKey string `json:"prompt_cache_key"` + } + json.Unmarshal(f.got, &q) + if !slices.Contains(q.Include, "reasoning.encrypted_content") || q.CacheKey != "thread-1" { + t.Errorf("provider got %s", f.got) + } +} diff --git a/internal/gateway/search.go b/internal/gateway/search.go index a6d1dd62b..f6de2a4b1 100644 --- a/internal/gateway/search.go +++ b/internal/gateway/search.go @@ -40,6 +40,23 @@ func searching(ctx context.Context) bool { return v } +// searchForKey holds the request magpie's searches are run for, which the +// Routing view names by a search's row: magpie's own call, on the model it +// searches with, not the conversation's (#314). +type searchForKey struct{} + +// CallFor is the request a call magpie made on its own was made for: its +// agent, and the model that agent asked for. +type CallFor struct { + Agent string `json:"agent"` + Model string `json:"model"` +} + +func searchFor(ctx context.Context) *CallFor { + f, _ := ctx.Value(searchForKey{}).(*CallFor) + return f +} + // searchesItself says whether the provider searches the web by itself when // asked on this API. func searchesItself(p provider.Provider, proto provider.Protocol) bool { @@ -245,7 +262,7 @@ type round func(ctx context.Context, req *Request) (<-chan Event, int, string) // reply. The first round's failure is a status, as another provider may // take over. func (s *Server) searchReply(w http.ResponseWriter, r *http.Request, from provider.Protocol, name string, req *Request, usage *Usage, ask round) (int, string) { - ctx, cancel := context.WithCancel(r.Context()) + ctx, cancel := context.WithCancel(context.WithValue(r.Context(), searchForKey{}, &CallFor{Agent: agentOf(r), Model: unprefixed(req.Model)})) defer cancel() q := *req q.WebSearch = false diff --git a/internal/gateway/side_call_kind_test.go b/internal/gateway/side_call_kind_test.go new file mode 100644 index 000000000..be933df52 --- /dev/null +++ b/internal/gateway/side_call_kind_test.go @@ -0,0 +1,119 @@ +package gateway + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// A call Codex makes on a hidden thread of its own — the title of a new +// chat — comes without x-openai-subagent; its turn metadata names the +// thread's source (#314). magpie's own web search says so too. +func TestCallKindThreadSource(t *testing.T) { + for want, h := range map[string]map[string]string{ + "thread_title": {"x-codex-turn-metadata": `{"session_id":"s","thread_source":"thread_title","turn_id":"t"}`}, + "guardian_review": {"x-codex-turn-metadata": `{"thread_source":"guardian_review"}`}, + "guardian": {"x-openai-subagent": "guardian", "x-codex-turn-metadata": `{"thread_source":"guardian_review"}`}, + "web_search": {"User-Agent": SearchAgent}, + "": {"x-codex-turn-metadata": `{"thread_source":"user","turn_id":"t"}`, "User-Agent": "codex_cli_rs/0.159.2"}, + } { + hh := http.Header{} + for k, v := range h { + hh.Set(k, v) + } + if got := callKind(hh); got != want { + t.Errorf("%v: %q, want %q", h, got, want) + } + } + for _, meta := range []string{"", "{", `{"thread_source":"subagent"}`, `{"turn_id":"t"}`} { + if got := threadSource(meta); got != "" { + t.Errorf("threadSource(%q) = %q", meta, got) + } + } +} + +// The searches magpie runs for a model that can't search are its own +// calls, on the model it searches with: the Routing view is told they are +// web searches, and for which agent's model (a DeepSeek chat in Codex +// showed Codex's GPT answering, #314). +func TestWebSearchCallSaysWhose(t *testing.T) { + search := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/v1/models": + io.WriteString(w, `{"data":[{"id":"claude-haiku-4-5"}]}`) + case "/v1/messages": + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"id":"s","type":"message","role":"assistant","model":"claude-haiku-4-5","content":[ + {"type":"text","text":"Sunny in Changsha."}],"stop_reason":"end_turn","usage":{"input_tokens":5,"output_tokens":5}}`) + default: + http.NotFound(w, r) + } + })) + defer search.Close() + n := 0 + model := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.ReadAll(r.Body) + n++ + w.Header().Set("Content-Type", "text/event-stream") + if n == 1 { + io.WriteString(w, sse(`data: {"id":"c","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"web_search","arguments":"{\"query\":\"changsha weather\"}"}}]}}]}`, + `data: {"id":"c","choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}`, `data: [DONE]`)) + return + } + io.WriteString(w, sse(`data: {"id":"d","choices":[{"index":0,"delta":{"role":"assistant","content":"Sunny."}}]}`, + `data: {"id":"d","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`, `data: [DONE]`)) + })) + defer model.Close() + + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + t.Setenv("HOME", t.TempDir()) + hosts := searchHosts[provider.Anthropic] + searchHosts[provider.Anthropic] = append(hosts, provider.HostOf(search.URL)) + defer func() { searchHosts[provider.Anthropic] = hosts }() + for _, p := range []provider.Provider{ + {ID: "srch", Name: "Search", Key: "k", Anthropic: search.URL}, + {ID: "deep", Name: "Deep", Key: "k", Chat: model.URL, Models: []string{"deep-chat"}}, + } { + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + } + p, _ := provider.Find("srch") + if _, err := p.Fetch(context.Background()); err != nil { + t.Fatal(err) + } + + s := New() + body := `{"model":"deep/deep-chat","messages":[{"role":"user","content":"长沙最近天气"}],"web_search_options":{}}` + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(body)) + req.Header.Set("User-Agent", "codex_cli_rs/0.159.2") + s.Handler().ServeHTTP(rec, req) + if rec.Code != 200 || !strings.Contains(rec.Body.String(), "Sunny.") { + t.Fatalf("%d %s", rec.Code, rec.Body.String()) + } + var turn, searched *Route + for _, r := range s.Trace(context.Background(), 0, 0).Routes { + switch r.Model { + case "deep/deep-chat": + turn = &r + case "srch/claude-haiku-4-5": + searched = &r + } + } + if turn == nil || searched == nil { + t.Fatalf("routes: turn %v, search %v", turn, searched) + } + if turn.Kind != "" || turn.For != nil { + t.Errorf("the turn is the agent's own: kind %q for %+v", turn.Kind, turn.For) + } + if searched.Kind != "web_search" || searched.For == nil || searched.For.Model != "deep/deep-chat" || searched.For.Agent != agentOf(req) { + t.Errorf("the search: kind %q for %+v, want web_search for %s's deep/deep-chat", searched.Kind, searched.For, agentOf(req)) + } +} diff --git a/internal/gateway/trace.go b/internal/gateway/trace.go index 20d2a2f26..74a741807 100644 --- a/internal/gateway/trace.go +++ b/internal/gateway/trace.go @@ -28,6 +28,7 @@ type Route struct { Time time.Time `json:"time"` Agent string `json:"agent"` Kind string `json:"kind,omitempty"` // what the call is for, as Call's + For *CallFor `json:"for,omitempty"` // the request it was made for, as Call's Model string `json:"model"` // as the agent asked Effort string `json:"effort,omitempty"` // the reasoning the agent asked for; "" for none Provider string `json:"provider"` // the provider the model resolved to diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 1accc20df..7d83e855c 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -1359,6 +1359,9 @@ const I18N = { "Title": "标题", "Subagent": "子代理", "Luna Reserve": "Luna 储备", + "Web search": "联网搜索", + "magpie ran this web search for {agent}'s {model}, which can't search the web by itself: {searcher} searched, and {model} goes on answering once it has what was found. Not a turn of the conversation.": "这是 magpie 替 {agent} 的 {model} 发起的联网搜索:{model} 自己不能搜索网页,由 {searcher} 去搜,{model} 拿到搜索结果后才接着回答。它不是对话中的一轮。", + "magpie ran this web search for a model that can't search the web by itself: {searcher} searched, and that model goes on answering once it has what was found. Not a turn of the conversation.": "这是 magpie 替一个自己不能搜索网页的模型发起的联网搜索:由 {searcher} 去搜,那个模型拿到搜索结果后才接着回答。它不是对话中的一轮。", "{agent} sent this turn on Luna Reserve, which it turns to once the plan's own allowance is used up; it picks the model itself.": "{agent} 用 Luna 储备发出了这一轮:套餐自己的额度用完后它会改用 Luna 储备,模型由它自己决定。", "{agent} made this call itself ({kind}), not as a turn of the conversation, and picks its model itself.": "这是 {agent} 自己发起的调用({kind}),不是对话中的一轮,模型由它自己决定。", "Nothing was tried: {error}": "没有尝试任何账号:{error}", diff --git a/internal/gui/assets/routing.js b/internal/gui/assets/routing.js index 41ba526fb..3c8a53a75 100644 --- a/internal/gui/assets/routing.js +++ b/internal/gui/assets/routing.js @@ -958,7 +958,9 @@ // what a call was for when it isn't a turn of the conversation, as // Codex names it (x-openai-subagent): its own guardian review of an // approval, a thread's title, memories… — each on the model Codex picks - // for it, so a list of Luna calls under a Sol composer reads as it is + // for it, so a list of Luna calls under a Sol composer reads as it is. + // A web search is magpie's own, run for a model that can't search on the + // model it searches with (a DeepSeek chat showing GPT calls, #314) const KIND = { guardian: "Approval check", auto_review: "Approval check", guardian_review: "Approval check", review: "Review", compact: "Compaction", @@ -966,6 +968,7 @@ thread_title: "Title", title: "Title", collab_spawn: "Subagent", thread_spawn: "Subagent", agent_job: "Subagent", luna_reserve: "Luna Reserve", + web_search: "Web search", }; const kindName = (k) => KIND[k] ? t(KIND[k]) : k; function kindTag(r) { @@ -986,6 +989,9 @@ function kindWhy(r) { const agent = agentName(r.agent); if (r.kind === "luna_reserve") return t("{agent} sent this turn on Luna Reserve, which it turns to once the plan's own allowance is used up; it picks the model itself.", { agent }); + if (r.kind === "web_search") return r.for + ? t("magpie ran this web search for {agent}'s {model}, which can't search the web by itself: {searcher} searched, and {model} goes on answering once it has what was found. Not a turn of the conversation.", { agent: agentName(r.for.agent), model: r.for.model, searcher: r.model }) + : t("magpie ran this web search for a model that can't search the web by itself: {searcher} searched, and that model goes on answering once it has what was found. Not a turn of the conversation.", { searcher: r.model }); return t("{agent} made this call itself ({kind}), not as a turn of the conversation, and picks its model itself.", { agent, kind: kindName(r.kind) }); } diff --git a/internal/gui/tests/README.md b/internal/gui/tests/README.md index 7ccba7f11..815c46bc8 100644 --- a/internal/gui/tests/README.md +++ b/internal/gui/tests/README.md @@ -72,6 +72,14 @@ a title, memories, a turn on Luna Reserve, a kind it does not know yet): each has a grey tag by its model in the Requests list, in English and Chinese, the model keeping its room first, and the request's story says what it was. +`routing-side-calls.test.cjs` lists what a DeepSeek chat in Codex sends besides +its turns (#314): the new chat's title, which Codex asks of its own Luna on a +hidden thread (known by its turn metadata), and the web searches magpie runs +for DeepSeek on the model it searches with. Each has its grey tag (Title / +标题, Web search / 联网搜索), a search's story names the agent and model it +was for, and picking a request moves nothing. Chromium and WebKit, English +and Chinese. + `routing-effort-row.test.cjs` lists live requests sent at high reasoning, one under way, one with two tries, in Chromium and WebKit, English and Chinese, at 1440, 1000 and 480px: in every row the "· high" is shown whole and no run of @@ -330,7 +338,7 @@ that draws the latest numbers. The checks run in English and Chinese. With Node.js and Playwright available: ```sh -node --test internal/gui/tests/menu-scroll.test.cjs internal/gui/tests/click-scroll.test.cjs internal/gui/tests/panel-fold.test.cjs internal/gui/tests/panel-routing.test.cjs internal/gui/tests/gateway-fold.test.cjs internal/gui/tests/routing-kind.test.cjs internal/gui/tests/balance-fix.test.cjs internal/gui/tests/cli-update.test.cjs internal/gui/tests/login-import.test.cjs internal/gui/tests/agy-launch.test.cjs internal/gui/tests/currency.test.cjs internal/gui/tests/usage-ledger.test.cjs internal/gui/tests/update-check.test.cjs internal/gui/tests/omarchy.test.cjs internal/gui/tests/brand.test.cjs node --test internal/gui/tests/signin-callback.test.cjs internal/gui/tests/routing-steady.test.cjs internal/gui/tests/old-webkit.test.cjs internal/gui/tests/session-terminal.test.cjs internal/gui/tests/text-size.test.cjs internal/gui/tests/zcode-site.test.cjs internal/gui/tests/rail-tip.test.cjs internal/gui/tests/sync-update.test.cjs internal/gui/tests/plugin-signin.test.cjs internal/gui/tests/plugin-market.test.cjs internal/gui/tests/s3-sync.test.cjs internal/gui/tests/routing-wb-refused.test.cjs internal/gui/tests/market-have.test.cjs internal/gui/tests/sessions-today.test.cjs +node --test internal/gui/tests/menu-scroll.test.cjs internal/gui/tests/click-scroll.test.cjs internal/gui/tests/panel-fold.test.cjs internal/gui/tests/panel-routing.test.cjs internal/gui/tests/gateway-fold.test.cjs internal/gui/tests/routing-kind.test.cjs internal/gui/tests/balance-fix.test.cjs internal/gui/tests/cli-update.test.cjs internal/gui/tests/login-import.test.cjs internal/gui/tests/agy-launch.test.cjs internal/gui/tests/currency.test.cjs internal/gui/tests/usage-ledger.test.cjs internal/gui/tests/update-check.test.cjs internal/gui/tests/omarchy.test.cjs internal/gui/tests/brand.test.cjs node --test internal/gui/tests/signin-callback.test.cjs internal/gui/tests/routing-steady.test.cjs internal/gui/tests/old-webkit.test.cjs internal/gui/tests/session-terminal.test.cjs internal/gui/tests/text-size.test.cjs internal/gui/tests/zcode-site.test.cjs internal/gui/tests/rail-tip.test.cjs internal/gui/tests/sync-update.test.cjs internal/gui/tests/plugin-signin.test.cjs internal/gui/tests/plugin-market.test.cjs internal/gui/tests/s3-sync.test.cjs internal/gui/tests/routing-wb-refused.test.cjs internal/gui/tests/market-have.test.cjs internal/gui/tests/sessions-today.test.cjs internal/gui/tests/routing-side-calls.test.cjs ``` If Playwright is installed outside the repository, set `NODE_PATH` to the diff --git a/internal/gui/tests/routing-side-calls.test.cjs b/internal/gui/tests/routing-side-calls.test.cjs new file mode 100644 index 000000000..fe323bcef --- /dev/null +++ b/internal/gui/tests/routing-side-calls.test.cjs @@ -0,0 +1,112 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A DeepSeek chat in Codex showed Codex's GPT answering in the Requests +// list (#314: 为啥 deepseek 对话会调用 gpt): the new chat's title, which +// Codex asks of gpt-6-luna on a hidden thread of its own, and the web +// searches magpie runs for DeepSeek on the model it searches with. Each +// says what it was by its model, and the search's story whose it was. +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 now = new Date(); +const day = [now.getFullYear(), now.getMonth() + 1, now.getDate()].map((n) => String(n).padStart(2, "0")).join("-"); +const at = (i) => new Date(now.getTime() - (i + 1) * 60e3).toISOString(); +const seat = (model, provider) => ({ id: provider, provider, name: provider === "codex" ? "Codex" : "DeepSeek", who: "a@b.c", kind: provider === "codex" ? "account" : "key", model }); +const call = (id, i, agent, model, provider, extra) => ({ + id, seq: id, time: at(i), agent, model: provider + "/" + model, provider, ...extra, + order: [seat(model, provider)], tries: [{ id: provider, model, start: at(i), done: true, status: 200, ms: 900 }], + done: true, status: 200, ms: 900, tokens: 1200, +}); +const routes = [ + call(104, 0, "magpie", "gpt-6.1-sol", "codex", { kind: "web_search", for: { agent: "codex", model: "deepseek/deepseek-flash" } }), + call(103, 1, "magpie", "gpt-6.1-sol", "codex", { kind: "web_search" }), + call(102, 2, "codex", "deepseek-flash", "deepseek", {}), + call(101, 3, "codex", "gpt-6-luna", "codex", { kind: "thread_title" }), +]; + +function serve(lang) { + const state = { + agents: [{ id: "codex", name: "Codex", path: "/test/config.toml", fields: [] }], + clients: [{ id: "codex", name: "Codex", icon: "codex-color" }, { id: "magpie", name: "magpie", icon: "magpie" }], + 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/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/gateway/trace") { + if (url.searchParams.get("wait")) await new Promise((r) => setTimeout(r, 20e3)); + return json({ mine: true, now: now.toISOString(), seq: 1, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] }); + } + if (url.pathname === "/api/gateway/history") { + const d = url.searchParams.get("day"); + return json({ cut: false, days: [{ day, requests: routes.length }], routes: d ? routes : [] }); + } + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/providers") return json({ providers: [], gateway: { running: true, window: true } }); + 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)]; + const body = await fs.readFile(file).catch(() => null); + await (body ? route.fulfill({ body, contentType }) : route.fulfill({ status: 404, body: "" })); + }; +} + +const want = { + en: { tags: ["Web search", "Web search", "", "Title"], story: /magpie ran this web search for Codex's deepseek\/deepseek-flash, which can't search the web by itself: codex\/gpt-6\.1-sol searched/, bare: /for a model that can't search the web by itself: codex\/gpt-6\.1-sol searched/, title: /Codex made this call itself \(Title\)/ }, + zh: { tags: ["联网搜索", "联网搜索", "", "标题"], story: /magpie 替 Codex 的 deepseek\/deepseek-flash 发起的联网搜索.*由 codex\/gpt-6\.1-sol 去搜/, bare: /替一个自己不能搜索网页的模型发起的联网搜索:由 codex\/gpt-6\.1-sol 去搜/, title: /这是 Codex 自己发起的调用(标题)/ }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh"]) { + test(`${engine} ${lang}: a title and magpie's web search say what they were`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const context = await browser.newContext({ viewport: { width: 1100, height: 760 }, reducedMotion: "reduce" }); + const page = await context.newPage(); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang)); + t.after(async () => { + if (process.env.ARTIFACT_DIR) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-side-calls.png`), fullPage: true }); + } + await browser.close(); + }); + await page.goto("http://magpie.test/?view=routing"); + await page.locator(".rt-day").nth(1).click(); + await page.locator(".rt-req").nth(routes.length - 1).waitFor(); + + const tags = await page.locator(".rt-req").evaluateAll((rows) => rows.map((r) => r.querySelector(".asked .kind")?.textContent || "")); + assert.deepEqual(tags, want[lang].tags); + + const story = async (i) => { + const row = page.locator(".rt-req").nth(i); + const was = await row.evaluate((e) => e.getBoundingClientRect().top); + const scrolled = await page.evaluate(() => document.scrollingElement.scrollTop); + await row.click(); + await page.waitForTimeout(400); + assert(Math.abs((await row.evaluate((e) => e.getBoundingClientRect().top)) - was) <= 1, "picking the request moved the row"); + assert.equal(await page.evaluate(() => document.scrollingElement.scrollTop), scrolled, "picking the request scrolled the page"); + return page.locator(".rt-steps li.kind"); + }; + let s = await story(0); + assert.equal(await s.locator(".kind").textContent(), want[lang].tags[0]); + assert.match(await s.textContent(), want[lang].story); + s = await story(1); + assert.match(await s.textContent(), want[lang].bare); + s = await story(3); + assert.match(await s.textContent(), want[lang].title); + s = await story(2); + assert.equal(await s.count(), 0); + assert.deepEqual(errors, []); + }); + } +}