routing: By session heads a session by its title, its folder quieter beside it (flandern1211_58540 on Discord)

Routing's By session headed each session "Claude Code · folder · title",
and with no title only the folder and id ("路由这里的会话名只能看到目录名和
会话ID吗"). Now the head is the agent and the session's title on one
line (whitespace folded), with its folder after it in a quieter .dir; with
no title the folder stands in, and with neither the id. The tooltip keeps
the title, the folder and the id.

The title comes from what magpie already reads, no second reader:
sessions.Titles (the agent's own title, else its first prompt) and Codex's
name index, and where both find nothing, the first prompt the gateway
recorded for that session (sessions.GatewayTitler, the title the Sessions
page shows for it), looked up under the agent the page names and the one
the gateway records it under (usage.AgentOf). A Codex thread Codex never
named now goes to sessions.Titles as a codex: key, so its rollout's first
prompt names it. withGatewayTitles and codexReadableTitles in trace.go.
Nothing is read that the Sessions page doesn't show already, and nothing
leaves the local GUI.

Tests: TestSessionTitlesFallBackToFirstPrompt (new): an unnamed Codex
thread gets its first prompt, a named one keeps its name, an unknown id
stays out, a pi session known only to the gateway gets its first words.
routing-session-folder.test.cjs follows the new head: title then .dir,
the first prompt on one line, the folder said once, the id with neither,
nothing clipped (chromium and webkit, en zh zh-TW ja de, 1100 and 420px).

Run on mote via mote-run, at origin/main e7b0c398e plus this change:
- Whole Routing GUI set (routing-*, panel-routing*) + i18n-keys,
  chromium and webkit: 2583 pass, 35 fail. Every red is a known one:
  rule-remove (#3096), rule-drag (#3789), row-swap (#3799),
  order-unknown (#4627), rules-line (#3593), many-keys, steady,
  steps-cap and story-shrinks (#5088), and under the load of another
  session's whole GUI suite (load ~200) routing-credits webkit ja 420
  (#5161) and routing-flood webkit en (#2215). Run again: credits 20/20
  and flood 12/12 here; order-unknown's webkit de 420 red the same at
  e7b0c398e alone.
- routing-session-folder: 20/20 (both engines, 5 languages, 2 widths).
- go test ./internal/gui: TestSessionTitlesFallBackToFirstPrompt ok;
  red only TestCoreScriptBudget (1534001 > 1533802, the same at
  e7b0c398e, #5139: this change adds nothing to the core scripts) and
  TestMainWindowCorners (the same at e7b0c398e, #3949).
- Rebased onto origin/main 1a67ca614 (its routing client.js changes
  merged clean), at this commit: routing-session-folder 20/20,
  routing-session-title 40/40, routing-kept-again 20/20,
  usage-compact-counts 30/30, routing-live-calm 2/2, i18n-keys 4/4, and
  go test ./internal/gui -run 'TestSession|TestCoreScriptBudget' ok
  (the budget passes at this base). The whole Routing set was not run
  again here. Then onto 0f1b40bbc (routing client.js and css again,
  merged clean): routing-session-folder 20/20, routing-live-bytes
  20/20, routing-live-calm 2/2, i18n-keys 4/4.

Broken by hand:
- withGatewayTitles a no-op: TestSessionTitlesFallBackToFirstPrompt red
  ("titles = map[]").
- client.js back to the old head: routing-session-folder red in every
  engine, language and width.

Not tried: the real app with real Codex, Claude Code and gateway-only
sessions (fixtures only), the Linux WebKitGTK app, Windows.
This commit is contained in:
yetone
2026-11-04 19:43:00 +08:00
parent 0f1b40bbc4
commit 43849d51c3
6 changed files with 176 additions and 15 deletions
+16
View File
@@ -227,6 +227,22 @@ neither does a Codex request whose parent was only matched by its prompt
(`parentMatched`), since that match is a guess. Verification:
`routing-session-title.test.cjs`.
A By session head reads as its title (flandern1211_58540 on Discord: a
folder and an id told nothing): the agent, then the session's title on one
line (whitespace folded), then its folder in a quieter `.dir`; with no title
the folder takes its place, and with neither the id. The tooltip keeps the
title, the folder and the id. Where `sessions.Titles` and Codex's name index
find nothing, the same endpoint falls back to the first prompt the gateway
recorded for that session (`sessions.GatewayTitler`, the title its list
shows), looked up under the agent the page names and the one the gateway
records it under (`usage.AgentOf`): `withGatewayTitles` and
`codexReadableTitles` in [`trace.go`](../../internal/gui/trace.go). Codex
ids the index doesn't name go to `sessions.Titles` as `codex:` keys first,
so a rollout's own first prompt names it. Nothing is read that the page
couldn't already show on the Sessions page, and nothing leaves the local
GUI. Verification: `TestSessionTitlesFallBackToFirstPrompt`,
`routing-session-folder.test.cjs`.
A gateway projection can be deleted (lc on Discord). `sessions.DeleteGateway`
moves its recorded text folders (`gateway-conversations/<date>/<identity hash>`)
into magpie's session trash under `trash/sessions/gateway/`, with a note
+11 -5
View File
@@ -3754,9 +3754,9 @@ function routingPage(part) {
for (const g of groups.values()) {
let x = sessionRows.get(g.key);
if (!x) {
const b = el(g.key ? "button" : "div", "rt-session"), name = el("span", "nm"), meta = el("span", "summary"), cost = el("span", "cost"), arrow = el("span", "arrow");
b.append(arrow, name, meta, cost);
x = { b, name, meta, cost, arrow };
const b = el(g.key ? "button" : "div", "rt-session"), name = el("span", "nm"), dir = el("span", "dir"), meta = el("span", "summary"), cost = el("span", "cost"), arrow = el("span", "arrow");
b.append(arrow, name, dir, meta, cost);
x = { b, name, dir, meta, cost, arrow };
if (g.key) b.onclick = () => {
if (closedSessions.has(g.key)) closedSessions.delete(g.key); else closedSessions.add(g.key);
steady(renderHist);
@@ -3783,11 +3783,17 @@ function routingPage(part) {
// for one purpose without renaming a chat that also made helper calls.
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") : "");
// its title: the agent's own, else its first prompt, on one line
// (flandern1211_58540 on Discord: a folder and an id told nothing)
const name = (g.rows.find((r) => r.sessionTitle)?.sessionTitle || otherTitles.get(ownKey(g.r)) || (memory ? t("Background memory task") : suggestions ? t("Background prompt suggestions") : "")).replace(/\s+/g, " ").trim();
// 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"));
// the title first; the folder after it, quieter, or in its place
// when there is no title; the id only when there is neither
setText(x.name, g.key ? [agentName(g.r.agent), name || folder || groupSession(g.r)].filter(Boolean).join(" · ") : t("No session ID"));
setText(x.dir, name && folder ? folder : "");
if (x.dir.hidden !== !(name && folder)) x.dir.hidden = !(name && folder);
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" : "";
@@ -381,6 +381,8 @@
button.rt-session { cursor: pointer; }
.rt-session .arrow { flex: none; width: 10px; color: var(--muted); }
.rt-session .nm { flex: 1 1 160px; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 500; }
.rt-session .dir { flex: 0 1 auto; min-width: 0; max-width: 40%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--muted); }
.rt-session .dir[hidden] { display: none; }
.rt-session .summary { display: flex; align-items: baseline; flex-wrap: wrap; gap: 4px 10px; color: var(--muted); font-variant-numeric: tabular-nums; }
.rt-session > .cost { flex: none; margin-left: auto; font-variant-numeric: tabular-nums; }
.rt-session > .cost[hidden] { display: none; }
+68
View File
@@ -8,6 +8,7 @@ import (
"path/filepath"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/sessions"
)
@@ -54,3 +55,70 @@ func TestSessionTitlesNameOtherAgents(t *testing.T) {
t.Fatalf("titles = %v, want %v (body %s)", out.Titles, want, w.Body)
}
}
// flandern1211_58540 on Discord: Routing headed a session by its folder
// and id ("路由这里的会话名只能看到目录名和会话ID吗"). A Codex thread Codex
// never named is headed by its first prompt, as the Sessions page heads
// it, and a session whose files aren't on this computer by the first words
// the gateway recorded of it. A named thread keeps its name, and a session
// with neither keeps no title.
func TestSessionTitlesFallBackToFirstPrompt(t *testing.T) {
sandboxHome(t)
t.Setenv("CLAUDE_CONFIG_DIR", t.TempDir())
codex := t.TempDir()
t.Setenv("CODEX_HOME", codex)
t.Cleanup(sessions.Reset)
sessions.Reset()
const unnamed, named = "019b0001-aaaa-7bbb-8ccc-000000000001", "019b0001-aaaa-7bbb-8ccc-000000000002"
day := filepath.Join(codex, "sessions", "2026", "11", "04")
if err := os.MkdirAll(day, 0o700); err != nil {
t.Fatal(err)
}
for _, id := range []string{unnamed, named} {
lines := []string{
`{"timestamp":"2026-11-04T10:00:00.000Z","type":"session_meta","payload":{"id":"` + id + `","timestamp":"2026-11-04T10:00:00.000Z","cwd":"/work/app","originator":"codex_cli_rs","cli_version":"0.99.0","source":"cli","model_provider":"openai"}}`,
`{"timestamp":"2026-11-04T10:00:01.000Z","type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"把路由页的会话名\n显示出来"}]}}`,
`{"timestamp":"2026-11-04T10:00:01.100Z","type":"event_msg","payload":{"type":"user_message","message":"把路由页的会话名\n显示出来","images":[]}}`,
}
if err := os.WriteFile(filepath.Join(day, "rollout-2026-11-04T10-00-00-"+id+".jsonl"), []byte(strings.Join(lines, "\n")+"\n"), 0o600); err != nil {
t.Fatal(err)
}
}
if err := os.WriteFile(filepath.Join(codex, "session_index.jsonl"), []byte(`{"id":"`+named+`","thread_name":"路由会话名","updated_at":"2026-11-04T10:01:00Z"}`+"\n"), 0o600); err != nil {
t.Fatal(err)
}
if err := sessions.SetGatewayRecording(true, false); err != nil {
t.Fatal(err)
}
if err := sessions.SaveGatewayTurn(sessions.GatewayTurn{Agent: "pi", Session: "ses_remote", Time: time.Now().UTC(),
Input: []sessions.Part{{Role: "user", Kind: "text", Text: "Deploy the staging server"}}}); err != nil {
t.Fatal(err)
}
mux := http.NewServeMux()
traceRoutes(mux)
ask := func(body string, out any) {
t.Helper()
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/gateway/session-titles", strings.NewReader(body)))
if w.Code != 200 {
t.Fatalf("%d %s", w.Code, w.Body)
}
if err := json.Unmarshal(w.Body.Bytes(), out); err != nil {
t.Fatal(err)
}
}
var groups struct {
Names map[string]string `json:"names"`
}
ask(`{"ids":["`+unnamed+`","`+named+`","019b0001-aaaa-7bbb-8ccc-00000000dead"],"groups":true,"routeIds":[]}`, &groups)
if groups.Names[unnamed] == "" || !strings.HasPrefix(groups.Names[unnamed], "把路由页的会话名") || groups.Names[named] != "路由会话名" || len(groups.Names) != 2 {
t.Fatalf("Codex names = %q", groups.Names)
}
var others struct {
Titles map[string]string `json:"titles"`
}
ask(`{"ids":[],"routeIds":[],"sessions":["pi:ses_remote","pi:ses_none","claude:ses_remote"]}`, &others)
if others.Titles["pi:ses_remote"] != "Deploy the staging server" || len(others.Titles) != 1 {
t.Fatalf("titles = %q", others.Titles)
}
}
@@ -1,8 +1,8 @@
// 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
// Routing page's By session heads a session with its title ("Claude Code ·
// title") and the folder dim beside it, 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
@@ -27,6 +27,7 @@ function fixture() {
req(3, "s-dial", "src/dial", 3),
req(4, "s-none", "", 2),
req(5, "", "", 1),
req(6, "s-old", "", 0.5),
];
}
@@ -39,10 +40,11 @@ function serve(lang, routes) {
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 });
return json({ mine: true, now: new Date().toISOString(), seq: 6, totals: { requests: 6, 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: {} });
// a session named by its first prompt, as sessions.Titles gives it
if (url.pathname === "/api/gateway/session-titles") return json({ titles: { "claude:s-old": "Rename foo\n to bar" } });
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([]);
@@ -76,14 +78,28 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
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();
await page.locator(".rt-session").nth(4).waitFor();
await page.waitForFunction(() => [...document.querySelectorAll(".rt-session .nm")].some((e) => e.textContent.includes("Rename")));
// 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 })));
// By session: the agent and the session's title, its folder dim
// beside it (flandern1211_58540 on Discord: "路由这里的会话名只能
// 看到目录名和会话ID吗"); with no title, the folder stands in, and
// with neither, the id
const names = await page.locator(".rt-session").evaluateAll((es) => es.map((e) => {
const nm = e.querySelector(".nm"), dir = e.querySelector(".dir");
return { text: nm.textContent, title: nm.title, dir: dir && !dir.hidden ? dir.textContent : "", dirTitle: dir?.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-magpie$/).text, "Claude Code · Fix the gateway");
assert.equal(of(/s-magpie$/).dir, "workspace/magpie", "the folder beside the title");
assert.equal(of(/s-old$/).text, "Claude Code · Rename foo to bar", "the first prompt, on one line");
assert.equal(of(/s-old$/).dir, "");
assert.equal(of(/s-dial$/).text, "Claude Code · src/dial", "a folder stands in for the session id");
assert.equal(of(/s-dial$/).dir, "", "the folder said once");
assert.equal(of(/s-none$/).text, "Claude Code · s-none", "no folder: as before");
assert.match(of(/s-old$/).title, new RegExp(`^Rename foo to bar\\n${w.session}: s-old$`));
const clipped = await page.locator(".rt-session").evaluateAll((es) => es.some((e) => [...e.children].some((c) => c.getBoundingClientRect().right > e.getBoundingClientRect().right + 1)));
assert.equal(clipped, false, "each heading's parts inside it");
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));
+55 -2
View File
@@ -284,6 +284,59 @@ func quotaView(id string) string {
return view
}
// withGatewayTitles fills in, for each agent:id key the agent's own files
// left without a title, the first words its user said through the gateway,
// as the Sessions page heads a session it knows only from there
// (flandern1211_58540 on Discord: Routing named a session by its folder and
// id). Nothing is read that the Sessions page doesn't show already.
func withGatewayTitles(out map[string]string, keys []string) map[string]string {
var title func(agent, id string) string
for _, k := range keys {
agent, id, ok := strings.Cut(k, ":")
if !ok || id == "" || out[k] != "" {
continue
}
if title == nil {
title = sessions.GatewayTitler()
}
// recorded under the agent its User-Agent named, as a route's
// agent may not have been
name := title(agent, id)
if name == "" {
if a := usage.AgentOf(agent); a != agent {
name = title(a, id)
}
}
if name != "" {
out[k] = name
}
}
return out
}
// codexReadableTitles is each Codex thread's name from Codex's index, else
// the title its own files give (its first prompt, as the Sessions page
// heads it), else the first words recorded through the gateway: a thread
// never named was headed by its folder and id alone.
func codexReadableTitles(ids []string) map[string]string {
out := sessions.CodexTitles(ids)
var keys []string
for _, id := range ids {
if id != "" && out[id] == "" {
keys = append(keys, "codex:"+id)
}
}
if len(keys) == 0 {
return out
}
for k, name := range withGatewayTitles(sessions.Titles(keys), keys) {
if name != "" {
out[strings.TrimPrefix(k, "codex:")] = name
}
}
return out
}
// traceRoutes serves the routing trace for the Gateway view to play: it
// waits up to 25 s for something to change after the seq it is given, so
// the page hears of a request as it happens.
@@ -307,7 +360,7 @@ func traceRoutes(mux *http.ServeMux) {
return
}
if len(in.Sessions) > 0 && len(in.IDs) == 0 {
writeJSON(rw, map[string]any{"titles": sessions.Titles(in.Sessions)})
writeJSON(rw, map[string]any{"titles": withGatewayTitles(sessions.Titles(in.Sessions), in.Sessions)})
return
}
if !in.Groups {
@@ -344,7 +397,7 @@ func traceRoutes(mux *http.ServeMux) {
in.IDs = append(in.IDs, row.ParentSession)
}
}
writeJSON(rw, map[string]any{"names": sessions.CodexTitles(in.IDs), "parents": parents, "matched": matched,
writeJSON(rw, map[string]any{"names": codexReadableTitles(in.IDs), "parents": parents, "matched": matched,
"resetInferred": in.Day != "" && rows == nil})
})
mux.HandleFunc("GET /api/gateway/route", func(rw http.ResponseWriter, r *http.Request) {