diff --git a/docs/subsystems/gateway-sessions.md b/docs/subsystems/gateway-sessions.md index afebfa0e5..be5de042c 100644 --- a/docs/subsystems/gateway-sessions.md +++ b/docs/subsystems/gateway-sessions.md @@ -170,6 +170,25 @@ capabilities to a gateway row. Verification: `TestDesktopSessionTitles`, `TestDesktopSessionTitleInStats`, `TestDesktopTitlesReadOncePerList`, `TestDesktopSessionTitlesOnPages`. +Routing's stage names the session an account is serving (connor_yang on +Discord): a row answering, or that answered, the request shown adds that +request's session title after its status, on one line cut short with the +whole line under the pointer. The title is what the list's By session heads +use, from the same `/api/gateway/session-titles`: `sessions.Titles` by +agent:id for every agent but Codex, Codex's name index by thread id (its +parent's, for a subagent Codex names one for). The page keeps both by session +id (`otherTitles`, `codexNames` in +[`client.js`](../../internal/gui/assets/plugins/routing/client.js)), since each +trace update brings its routes anew; a session not seen yet is asked about +once (`askUnnamed`, skipped when a read since has taken it), and the rest +with the list's 15-second refresh, never on the stage's per-second passes. A +names reply silent on a Codex session (unknown to the index, or the index +unread) leaves the title the trace brought, and only a reply that names it +changes it. A session with no title says nothing more, and +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 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 be378dfbe..89bd90fc0 100644 --- a/internal/gui/assets/plugins/routing/client.js +++ b/internal/gui/assets/plugins/routing/client.js @@ -1415,6 +1415,26 @@ function routingPage(part) { let cur = null; // the route the header and the log tell of: the newest played let pinned = null; // a past route picked from the strip let rows = new Map(); // id → { li, wire, st, bi, tg, w, rid, up } + // a request's session, and what its agent's own files name it: the + // list's session heads and the stage's rows read them, the stage from + // its first pass, so they are made here + const groupSession = (r) => r.parentSession || r.session || ""; + const sessionKey = (r) => groupSession(r) ? JSON.stringify([r.agent || "other", groupSession(r)]) : ""; + // Other agents' sessions are named from their own files, by the id the + // agent gave (magpie's X-Magpie-Session can stand in front of it), so a + // Claude Code session heads its group with its title, not its UUID + // (#1293). Kept here by agent:id, as each trace update brings its rows + // anew; a key not asked about yet is asked about at once. Codex's are + // kept by its thread id, from its own name index, for the same reason. + const ownSession = (r) => r.native_session || r.session || ""; + const ownKey = (r) => r.agent && r.agent !== "codex" && ownSession(r) ? r.agent + ":" + ownSession(r) : ""; + const otherTitles = new Map(), askedTitles = new Set(), codexNames = new Map(), codexAsked = new Set(); + let namesBusy = false, askSoon = 0; + const namesDue = new Set(); // asked about, not yet read by a pass + // the title of the session a request is of, as its agent named it, or + // nothing: never one matched to it by its prompt (parentMatched), which + // the list's head says is a guess (connor_yang on Discord) + const titleOf = (r) => !r || r.parentMatched ? "" : r.agent === "codex" ? codexNames.get(groupSession(r)) || "" : otherTitles.get(ownKey(r)) || ""; const subs = new Map(); // a group in the group's way down → its heading { li, wire, key, up } // A provider's keys serving one model, FOLD_AT or more of them side by // side, fold into one row that tells of them all (#1319: 53 keys for one @@ -2517,8 +2537,9 @@ function routingPage(part) { if (!cur) return; hubText(); const n = now(), rs = staged(); - const trying = new Set(), busy = new Set(); - for (const r of rs) for (const tr of r.tries) if (!tr.done) { trying.add(tryseat(r, tr)); busy.add(r.agent); } + const trying = new Map(), busy = new Set(); // a seat → the request it answers now + for (const r of rs) for (const tr of r.tries) if (!tr.done) { trying.set(tryseat(r, tr), r); busy.add(r.agent); } + askUnnamed(rs); const onWire = new Set(); for (const f of flying.values()) { onWire.add(f.id); busy.add(f.agent); } // what each request found, read once a pass: hundreds of a route's @@ -2560,14 +2581,17 @@ function routingPage(part) { const r = src().get(row.rid) || pinned || cur, { answered, rests, gave, went } = findings(r); const w = row.w, rest = rests.get(w.id) || rests.get(w.id + "\u0000" + (w.model || "")), resting = rest && at(rest.until) > n; const smart = r.order[0] && id === seat(r.order[0]) && smartFor(r), said = smart ? t("picked for “{intent}”", { intent: smart }) : ""; - let s, b; + // the session it answers or answered, by its title, so which one + // has the account shows (connor_yang on Discord): the request's + // own, not each request's words + let s, b, named = ""; if (w.unlisted) s = unlistedWord(w); else if (resting) s = restSay(rest); else if (w.window) s = t("request longer than its {n} window · passed over", { n: ctxShort(w.window) }); // a row another request weighed, answering that one: the header // tells of this request, so it says the answer is not this one's - else if (trying.has(id)) s = (r.id !== cur.id && agents.size <= 1 ? t("answering another request…") : t("answering…")) + (said && " · " + said); - else if (answered.has(id)) s = (agents.size > 1 ? t("answered {agent}", { agent: agentName(r.agent) }) : t("answered this request")) + (said && " · " + said); + else if (trying.has(id)) { s = (r.id !== cur.id && agents.size <= 1 ? t("answering another request…") : t("answering…")) + (said && " · " + said); named = titleOf(trying.get(id)); } + else if (answered.has(id)) { s = (agents.size > 1 ? t("answered {agent}", { agent: agentName(r.agent) }) : t("answered this request")) + (said && " · " + said); named = titleOf(r); } else if (gave.has(id)) s = t("{status} · {fail} · passed to {agent}", { status: gave.get(id).status, fail: failWord(gave.get(id).fail), agent: agentName(r.agent) }); else if (went.has(id)) s = t("{status} · {fail} · went on to the next", { status: went.get(id).status, fail: failWord(went.get(id).fail) }); else if (w.noURL) s = noURLWord(w); @@ -2592,10 +2616,15 @@ function routingPage(part) { else if (w.aside) s = t("{api} only · after the others", { api: API[w.speaks] || w.speaks || t("any API") }); else if (w.speaks) s = t("{api} only", { api: API[w.speaks] || w.speaks }); else s = w.kind === "key" ? t("API key") : t("one key"); - if (row.st.textContent !== s) row.st.textContent = s; - // the intent is the user's own words, of any length: cut short on - // the row (routing.css), read whole over it - const full = said && s.includes(said) ? s : resting && !w.unlisted ? restTip(rest) : ""; + // the title in a span of its own, one line cut short however the + // status wraps on a narrow stage (routing.css .ses) + const line = s + (named ? " · " : ""); + if (row.st.textContent !== line + named) { + if (named) { const n = el("span", "ses", named); row.st.replaceChildren(line, n); } else row.st.textContent = s; + } + // the intent and a session's title are the user's own words, of any + // length: cut short on the row (routing.css), read whole over it + const full = said && s.includes(said) || named ? line + named : resting && !w.unlisted ? restTip(rest) : ""; if (row.st.title !== full) { if (full) row.st.title = full; else row.st.removeAttribute("title"); } // an empty title would hide the row's own // an account's windows each, with when they reset, in its tooltip // (#1835): the row says the fullest one while idle and what it is @@ -2632,6 +2661,9 @@ function routingPage(part) { if (resting) parts.push(t("{n} resting", { n: resting })); if (held) parts.push(t("{n} held", { n: held })); setText(f.st, parts.join(" · ")); + // a title or an intent the row cut short is read whole over the fold too + const tip = on?.st.title ? f.st.textContent : ""; + if (f.st.title !== tip) { if (tip) f.st.title = tip; else f.st.removeAttribute("title"); } lightRow(f.li, f.wire, !!on, ms.some((m) => has(m, "now"))); if (on) f.wire.style.setProperty("--agent", on.wire.style.getPropertyValue("--agent")); return !!ms.length && resting + held === ms.length; @@ -3310,26 +3342,25 @@ function routingPage(part) { const reqRows = new Map(); // id → { b, sig, r } const sessionRows = new Map(); // agent + session → persistent heading const closedSessions = new Set(); - const groupSession = (r) => r.parentSession || r.session || ""; - const sessionKey = (r) => groupSession(r) ? JSON.stringify([r.agent || "other", groupSession(r)]) : ""; - let namesBusy = false; - // Other agents' sessions are named from their own files, by the id the - // agent gave (magpie's X-Magpie-Session can stand in front of it), so a - // Claude Code session heads its group with its title, not its UUID - // (#1293). Kept here by agent:id, as each trace update brings its rows - // anew; a key not asked about yet is asked about at once. - const ownSession = (r) => r.native_session || r.session || ""; - const ownKey = (r) => r.agent && r.agent !== "codex" && ownSession(r) ? r.agent + ":" + ownSession(r) : ""; - const otherTitles = new Map(), askedTitles = new Set(); - let askSoon = 0; + // asked about once each: one the list doesn't hold isn't fetched, and + // asking again for it on every pass would be a fetch a second function askUnnamed(rs) { - if (askSoon || !rs.some((r) => ownKey(r) && !askedTitles.has(ownKey(r)))) return; - askSoon = setTimeout(() => { askSoon = 0; refreshSessionNames(); }, 300); + if (askSoon) return; + let ask = false; + for (const r of rs) { + const k = ownKey(r), id = !k && r.agent === "codex" && !r.parentMatched ? groupSession(r) : ""; + if (k && !askedTitles.has(k)) { askedTitles.add(k); namesDue.add(k); ask = true; } + if (id && !codexAsked.has(id)) { codexAsked.add(id); namesDue.add("codex\u0000" + id); ask = true; } + } + // one asked while names are being read waits for that read to end, + // and none is made when a read since (the page's first) took them all + const go = () => { askSoon = namesBusy ? setTimeout(go, 300) : 0; if (!askSoon && namesDue.size) { namesDue.clear(); refreshSessionNames(); } }; + if (ask) askSoon = setTimeout(go, 300); } async function refreshOtherNames() { const keys = [...new Set(listed().map(ownKey).filter(Boolean))].slice(0, 2000); if (!keys.length) return false; - for (const k of keys) askedTitles.add(k); + for (const k of keys) { askedTitles.add(k); namesDue.delete(k); } const res = await fetch("/api/gateway/session-titles", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ids: [], routeIds: [], sessions: keys }) }); if (!res.ok) return false; const titles = (await res.json()).titles || {}; @@ -3345,7 +3376,7 @@ function routingPage(part) { namesBusy = true; let others = false; try { others = await refreshOtherNames(); } catch {} finally { namesBusy = false; } - if (others) steady(renderHist); + if (others) { steady(renderHist); render(); } if (namesBusy || !shown()) return; const rs = listed().filter((r) => r.agent === "codex"), sourceDay = day, routeIDs = new Set(rs.map((r) => r.id)); if (!rs.some(groupSession)) return; @@ -3356,6 +3387,7 @@ function routingPage(part) { // the API's 2,000-row limit. Only Codex rows need names or associations. for (let i = 0; i < rs.length; i += 2000) { const batch = rs.slice(i, i + 2000), ids = [...new Set(batch.map(groupSession).filter(Boolean))]; + for (const id of ids) namesDue.delete("codex\u0000" + id); const res = await fetch("/api/gateway/session-titles", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ids, groups: true, routeIds: batch.map((r) => r.id), day: sourceDay }) }); if (!res.ok) return; const part = await res.json(); @@ -3379,11 +3411,15 @@ function routingPage(part) { r.parentSession = parent; r.parentMatched = matched; changed = true; } } + // a reply silent on a session says nothing of it: the title the + // trace brought stays (an ask for a new row lands between updates) const id = groupSession(r); + if (!id || !Object.hasOwn(names, id)) continue; const name = typeof names[id] === "string" ? names[id] : ""; if ((r.sessionTitle || "") !== name) { r.sessionTitle = name; changed = true; } + if (!r.parentMatched && (codexNames.get(id) || "") !== name) { if (name) codexNames.set(id, name); else codexNames.delete(id); changed = true; } } - if (changed) steady(renderHist); + if (changed) { steady(renderHist); render(); } } catch {} finally { namesBusy = false; } } setInterval(refreshSessionNames, 15000); diff --git a/internal/gui/assets/plugins/routing/routing.css b/internal/gui/assets/plugins/routing/routing.css index 993e02a85..8af00e13f 100644 --- a/internal/gui/assets/plugins/routing/routing.css +++ b/internal/gui/assets/plugins/routing/routing.css @@ -104,6 +104,9 @@ routing picked it for) is cut short, its name kept, never run off the row's edge (penershu on X) */ .rt-accts li > em { min-width: 0; overflow: hidden; text-overflow: ellipsis; } +/* the session an account answers (connor_yang on Discord): one line cut + short, also where a narrow stage lets the status wrap */ +.rt-accts em .ses { display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; vertical-align: bottom; } .rt-accts .bar { grid-column: 2 / 4; height: 3px; border-radius: 2px; background: var(--card-2); overflow: hidden; } .rt-accts .bar i { display: block; height: 100%; width: 0; border-radius: 2px; background: var(--muted); transition: width .4s; } .rt-accts li.nobar .bar { display: none; } diff --git a/internal/gui/tests/routing-session-title.test.cjs b/internal/gui/tests/routing-session-title.test.cjs new file mode 100644 index 000000000..e3fc118ff --- /dev/null +++ b/internal/gui/tests/routing-session-title.test.cjs @@ -0,0 +1,151 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// The Routing page's stage says which session has an account (connor_yang on +// Discord: "回答了这个请求" beside the account, with the current session's +// title, shows which session is using it). A row answering or that answered +// the request shown says the title of that request's session after its +// status, on one line cut short, the whole of it under the pointer. The +// title is the one the agent's own files give (Claude Code's by agent:id, +// Codex's from its name index by thread id), read from +// /api/gateway/session-titles once a session is new and with the list's +// 15s refresh, not on each of the stage's passes; a Codex title kept through +// the trace's next update of the same request. A session with no title, and +// a Codex request whose session was only matched to it by its prompt +// (parentMatched), says nothing more. English, Chinese (simplified and +// traditional), Japanese and German, at 1100px and 420px; 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"); +const M = "gpt-5.5"; +const seat = { id: "acct#a1", provider: "acct", name: "ChatGPT", who: "me@example.com", kind: "account", model: M }; +const TITLE = "Fix the login redirect that loops back to the sign-in page after the token refresh fails on Safari"; + +function serve(lang, agent, live) { + return async (request) => { + const url = new URL(request.request().url()); + const json = (data) => request.fulfill({ json: data }); + if (url.pathname === "/boot.js") return request.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return request.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [{ id: agent, name: agent === "codex" ? "Codex" : "Claude Code", fields: [] }], profiles: [], settings: { lang, theme: "light" } }); + if (url.pathname === "/api/gateway/trace") { + if (url.searchParams.get("wait")) { + if (live.queued.length) return json(live.queued.shift()); + live.pending.push(request); + return; + } + return json({ mine: true, now: new Date().toISOString(), seq: 1, totals: { requests: 1, rerouted: 0, errors: 0 }, routes: [live.first] }); + } + if (url.pathname === "/api/gateway/session-titles") { + const input = request.request().postDataJSON(); + live.asked.push(input); + return json(live.titles(input)); + } + if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] }); + if (url.pathname === "/api/groups") return json({ groups: [], pools: [] }); + if (url.pathname === "/api/providers") return json({ providers: [], excluded: [], 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)]; + await request.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +// what the gateway answers for each agent: Claude Code's sessions by +// agent:id (sessions.Titles), Codex's by thread id (CodexTitles), with the +// parent a title request was matched to by its prompt +const titlesFor = (agent) => (input) => { + if (agent === "claude") return { titles: input.sessions.includes("claude:s-1") ? { "claude:s-1": TITLE } : {} }; + const names = {}, parents = {}, matched = {}; + for (const id of input.ids) if (id === "s-1") names[id] = TITLE; + // request 3 is a title request matched to s-1's chat by its prompt only + if (input.routeIds?.includes(3)) { parents[3] = "s-1"; matched[3] = true; names["s-1"] = TITLE; } + return { names, parents, matched }; +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const agent of ["claude", "codex"]) { + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + for (const width of [1100, 420]) { + test(`${engine} ${agent} ${lang} ${width}px: the account's row names the session it answers, only one its agent named`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await browser.newPage({ viewport: { width, height: 900 }, reducedMotion: "reduce" }); + page.setDefaultTimeout(8000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (error) => errors.push(error.message)); + const at = (s) => new Date(Date.now() - s * 1e3).toISOString(); + const route = (id, session, done, extra = {}) => ({ id, seq: id, time: at(2), agent, session, model: M, provider: "acct", done, status: done ? 200 : 0, ms: done ? 900 : 0, + tokens: 1200, order: [seat], tries: [{ id: seat.id, model: M, start: at(2), done, ...(done ? { status: 200, ms: 900 } : {}) }], ...extra }); + const live = { pending: [], queued: [], seq: 1, asked: [], first: route(1, "s-1", false), titles: titlesFor(agent) }; + await page.route("**/*", serve(lang, agent, live)); + const send = (...routes) => { + const d = { mine: true, now: new Date().toISOString(), seq: ++live.seq, totals: { requests: live.seq }, routes }; + const r = live.pending.shift(); + if (r) r.fulfill({ json: d }); else live.queued.push(d); + }; + const say = (key) => page.evaluate(([lang, key]) => (lang !== "en" && I18N[lang]?.[key]) || key, [lang, key]); + await page.goto("http://magpie.test/?view=routing"); + const em = page.locator(".rt-accts li:not(.rt-fold) > em"); + + // in flight: answering…, then its session's title once asked for + const answering = await say("answering…"); + await page.waitForFunction((want) => document.querySelector(".rt-accts li:not(.rt-fold) > em")?.textContent === want, `${answering} · ${TITLE}`); + assert.equal(await em.getAttribute("title"), `${answering} · ${TITLE}`, "the whole title under the pointer"); + + // done: the trace's next update brings the request anew, and its title stays + const answered = await say("answered this request"); + send(route(1, "s-1", true)); + await page.waitForFunction((want) => document.querySelector(".rt-accts li:not(.rt-fold) > em")?.textContent === want, `${answered} · ${TITLE}`); + assert.equal(await em.getAttribute("title"), `${answered} · ${TITLE}`); + // one line, cut short at its column, the row and the page in their width + // (the title's own span: a narrow stage lets the status wrap under the name) + const box = await em.evaluate((em) => { const e = em.querySelector(".ses"); return { text: e?.textContent, ws: getComputedStyle(e).whiteSpace, over: getComputedStyle(e).textOverflow, h: e.getBoundingClientRect().height, + lh: parseFloat(getComputedStyle(e).lineHeight) || 16, sw: e.scrollWidth, cw: e.clientWidth, li: em.parentElement.scrollWidth <= em.parentElement.clientWidth + 1 }; }); + assert.equal(box.text, TITLE); + assert.equal(box.ws, "nowrap"); + assert.equal(box.over, "ellipsis"); + assert(box.h < box.lh * 1.6, `one line: ${JSON.stringify(box)}`); + assert(box.sw > box.cw, `a long title is cut short: ${JSON.stringify(box)}`); + assert(box.li, "the row holds its status"); + 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)}`); + 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}-${agent}-${lang}-${width}-session-title.png`) }); + } + + // the stage's passes ask for nothing more: names are read when a + // session is new and with the list's refresh, not each second + const asked = live.asked.length; + await page.evaluate(() => new Promise((r) => setTimeout(r, 3000))); + assert(live.asked.length <= asked + 1, `asked ${live.asked.length - asked} more times in 3s`); + + // a session its agent gave no title: the status alone + const before = live.asked.length; + send(route(2, "s-2", true)); + await page.waitForFunction((want) => document.querySelector(".rt-accts li:not(.rt-fold) > em")?.textContent === want, answered); + await new Promise((r) => { const tick = () => live.asked.length > before ? r() : setTimeout(tick, 50); tick(); }); + await page.evaluate(() => new Promise((r) => setTimeout(r, 1500))); + assert.equal(await em.textContent(), answered, "no title for a session with none"); + assert.equal(await em.getAttribute("title"), null); + + if (agent === "codex") { + // a title request matched to a chat by its prompt alone: a guess, so no title + const n = live.asked.length; + send(route(3, "t-3", true, { kind: "title" })); + await new Promise((r) => { const tick = () => live.asked.slice(n).some((x) => x.routeIds?.includes(3)) ? r() : setTimeout(tick, 50); tick(); }); + await page.evaluate(() => new Promise((r) => setTimeout(r, 1500))); + const text = await em.textContent(); + assert(!text.includes(TITLE), `a matched session's title is not shown: ${text}`); + } + assert.deepEqual(errors, []); + }); + } + } + } +}