diff --git a/docs/subsystems/gateway-sessions.md b/docs/subsystems/gateway-sessions.md index 847a7b616..771a98a10 100644 --- a/docs/subsystems/gateway-sessions.md +++ b/docs/subsystems/gateway-sessions.md @@ -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//`) into magpie's session trash under `trash/sessions/gateway/`, with a note diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js index dad47fa6e..b488a4f81 100644 --- a/internal/gui/assets/plugins/routing/client.js +++ b/internal/gui/assets/plugins/routing/client.js @@ -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" : ""; diff --git a/internal/gui/assets/plugins/routing/routing.css b/internal/gui/assets/plugins/routing/routing.css index 2acb63145..114ab510a 100644 --- a/internal/gui/assets/plugins/routing/routing.css +++ b/internal/gui/assets/plugins/routing/routing.css @@ -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; } diff --git a/internal/gui/session_names_test.go b/internal/gui/session_names_test.go index 7046aaf8b..c9b683c2d 100644 --- a/internal/gui/session_names_test.go +++ b/internal/gui/session_names_test.go @@ -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) + } +} diff --git a/internal/gui/tests/routing-session-folder.test.cjs b/internal/gui/tests/routing-session-folder.test.cjs index 708836473..aa68d6a5f 100644 --- a/internal/gui/tests/routing-session-folder.test.cjs +++ b/internal/gui/tests/routing-session-folder.test.cjs @@ -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)); diff --git a/internal/gui/trace.go b/internal/gui/trace.go index 4d4811bbe..fefa0a166 100644 --- a/internal/gui/trace.go +++ b/internal/gui/trace.go @@ -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) {