gateway, gui: routing history keeps the last two levels of the folder an agent works in, and By session, the stage and the panel name it (#1068, emo172)
Routes now carry Folder: the last two levels of the working directory the agent states (Claude Code's "Primary working directory", Codex's <cwd>, Pi, OpenCode), cut by shortFolder before the route is stored, so no full path reaches the routing history, /api, or the GUI. It is kept in the routing history for as long as the history itself (30 days / 200 MB). A request that states no folder (title, side calls) takes the folder its session (or parent session) last stated; the per-session map is capped at 512 entries. GUI: By session headings read "Agent · folder · title", their tooltip and every request row's tooltip (page and tray panel) name the folder, the stage's agent subtitle lists the last level of each folder when an agent works in more than one, and the panel's agent node tooltip lists them. Run: - TestShortFolder (unix, trailing slash, C:\, D:\, UNC, CJK with spaces) and TestRouteKeepsItsFolderShort (real Handler, fake upstream: session inheritance, a moved Windows path, nothing of the full path in the marshalled routes, saveRoute -> History round trip), TestTurnDone. Broke it by hand: without the session lookup the title request has no folder; with the folder unshortened the full path shows. Both go red. - routing-session-folder.test.cjs: chromium + webkit x en, zh, zh-TW, ja, de x 1100 and 420 px, 20/20. Red on the old routing.js and with the stage's live routes left out. - GUI suites routing-*, panel-routing*, purpose-filter, reasoning-speed, gui-de/ja/zh-tw, click-scroll, number-units: 951/951. - gofmt -l clean; go vet darwin, linux (nogui), windows; builds for all three. go test -tags nogui ./...: all ok except internal/gateway, which hit go test's default 10m timeout at 611s on a loaded machine (#2108); alone with -timeout 30m it passes in 356s. - Real use: nogui build in a sandbox HOME, fake upstream, real Claude Code 2.1.299 (claude -p) run from .../workspace/magpie and .../src/dial: the day's routing jsonl has folder "workspace/magpie" and "src/dial" and no part of the sandbox path above them. Not tried: title/side requests' inheritance end to end with a real agent (claude -p made none), Codex, OpenCode and Pi with real binaries, Windows.
This commit is contained in:
@@ -26,7 +26,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md).
|
||||
| Image generation | `/v1/images/generations` and `/v1/images/edits` are translated to the selected model's image API. OpenRouter image-only models use its `/images` endpoint and send reference images as `input_references`; OpenRouter models that return images through chat stay on Chat Completions. A routing group named for a drawing or a video (`drawingGroup`: `group/<id>`, or a bare id the group goes by that resolved to one of its members) is tried member by member in the order its routing plans for a chat (`drawingTries` over `planGroup`), each member over its own keys or accounts (`drawOnAccounts`, `startVideo`); the next member is asked while one fails as a chat's would move on (`retryable`: its vendor 5xx, out of quota, the model not served), never for a refusal of the request itself, and the call's `Fallback` names those tried first (#2005, tianxia3111: a group of two relays answered the first one's 502). Pause rules and a gateway key's group hold apply as for a chat. Nothing rests for a failed drawing. `TestImageGroupMovesOnToTheNextMember`, `TestVideoGroupMovesOnToTheNextMember`. | [`draw.go`](../../internal/gateway/draw.go), [`video.go`](../../internal/gateway/video.go), [`catalog.go`](../../internal/catalog/catalog.go) |
|
||||
| Affinity | A conversation stays with the key or account that answered it, so the vendor's prompt cache is read again. Modes: auto (""), `session`, `turn`, `off`, `strict`. Stored in `affinity.json` next to `providers.json`. | [`affinity.go`](../../internal/gateway/affinity.go) |
|
||||
| One try | `attempt` sends one candidate the request. It goes through the proxy of the account or key it uses, else the provider's (`p.Via`, `ProxyChoice`: `AccountProxies` holds an account's by its name, a key's by its `KeyID`). A request magpie makes for one provider while serving another's (a web search, an image description, a classifier call) takes its own provider's proxy or the global one, never the outer one: `netproxy.With` replaces a choice the context already names, "" too, and `webSearch` starts from none, so the search APIs follow the global proxy (#1522). A subscription with its own client is served specially, such as Claude through the genuine Claude Code. The request is relayed as is (`passthrough`) when the model is usable on the agent's API, except that a Claude model where the provider has an Anthropic URL is translated to Messages from Chat or Responses too (`OnMessages`: OpenCode speaks Chat for every model, and a relay drops cache_control there), unless the user set the model's API or the vendor's list names its APIs. A request offering web search to a provider that doesn't search by itself is translated too, so magpie can search for it (`search.go`; a provider that searches for some of its models only, Command Code's Provider API, lists them in `searchModels` by API, and none count under its `x-cmd-zdr` header, #1590), but on the agent's own API where the provider serves it and no `ResponsesFirst`/`MessagesFirst` rule prefers another: Codex offers web_search on every turn, and each went out as Chat (#997). Otherwise it is translated (`translate`) to the first API `usable` gives: Chat, except Responses for OpenAI's models where their maker serves them (`ResponsesFirst`), Responses for every model at ModelScope, whose Chat API reports neither the tokens its cache answered nor reasoning while its Responses API reports both (`ResponsesTellsCache`, #1578; a 404 there sends the model to Chat, and only there), and Anthropic's Messages for a Claude model where the provider has an Anthropic URL (`MessagesFirst`, which keeps its cache breakpoints, #997). An API that answers the model is not served there (`wrongEndpoint`) is remembered in `unfit` until magpie restarts. When every API has turned the model away, the API the user picked for it (`ModelAPI`) is asked again, and without a pick each API the provider has a URL for (`Speaks`), Chat first. `Provider.Native`, the API agents with a per-model API (Pi, omp, droid) are wired to ask on, follows the same order. A custom provider with a Gemini URL (#1346) has Gemini last among the APIs it speaks: a Gemini client's request is relayed there, and any other is translated to it when it has no other, or when the user set Gemini as the model's API (`SetModelAPI` takes chat, responses, anthropic or gemini, each only where the provider has its URL; a model set to Gemini has no `Native`, so those agents ask it on their own API and it is translated). Upstream it is always asked `models/{model}:streamGenerateContent?alt=sse` under the base (`upstreamPath`), the model only in the path (`forwardOnce` drops the body's), so a Gemini client that asked for one JSON body is translated, as for Factory's generate route. | [`gateway.go`](../../internal/gateway/gateway.go) |
|
||||
| Trace | The Routing view's record of each decision, written where the decision is made: candidates, rests, which try answered. | [`trace.go`](../../internal/gateway/trace.go) |
|
||||
| Trace | The Routing view's record of each decision, written where the decision is made: candidates, rests, which try answered. `Route.Folder` is the folder the agent says it works in (`workDir`), its last two levels only (`shortFolder`, e.g. `workspace/magpie`), never the full path; a request that says none (a title, a topic check) takes its session's as said last (`trace.sessionFolder`), one without a session id has none (#1068). It is kept in the routing history on disk for as long as the route is (`history.go`: 30 days, 200 MB). The GUI shows it in By session's headings, a request row's tooltip, the stage's agent working in more than one folder, and the tray panel's agent tooltip. | [`trace.go`](../../internal/gateway/trace.go) |
|
||||
| Prompt | What each request's prompt held, part by part: the agent's system prompt, tool definitions (an MCP server's tools as one item), instruction files and skills, files its tools read, their other output, and the conversation. `inspectPrompt` reads it from the body as the agent sent it, before translation; `calibrated` scales the estimate to the prompt the vendor counted and sets the window of the model that answered. The route keeps names and sizes only, never the text, so the routing history on disk holds none. For the card's text (masaka on Discord), the trace keeps the last `promptBodies` (10) request bodies in memory only (at most 32 MiB each, 64 MiB together), masked as the vendor got them; for a model let have it unmasked, the masked copy is kept all the same. `PromptText` reads a part's items and their text from that body again (`prompt_text.go`), served to the GUI as `/api/context/text`; once a body is dropped, or magpie quits, its text is gone. It goes on the trace as `Route.Prompt`, with `Route.Conv` naming a conversation that has no session id. The GUI's `/api/context` scores each agent from it (`internal/gui/context.go`). | [`prompt.go`](../../internal/gateway/prompt.go) |
|
||||
| Vertex AI | A [Google Vertex AI provider](providers-accounts.md#responsibilities-and-sources-of-truth) speaks Gemini alone. A request goes to `<base>/publishers/google/models/<model>:streamGenerateContent?alt=sse` (`provider.VertexPath`, `upstreamPath`), the model named as the user's upstream name for it says (`UpstreamNameIn`, which the usage log's endpoint names too), with no `model` or `stream` field in its body (`passthrough`, `forwardOnce`, `geminiRequest`). A Gemini client's request is relayed as it came, its own `thinkingConfig`, `safetySettings` and the rest kept: streamed there, asked whole to `:generateContent` (`provider.VertexWholePath`), which answers one JSON body (Factory's rule of translating a whole request, as its route only streams, isn't Vertex AI's). Every other API's is translated (`buildFor`, `buildVertex`) and its stream read by `codeAssistDecoder`, which gives thought parts as reasoning, never as the answer's text. Effort: `vertexEffort` fits it to the model's levels, reasoning turned off going as `minimal` fitted the same way, and holds a model whose levels aren't known to `low`…`high`. `vertexThinking` sends Gemini 3 a `thinkingLevel` (`includeThoughts` false with reasoning off) and 2.5 a `thinkingBudget` in the model's range (`vertexBudgets`): turned off, the budget that stops its thinking, or Pro's least, as Pro can't stop. Thought signatures are every Gemini path's (#1445): a call's signature reaches the client in its id (`signedID`) and goes back on the call it came on, while a call with none in a step Vertex AI signed goes without; a step with nothing to give back has every call sent `skip_thought_signature_validator`. A 400 `Invalid thought signature.` is asked again with every call sent so (`withoutSignatures`), for that request only. A 400 refusing `minimal` (`geminiRefusedLevel`) is asked again at the model's lowest other level (`onEffort`), and `markUnfit(offRefused)` keeps that level until magpie restarts. Both retries are the translated path's. Vertex AI's own Google Search grounding isn't used: `searchHosts` names only `generativelanguage.googleapis.com` for Gemini, so magpie searches for it (`search.go`). | [`vertex.go`](../../internal/gateway/vertex.go), [`gateway.go`](../../internal/gateway/gateway.go), [`codeassist.go`](../../internal/gateway/codeassist.go), [`gemini.go`](../../internal/gateway/gemini.go), [`gemini_signature.go`](../../internal/gateway/gemini_signature.go), [`search.go`](../../internal/gateway/search.go) |
|
||||
|
||||
|
||||
@@ -102,6 +102,10 @@ type Route struct {
|
||||
// Conv: the conversation a request without a session id is part of,
|
||||
// as a digest of its first user turn (conversationID)
|
||||
Conv string `json:"conv,omitempty"`
|
||||
// Folder: the last two levels of the folder its agent says it works
|
||||
// in (shortFolder), never the whole path; a request that says none
|
||||
// takes its session's, as said last (#1068)
|
||||
Folder string `json:"folder,omitempty"`
|
||||
}
|
||||
|
||||
// RouteUsage is one billable attempt's pricing inputs, kept in routing history.
|
||||
@@ -410,6 +414,14 @@ type trace struct {
|
||||
bodies []keptBody
|
||||
// turns follows agents' turns, to say when one is done (TurnDone)
|
||||
turns turns
|
||||
// folders: each session's folder, as its requests said it last, for
|
||||
// the requests that don't say it (a title, a topic check)
|
||||
folders map[string]sessionFolder
|
||||
}
|
||||
|
||||
type sessionFolder struct {
|
||||
folder string
|
||||
at time.Time
|
||||
}
|
||||
|
||||
// Totals count the requests routed since the gateway started.
|
||||
@@ -443,8 +455,16 @@ func (t *trace) beginFor(req *http.Request, r Route) *Route {
|
||||
}
|
||||
|
||||
func (t *trace) begin(r Route) *Route {
|
||||
// the body is read for its folder before the lock: a long one takes
|
||||
// a while, and every route waits on the lock
|
||||
if r.dirOf != nil {
|
||||
dir := r.dirOf()
|
||||
r.dirOf = func() string { return dir }
|
||||
r.Folder = shortFolder(dir)
|
||||
}
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
t.sessionFolder(&r, time.Now())
|
||||
if t.ids == 0 {
|
||||
// ids go on from one run to the next, the history keeping them
|
||||
// all: counted on from the time the gateway began
|
||||
@@ -464,6 +484,63 @@ func (t *trace) begin(r Route) *Route {
|
||||
return rp
|
||||
}
|
||||
|
||||
// foldersKeep is how many sessions' folders are kept, the oldest said
|
||||
// going first when there are more.
|
||||
const foldersKeep = 512
|
||||
|
||||
// sessionFolder gives r its session's folder when it says none, and keeps
|
||||
// the one it says for those that come after: an agent's requests on the
|
||||
// side, a title or a topic check, have no full system prompt to say it.
|
||||
// A request with no session id has only its own (#1068).
|
||||
func (t *trace) sessionFolder(r *Route, now time.Time) {
|
||||
key := func(s string) string {
|
||||
if s == "" {
|
||||
return ""
|
||||
}
|
||||
return r.Agent + "\x00" + s
|
||||
}
|
||||
own, parent := key(r.Session), key(r.ParentSession)
|
||||
if r.Folder == "" {
|
||||
for _, k := range []string{own, parent} {
|
||||
if f, ok := t.folders[k]; ok && k != "" {
|
||||
r.Folder = f.folder
|
||||
return
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
if own == "" {
|
||||
return
|
||||
}
|
||||
if t.folders == nil {
|
||||
t.folders = map[string]sessionFolder{}
|
||||
}
|
||||
t.folders[own] = sessionFolder{r.Folder, now}
|
||||
for len(t.folders) > foldersKeep {
|
||||
oldest := ""
|
||||
for k, f := range t.folders {
|
||||
if oldest == "" || f.at.Before(t.folders[oldest].at) {
|
||||
oldest = k
|
||||
}
|
||||
}
|
||||
delete(t.folders, oldest)
|
||||
}
|
||||
}
|
||||
|
||||
// shortFolder is the last two levels of dir, "/"-joined: enough to tell
|
||||
// one project from another, without the rest of the path (#1068). A
|
||||
// Windows drive is no level; "" for none.
|
||||
func shortFolder(dir string) string {
|
||||
parts := strings.FieldsFunc(strings.TrimSpace(dir), func(c rune) bool { return c == '/' || c == '\\' })
|
||||
if len(parts) > 0 && len(parts[0]) == 2 && parts[0][1] == ':' {
|
||||
parts = parts[1:]
|
||||
}
|
||||
if len(parts) > 2 {
|
||||
parts = parts[len(parts)-2:]
|
||||
}
|
||||
return strings.Join(parts, "/")
|
||||
}
|
||||
|
||||
// trim keeps traceKeep routes, the oldest finished ones going first: a
|
||||
// request still going isn't dropped for those that came after it (#436),
|
||||
// as the history has only finished ones, unless more than twice traceKeep
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
func TestShortFolder(t *testing.T) {
|
||||
for dir, want := range map[string]string{
|
||||
"/Users/someone/secret/workspace/magpie": "workspace/magpie",
|
||||
"/Users/someone/secret/workspace/magpie/": "workspace/magpie",
|
||||
`C:\Users\someone\src\magpie`: "src/magpie",
|
||||
`D:\magpie`: "magpie",
|
||||
`C:\`: "",
|
||||
`\\server\share\team\magpie`: "team/magpie",
|
||||
"/magpie": "magpie",
|
||||
"/": "",
|
||||
"": "",
|
||||
"/home/u/my project/中文 目录": "my project/中文 目录",
|
||||
} {
|
||||
if got := shortFolder(dir); got != want {
|
||||
t.Errorf("shortFolder(%q) = %q, want %q", dir, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A route keeps the last two levels of the folder its agent says it works
|
||||
// in, and never the rest of the path (#1068): in the trace the page and
|
||||
// the agents' callers read, and in the history on disk. A request of the
|
||||
// same session that says none, as Claude Code's title request doesn't,
|
||||
// takes the session's; one with no session id has none.
|
||||
func TestRouteKeepsItsFolderShort(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
t.Setenv("XDG_CACHE_HOME", t.TempDir())
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
io.WriteString(w, `data: {"id":"c1","choices":[{"index":0,"delta":{"role":"assistant","content":"ok"}}]}`+"\n\n")
|
||||
io.WriteString(w, `data: {"id":"c1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`+"\n\n")
|
||||
io.WriteString(w, "data: [DONE]\n\n")
|
||||
}))
|
||||
defer srv.Close()
|
||||
if err := provider.Save(provider.Provider{ID: "plan", Name: "Plan", Chat: srv.URL + "/v1", Models: []string{"m1"}, Key: "k"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := New()
|
||||
send := func(body, session string) Route {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body))
|
||||
req.Header.Set("User-Agent", "claude-cli/2.1.296 (external, cli)")
|
||||
if session != "" {
|
||||
req.Header.Set("x-claude-code-session-id", session)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
s.Handler().ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("%d %s", rec.Code, rec.Body)
|
||||
}
|
||||
rs := s.Trace(context.Background(), 0, 0).Routes
|
||||
return rs[len(rs)-1]
|
||||
}
|
||||
// Claude Code's main request: its environment in a system block
|
||||
turn := `{"model":"plan/m1","stream":true,"max_tokens":100,"system":[{"type":"text","text":"You are Claude Code, Anthropic's official CLI for Claude."},{"type":"text","text":"# Environment\nYou have been invoked in the following environment: \n - Primary working directory: /Users/someone/secret/workspace/magpie\n - Is a git repository: true\n - Platform: darwin\n"}],"messages":[{"role":"user","content":"hi"}]}`
|
||||
// its title request: no environment
|
||||
title := `{"model":"plan/m1","stream":true,"max_tokens":100,"system":[{"type":"text","text":"Generate a concise, sentence-case title (3-7 words) that captures the main topic or goal of this coding session."}],"messages":[{"role":"user","content":"hi"}]}`
|
||||
|
||||
if r := send(turn, "s1"); r.Folder != "workspace/magpie" {
|
||||
t.Fatalf("the turn's folder: %q", r.Folder)
|
||||
}
|
||||
if r := send(title, "s1"); r.Folder != "workspace/magpie" {
|
||||
t.Fatalf("a request of the session that says no folder: %q", r.Folder)
|
||||
}
|
||||
if r := send(title, "s2"); r.Folder != "" {
|
||||
t.Fatalf("another session's: %q", r.Folder)
|
||||
}
|
||||
if r := send(title, ""); r.Folder != "" {
|
||||
t.Fatalf("no session id: %q", r.Folder)
|
||||
}
|
||||
// the folder said last goes: the agent moved
|
||||
moved := strings.Replace(turn, "/Users/someone/secret/workspace/magpie", `C:\\Users\\someone\\src\\dial`, 1)
|
||||
if r := send(moved, "s1"); r.Folder != "src/dial" {
|
||||
t.Fatalf("moved: %q", r.Folder)
|
||||
}
|
||||
if r := send(title, "s1"); r.Folder != "src/dial" {
|
||||
t.Fatalf("after the move: %q", r.Folder)
|
||||
}
|
||||
|
||||
// what the page gets, and what the history keeps on disk
|
||||
now := historyNoon(t)
|
||||
for _, r := range s.Trace(context.Background(), 0, 0).Routes {
|
||||
b, _ := json.Marshal(r)
|
||||
for _, leak := range []string{"someone", "secret", "Users"} {
|
||||
if strings.Contains(string(b), leak) {
|
||||
t.Fatalf("the route carries the folder's path (%s): %s", leak, b)
|
||||
}
|
||||
}
|
||||
r.Time = now
|
||||
saveRoute(r)
|
||||
}
|
||||
_, kept, _ := History(now.Format(dayForm))
|
||||
var folders []string
|
||||
for _, r := range kept {
|
||||
folders = append(folders, r.Folder)
|
||||
}
|
||||
if got := strings.Join(folders, ","); !strings.Contains(got, "workspace/magpie") || !strings.Contains(got, "src/dial") {
|
||||
t.Fatalf("the history's folders: %q", got)
|
||||
}
|
||||
}
|
||||
@@ -1153,6 +1153,10 @@
|
||||
return SPARE[h % SPARE.length];
|
||||
}
|
||||
|
||||
// foldersOf: the folders routes say, each once, in their order;
|
||||
// lastLevel, a folder's last level ("workspace/magpie" → "magpie")
|
||||
const foldersOf = (rs) => [...new Set(rs.map((r) => r.folder).filter(Boolean))];
|
||||
const lastLevel = (f) => f.split("/").pop();
|
||||
function agentNode(id) {
|
||||
let a = agents.get(id);
|
||||
if (a) return a;
|
||||
@@ -1327,7 +1331,13 @@
|
||||
const a = agents.get(id), r = rs.filter((x) => x.agent === id).pop(), ag = agentOf(id);
|
||||
if (a.icon !== (ag?.icon || "generic")) { a.icon = ag?.icon || "generic"; a.ic.replaceChildren(icon(a.icon)); }
|
||||
a.name.textContent = agentName(id);
|
||||
a.sub.textContent = r.model;
|
||||
// one agent working in more than one folder at once: which, by
|
||||
// their last level (#1068). The stage holds an agent's latest
|
||||
// request alone, so its others still going, or just done, count too.
|
||||
const n = now(), going = pinned ? [] : [...src().values()].filter((x) => x.agent === id && (!x.done || at(x.time) + (x.ms || 0) > n - LINGER));
|
||||
const fs = foldersOf([...new Set([...going, ...rs.filter((x) => x.agent === id)])].sort((x, y) => x.id - y.id));
|
||||
a.sub.textContent = fs.length > 1 ? fs.map(lastLevel).join(", ") : r.model;
|
||||
a.node.title = [agentName(id), r.model, ...fs.map((f) => t("Folder") + ": " + f)].join("\n");
|
||||
}
|
||||
// the account sets, the latest of each
|
||||
const latest = new Map();
|
||||
@@ -1976,11 +1986,13 @@
|
||||
// the row no longer says (#337)
|
||||
function reqTitle(r, how, tr) {
|
||||
const head = `${agentName(r.agent)} · ${r.model} → `;
|
||||
// the folder its agent works in, the last two levels of it (#1068)
|
||||
const folder = r.folder ? "\n" + t("Folder") + ": " + r.folder : "";
|
||||
const w = how !== "bad" && r.tries.length > 1 && tr && tried(r, tr);
|
||||
if (!w) return head + r.provider;
|
||||
if (!w) return head + r.provider + folder;
|
||||
const first = r.tries[0], f = tried(r, first);
|
||||
const from = f && seat(f) !== seat(w) ? "\n" + t("rerouted from {from}", { from: `${where(f)} · ${first.model || f.model}` }) : "";
|
||||
return head + `${where(w)} · ${tr.model || w.model}` + from;
|
||||
return head + `${where(w)} · ${tr.model || w.model}` + from + folder;
|
||||
}
|
||||
|
||||
// the requests the gateway keeps, newest first: pick one to see how it was routed
|
||||
@@ -2192,11 +2204,14 @@
|
||||
const memory = g.r.agent === "codex" && g.rows.every((r) => purposeOf(r.kind) === "kind:memory_consolidation");
|
||||
const suggestions = g.r.agent === "codex" && g.rows.every((r) => purposeOf(r.kind) === "kind:ambient_suggestions");
|
||||
const name = g.rows.find((r) => r.sessionTitle)?.sessionTitle || otherTitles.get(ownKey(g.r)) || (memory ? t("Background memory task") : suggestions ? t("Background prompt suggestions") : "");
|
||||
setText(x.name, g.key ? agentName(g.r.agent) + " · " + (name || groupSession(g.r)) : t("No session ID"));
|
||||
// the folder the session works in, as its latest request said it
|
||||
// (#1068): it tells two runs of one agent apart before their titles
|
||||
const folder = g.key ? g.rows.find((r) => r.folder)?.folder || "" : "";
|
||||
setText(x.name, g.key ? [agentName(g.r.agent), folder, name || (folder ? "" : groupSession(g.r))].filter(Boolean).join(" · ") : t("No session ID"));
|
||||
const purpose = memory ? t("Codex is organizing memories from earlier chats in the background. This can continue after a chat finishes.") + "\n"
|
||||
: suggestions ? kindWhy(g.r) + "\n"
|
||||
: g.rows.some((r) => r.parentMatched) ? t("Title requests were automatically matched using the prompt and the applied chat title.") + "\n" : "";
|
||||
x.name.title = g.key ? (name ? name + "\n" : "") + purpose + t("Session id") + ": " + groupSession(g.r) : t("These requests did not provide a session ID; they are not treated as one conversation.");
|
||||
x.name.title = g.key ? (name ? name + "\n" : "") + purpose + (folder ? t("Folder") + ": " + folder + "\n" : "") + t("Session id") + ": " + groupSession(g.r) : t("These requests did not provide a session ID; they are not treated as one conversation.");
|
||||
const bits = [t(g.rows.length === 1 ? "{n} request" : "{n} requests", { n: g.rows.length })];
|
||||
if (visibleMetrics.includes("tokens") && total.tokens) bits.push(t("{n} tokens", { n: tokens(total.tokens) }));
|
||||
if (total.running) bits.push(t("{n} in progress", { n: total.running }));
|
||||
@@ -5070,7 +5085,7 @@
|
||||
n.node.style.setProperty("--agent", hueOf(id));
|
||||
n.wire.style.setProperty("--agent", hueOf(id));
|
||||
n.node.replaceChildren(icon(ag?.icon || "generic"), el("span", "ps-name", agentName(id)));
|
||||
n.node.title = agentName(id);
|
||||
n.node.title = [agentName(id), ...foldersOf(recent.filter((r) => r.agent === id).slice(0, 20).reverse()).map((f) => t("Folder") + ": " + f)].join("\n");
|
||||
return n.node;
|
||||
}));
|
||||
pTo.replaceChildren(...pDst.map((k) => {
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// Each route keeps the folder its agent works in, its last two levels only
|
||||
// (#1068, emo172: two Claude Code runs in two projects read as one). The
|
||||
// Routing page's By session heads a session with it ("Claude Code ·
|
||||
// workspace/magpie · title"), the session id under the pointer; a request's
|
||||
// row says it under the pointer; the stage's agent, working in two folders
|
||||
// at once, names both by their last level; the tray panel's agent says them
|
||||
// under the pointer. A session that says no folder reads as before. In every
|
||||
// language, at 1100 and 420. No backend: the API is faked here.
|
||||
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");
|
||||
|
||||
function fixture() {
|
||||
const now = Date.now(), at = (s) => new Date(now - s * 1000).toISOString();
|
||||
const seat = { id: "relay", provider: "relay", name: "Relay", who: "team", kind: "key", model: "m1" };
|
||||
const req = (id, session, folder, ago, extra = {}) => ({ id, seq: id, time: at(ago), agent: "claude", session, ...(folder ? { folder } : {}),
|
||||
model: "relay/m1", provider: "relay", order: [seat], tries: [{ id: seat.id, model: "m1", start: at(ago), done: true, status: 200, ms: 500 }],
|
||||
done: true, status: 200, ms: 500, tokens: 1000, ...extra });
|
||||
return [
|
||||
req(1, "s-magpie", "workspace/magpie", 5),
|
||||
req(2, "s-magpie", "workspace/magpie", 4, { sessionTitle: "Fix the gateway" }),
|
||||
req(3, "s-dial", "src/dial", 3),
|
||||
req(4, "s-none", "", 2),
|
||||
req(5, "", "", 1),
|
||||
];
|
||||
}
|
||||
|
||||
function serve(lang, routes) {
|
||||
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({ agents: [{ id: "claude", name: "Claude Code", fields: [] }], profiles: [], settings: { lang, theme: "light" } });
|
||||
if (url.pathname === "/api/gateway/trace") {
|
||||
if (url.searchParams.has("wait")) return new Promise(() => {});
|
||||
return json({ mine: true, now: new Date().toISOString(), seq: 5, totals: { requests: 5, rerouted: 0, errors: 0 }, routes });
|
||||
}
|
||||
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
|
||||
if (url.pathname === "/api/gateway/session-titles") return json({ titles: {} });
|
||||
if (url.pathname === "/api/groups") return json({ groups: [] });
|
||||
if (url.pathname === "/api/providers") return json({ providers: [], gateway: { running: true, window: true } });
|
||||
if (url.pathname === "/api/usage/quotas") return json([]);
|
||||
if (url.pathname === "/api/window/fit") return route.fulfill({ status: 204 });
|
||||
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)];
|
||||
return route.fulfill({ body: await fs.readFile(file), contentType });
|
||||
};
|
||||
}
|
||||
|
||||
const words = {
|
||||
en: { folder: "Folder", session: "Session id" },
|
||||
zh: { folder: "文件夹", session: "会话 ID" },
|
||||
"zh-TW": { folder: "資料夾", session: "會話 ID" },
|
||||
ja: { folder: "フォルダ", session: "セッション ID" },
|
||||
de: { folder: "Ordner", session: "Sitzungs-ID" },
|
||||
};
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of Object.keys(words)) {
|
||||
for (const width of [1100, 420]) {
|
||||
test(`${engine} ${lang} ${width}: routing names each session's folder, never more of its path`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
const w = words[lang], errors = [];
|
||||
const page = await browser.newPage({ viewport: { width, height: 900 }, reducedMotion: "reduce" });
|
||||
page.setDefaultTimeout(5000);
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", serve(lang, fixture()));
|
||||
try { await page.addInitScript(() => localStorage.setItem("magpie.routingBySession", "1")); } catch {}
|
||||
await page.goto("http://magpie.test/?view=routing");
|
||||
await page.locator(".rt-session").nth(3).waitFor();
|
||||
|
||||
// By session: the folder after the agent, before the title
|
||||
const names = await page.locator(".rt-session .nm").evaluateAll((es) => es.map((e) => ({ text: e.textContent, title: e.title })));
|
||||
const of = (re) => names.find((n) => re.test(n.title)) || assert.fail(`no group for ${re}: ${JSON.stringify(names)}`);
|
||||
assert.equal(of(/s-magpie$/).text, "Claude Code · workspace/magpie · Fix the gateway");
|
||||
assert.equal(of(/s-dial$/).text, "Claude Code · src/dial", "a folder stands in for the session id");
|
||||
assert.equal(of(/s-none$/).text, "Claude Code · s-none", "no folder: as before");
|
||||
assert.match(of(/s-magpie$/).title, new RegExp(`${w.folder}: workspace/magpie\\n${w.session}: s-magpie$`));
|
||||
assert.doesNotMatch(of(/s-none$/).title, new RegExp(w.folder));
|
||||
|
||||
// a request's row says its folder under the pointer
|
||||
const rowTitles = await page.locator(".rt-req").evaluateAll((es) => es.map((e) => e.title));
|
||||
assert(rowTitles.some((x) => x.endsWith(`\n${w.folder}: src/dial`)), JSON.stringify(rowTitles));
|
||||
assert.equal(rowTitles.filter((x) => x.includes(w.folder)).length, 3, "only the rows that have a folder");
|
||||
|
||||
// the stage: one agent in two folders at once names both
|
||||
const node = page.locator(".rt-src").first();
|
||||
await page.waitForFunction(() => document.querySelector(".rt-src small")?.textContent.includes(","));
|
||||
assert.equal(await node.locator("small").textContent(), "magpie, dial");
|
||||
assert.match(await node.getAttribute("title"), new RegExp(`${w.folder}: workspace/magpie\\n${w.folder}: src/dial$`));
|
||||
|
||||
const fit = await page.evaluate(() => ({ client: document.documentElement.clientWidth, scroll: document.documentElement.scrollWidth }));
|
||||
assert(fit.scroll <= fit.client + 1, `the page overflows at ${width}: ${JSON.stringify(fit)}`);
|
||||
const reqs = await page.locator(".rt-reqs").evaluate((e) => ({ client: e.clientWidth, scroll: e.scrollWidth }));
|
||||
assert(reqs.scroll <= reqs.client + 1, `request list overflows at ${width}: ${JSON.stringify(reqs)}`);
|
||||
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}-${width}-session-folder.png`), fullPage: true });
|
||||
}
|
||||
|
||||
// the tray panel's agent: its folders under the pointer
|
||||
const panel = await browser.newPage({ viewport: { width: Math.min(width, 440), height: 600 }, reducedMotion: "reduce" });
|
||||
panel.setDefaultTimeout(5000);
|
||||
panel.on("pageerror", (e) => errors.push(e.message));
|
||||
await panel.route("**/*", serve(lang, fixture()));
|
||||
await panel.goto("http://magpie.test/?mode=panel");
|
||||
await panel.locator('[data-ptab="routing"]').click();
|
||||
await panel.locator(".ps-ag").first().waitFor();
|
||||
assert.match(await panel.locator(".ps-ag").first().getAttribute("title"), new RegExp(`^Claude Code\\n${w.folder}: workspace/magpie\\n${w.folder}: src/dial$`));
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user