gui: the Sessions page nests subagents under their session and opens each one's conversation; Codex threads nest under their parent_session (#2261, infinitr0us)

Only main sessions sit at the top of the Sessions page now.

- A session with subagents shows an "N subagents" fold under its row. It starts folded.
  - Unfolding neither opens the session nor moves the page.
  - The rows are indented by the depth of the subagent that started them.
  - Clicking a row opens its conversation in place, via /api/sessions/transcript?sub=.
- Codex threads with a parent_session nest under that session, to any depth.
  - The parent chain is guarded against loops and capped at a depth of 8.
  - A thread whose parent isn't listed stays at the top.
  - A folder's count and its select-all include the nested threads.
  - Searching opens the folds that hold matches. Opening a nested session from elsewhere opens its ancestors' folds.
- New strings ("{n} subagent", "{n} subagents") in zh, en, zh-TW, ja and de.
- No native select and no left-border accent. The nested list is a bordered card.
- docs/subsystems/gateway-sessions.md describes the subagents field, the sub= route and the page.

What was run, at this head before the rebase (5618ade1e):

- internal/gui/tests/sessions-subagents.test.cjs (new): 40/40 pass in Chromium and WebKit, at widths 1100 and 420, in all 5 languages.
  - It checks the fold, the indentation and order, that the transcript is called with sub= and read once, and Codex nesting with a loop and a missing parent.
  - Its tidy check covers: no select, no left border, nothing wider than the page.
- Related GUI tests (sessions*, sess*, session*, i18n, routing-session, account-mask, click-scroll): 451/451 pass.
- Broken by hand, each restored afterwards:
  - Without nest(), the Codex test fails.
  - Without the fold, both tests fail.
  - Without &sub=, the Claude test fails.
- usage-agents-hide and usage-fold fail the same way on origin/main bc470c6b6, with or without this change. They are filed as #2211 and #2163.
- The full suite, go test -p 4 -timeout 40m ./... under a temp HOME at 5618ade1e with this change: green (exit 0).
- gofmt -l is clean. go vet passes for darwin, linux (-tags nogui) and windows.
- Real use: a sandbox magpie (temp HOME, ports 3486/3487) against read-only copies of real sessions.
  - Claude Code: the 5-subagent fold, and a real nested subagent indented one step whose conversation opened.
  - Codex: a real exec rollout pair, with the child's session_meta source rewritten to thread_spawn of the parent. Only the parent is at the top, and the child's details and conversation open in place.
  - Found on the way, and the same on main: a Codex Image Session Helper rollout is listed but can't be opened ("no such session"). Filed as #2273.

Rebased onto 69d7ee33a, whose new commits touch none of these files. Rerun at the rebased head:

- go test ./internal/sessions ./internal/gui: pass.
- sessions-subagents: 40/40.
- i18n-keys, sessions-* and claude-cloud-drift: 371/371.
- gofmt -l is clean.

Not tried:

- A real Codex rollout written as a subagent: none on this Mac, so the copied rollout above stands in.
- Real OpenCode children and real Kimi sessions.
- The GUI on Linux (WebKitGTK) and Windows.
This commit is contained in:
yetone
2026-10-15 08:31:21 +08:00
parent c516841e46
commit 3a0b61275f
5 changed files with 445 additions and 14 deletions
+44 -2
View File
@@ -366,8 +366,8 @@ files gets `Subagent` from the file's name, `<session>/subagents/agent-<id>.json
or `<session>/subagents/workflows/<run>/agent-<id>.jsonl`
(`sessions.SubagentOf`), so no cache version changes, and `ParentAgent` from
the `parentAgentId` of the `agent-<id>.meta.json` beside it, which Claude Code
writes for a subagent a subagent started (`sessions.SubagentParent`, read once
a file; a meta file not read is unknown and read again). A gateway row matched
writes for a subagent a subagent started (`sessions.SubagentParent`, through
`ccMeta`: read once a file; a meta file not read is unknown and read again). A gateway row matched
to a file row keeps the gateway's own. Both were checked against Claude Code
2.1.296 spawning a subagent from a subagent.
@@ -380,6 +380,48 @@ metadata, gateway-only entries and conflicting identities set `role` to
`unknown` and do not acquire a guessed parent or root. These fields are omitted
for other agents. This is Codex-specific (#1591).
A session whose agent keeps its subagents' conversations beside its own
lists them in `subagents` on the sessions API (`/api/sessions`, `one`, `manage`; #2261,
[`subagents.go`](../../internal/sessions/subagents.go)), only for agents with
a transcript, oldest first. Each has `id`, `title` (the task it was given),
`kind` (the agent it ran as), `parent` (the subagent that started it, empty
for the session) and `start`/`last`; its file is never sent.
- Claude Code, Qoder and Qoder CN: each `subagents/agent-<id>.jsonl` (and
under `workflows/<run>/`), with `agentType`, `description` and
`parentAgentId` from the meta file beside it (`ccMeta`). With no meta file
(Qoder), the title is the file's first user line (`ccTask`, at most 16
lines read). `agent-acompact-<id>.jsonl` is a compaction's own run and is
left out.
- OpenCode: a child session (`parent_id`, from the JSON store or
`opencode.db`) is a subagent of its root, not a session of its own;
`ocRoots` records its parent. Its title splits 1.x's
`<description> (@<agent> subagent)`; 2.x titles it the description alone
(task tool, opencode 2.0.25), and a default `Child session - <time>` is no
title. ZCode shares the parser but has no transcript, so lists none.
- Kimi Code: each `agents/agent-<n>/wire.jsonl`. 1.5's `subagent.spawned`
record, written in the starting agent's wire, gives `subagentName`,
`description` and `parentAgentId` (`kimiWireOf`, read again only when the
file's size or time changes); 1.4 writes none, and the title is the
subagent's first `turn.prompt`.
These are read beside the parsed-session cache, not in it, so its version
is unchanged. `GET /api/sessions/transcript` takes `sub=<id>` for a
subagent's conversation; the id is looked up among the session's own
`subagents` (`sessions.SubagentTranscript`), never used as a path, and one
not listed is an error. See `TestClaudeSubagents`, `TestQoderSubagents`,
`TestOpenCodeSubagents`, `TestKimiSubagents` and
`TestSessionSubagentTranscript`.
The Sessions page draws only main sessions on top. A session's subagents are
folded under its row ("2 subagents"); unfolded, each is a row of its task and
kind, set in under the subagent that started it, and a click shows its
conversation (`sub=`). A Codex thread whose `parent_session` chain reaches a
listed session is drawn, as a session with its own details, Resume and
Delete, under its parent in the same fold; a loop of parents, a chain deeper
than eight or a parent not listed leaves it on top. The folder's count and
checkbox cover the sessions under others. See `sessions-subagents.test.cjs`.
Codex keeps the existing session-title precedence. Only when that leaves the
title empty may a child thread use its parent's `spawn_agent` `task_name`,
matched by the same `call_id` and an `item_completed` event whose item has type
+158 -12
View File
@@ -39,6 +39,18 @@ magpie.plugin("sessions", (ctx) => {
let detail = ""; // the session opened to its details
const talkOpen = new Set(); // sessions whose conversation is shown, by agent/id
const talks = new Map(); // what was said in them, as read, by agent/id
// A session's subagents sit under it, folded (#2261): the conversations
// its agent started inside it (Claude Code, Qoder, OpenCode, Kimi Code:
// s.subagents, each opened to what was said in it), and the Codex
// threads that name it as their parent_session, which are sessions of
// their own and drawn as such, only one step in. subsOpen is the
// sessions unfolded, by agent/id; kidsOf is the sessions shown under
// each one, by its id, and rootOf the top one each nested session is
// under, as last drawn.
const subsOpen = new Set();
let kidsOf = new Map();
let rootOf = new Map();
const MAX_DEPTH = 8;
let loading = 0;
let fitObserver = null;
let focus = null; // { agent, id, until }: a session to bring into sight once drawn
@@ -546,8 +558,17 @@ magpie.plugin("sessions", (ctx) => {
drawnIn.clear();
if (list[0]) opened.add(groupOf(list[0]));
}
nest(list);
// a session shown under another stays in sight: its folder and every
// session it is under are unfolded
for (const id of [detail, focus?.agent === data.agent ? focus.id : ""]) {
if (!id || !rootOf.has(id)) continue;
const byId = new Map(list.map((s) => [s.id, s]));
for (let p = byId.get(byId.get(id)?.parent_session), n = 0; p && n < MAX_DEPTH; p = byId.get(p.parent_session), n++) subsOpen.add(p.agent + "/" + p.id);
}
const groups = new Map();
for (const s of list) {
if (rootOf.has(s.id)) continue;
const k = groupOf(s);
if (!groups.has(k)) groups.set(k, []);
groups.get(k).push(s);
@@ -564,13 +585,38 @@ magpie.plugin("sessions", (ctx) => {
const all = [...groups];
// a page of folders, or as many as were drawn before, and down to the
// folder of the session opened to its details
const at = detail ? all.findIndex(([, items]) => items.some((s) => s.id === detail)) : -1;
const top = rootOf.get(detail) || detail;
const at = detail ? all.findIndex(([, items]) => items.some((s) => s.id === top)) : -1;
const n = Math.min(all.length, Math.max(drawnIn.get(FOLDERS) || SM_PAGE, at + 1));
for (const [cwd, items] of all.slice(0, n)) tree.append(folder(cwd, items, q));
if (n < all.length) tree.append(moreFolders(all, n, q));
toFocus();
}
// nest finds the sessions shown that are under another one shown: a
// Codex thread whose parent_session is, by a chain with no loop in it
function nest(list) {
const byId = new Map(list.map((s) => [s.id, s]));
kidsOf = new Map();
rootOf = new Map();
for (const s of list) {
let p = byId.get(s.parent_session), root = null;
const seen = new Set([s.id]);
while (p && !seen.has(p.id) && seen.size <= MAX_DEPTH) {
seen.add(p.id);
root = p;
p = byId.get(p.parent_session);
}
// a loop, or a chain deeper than is drawn, leaves it on top
if (!root || p) continue;
rootOf.set(s.id, root.id);
const kids = kidsOf.get(s.parent_session) || [];
kids.push(s);
kidsOf.set(s.parent_session, kids);
}
for (const kids of kidsOf.values()) kids.sort((a, b) => (a.start || a.last || "").localeCompare(b.start || b.last || ""));
}
// moreFolders adds the next page of folders above itself, as moreRow does
// a folder's sessions
function moreFolders(all, n, q) {
@@ -596,7 +642,11 @@ magpie.plugin("sessions", (ctx) => {
const open = !!q || opened.has(cwd);
const g = el("div", "list sm-group");
const r = el("div", "row sm-folder");
const writable = items.filter((s) => s.deletable);
// the sessions under those on top are the folder's too
const members = [];
const under = (s, n) => { members.push(s); if (n < MAX_DEPTH) for (const k of kidsOf.get(s.id) || []) under(k, n + 1); };
for (const s of items) under(s, 0);
const writable = members.filter((s) => s.deletable);
// the folder's box picks every session of it shown, folded or not,
// for the bar's Delete; the bar still counts sessions (#527)
if (current()?.deletable && writable.length) {
@@ -626,7 +676,7 @@ magpie.plugin("sessions", (ctx) => {
redrawList();
};
const path = cwd === GW ? "" : cwd;
r.append(fold, el("span", "sub sm-path", path), el("span", "grow"), el("span", "note", t(items.length === 1 ? "{n} session" : "{n} sessions", { n: items.length })));
r.append(fold, el("span", "sub sm-path", path), el("span", "grow"), el("span", "note", t(members.length === 1 ? "{n} session" : "{n} sessions", { n: members.length })));
const allInFolder = (data.sessions || []).filter((s) => s.cwd === cwd);
if (data.agent === "claude" && path && allInFolder.every((s) => !s.read_only && !s.gateway)
&& new Set(allInFolder.map((s) => s.wsl || "")).size === 1) {
@@ -641,7 +691,8 @@ magpie.plugin("sessions", (ctx) => {
if (open) {
// a page, or as many as were drawn before, and down to the session
// opened to its details (from the Usage page's list, #752)
const at = detail ? items.findIndex((s) => s.id === detail) : -1;
const top = rootOf.get(detail) || detail;
const at = detail ? items.findIndex((s) => s.id === top) : -1;
const n = Math.min(items.length, Math.max(drawnIn.get(cwd) || SM_PAGE, at + 1));
for (const s of items.slice(0, n)) g.append(item(s));
if (n < items.length) g.append(moreRow(cwd, items, n));
@@ -661,7 +712,7 @@ magpie.plugin("sessions", (ctx) => {
b.onclick = (e) => {
e.stopPropagation();
const next = Math.min(items.length, n + SM_PAGE);
b.before(...items.slice(n, next).map(item));
b.before(...items.slice(n, next).map((s) => item(s)));
n = next;
drawnIn.set(cwd, n);
if (n >= items.length) b.remove();
@@ -670,9 +721,10 @@ magpie.plugin("sessions", (ctx) => {
return b;
}
function item(s) {
function item(s, depth = 0) {
const a = current();
const wrap = el("div", "sess-item sm-item" + (detail === s.id ? " open" : ""));
wrap.dataset.depth = String(depth);
const r = el("div", "row sess sm-sess");
r.dataset.id = s.id;
if (a?.deletable && s.deletable) {
@@ -746,12 +798,106 @@ magpie.plugin("sessions", (ctx) => {
if (was && was !== s.id) {
const old = page.querySelector(`.row.sm-sess[data-id="${CSS.escape(was)}"]`)?.closest(".sm-item");
const prev = data.sessions.find((x) => x.id === was);
if (old && prev) old.replaceWith(item(prev));
if (old && prev) old.replaceWith(item(prev, +old.dataset.depth || 0));
}
wrap.replaceWith(item(s));
wrap.replaceWith(item(s, depth));
};
wrap.append(r);
if (detail === s.id) wrap.append(details(s));
const kids = depth < MAX_DEPTH ? kidsOf.get(s.id) || [] : [];
if (kids.length || s.subagents?.length) wrap.append(subagentsBox(s, kids, depth));
return wrap;
}
// subagentsBox is the fold under a session with its subagents: those
// its agent started inside it, each opened to its conversation, and the
// Codex threads it started, drawn as sessions
function subagentsBox(s, kids, depth) {
const box = el("div", "sm-subs");
const k = s.agent + "/" + s.id;
const subs = subTree(s.subagents || []);
const n = kids.length + subs.length;
const draw = () => {
const open = subsOpen.has(k) || (!!query.trim() && kids.length > 0);
const fold = el("button", "fold sm-subs-fold");
fold.type = "button";
fold.setAttribute("aria-expanded", String(open));
fold.append(svg(CHEV_R, 10, 1.6), el("span", "", t(n === 1 ? "{n} subagent" : "{n} subagents", { n })));
fold.onclick = (e) => {
e.stopPropagation();
if (subsOpen.has(k)) subsOpen.delete(k); else subsOpen.add(k);
draw();
};
const out = [fold];
if (open) {
const list = el("div", "sm-subs-list");
for (const c of kids) list.append(item(c, depth + 1));
for (const [sa, d] of subs) list.append(subRow(s, sa, d));
out.push(list);
}
box.replaceChildren(...out);
};
box.style.setProperty("--sub-depth", String(depth));
draw();
return box;
}
// subTree orders a session's subagents as they started one another,
// each with how deep it is under the session
function subTree(subs) {
const ids = new Set(subs.map((sa) => sa.id));
const under = new Map();
for (const sa of subs) {
const p = sa.parent && ids.has(sa.parent) && sa.parent !== sa.id ? sa.parent : "";
if (!under.has(p)) under.set(p, []);
under.get(p).push(sa);
}
const out = [];
const seen = new Set();
const walk = (p, d) => {
for (const sa of under.get(p) || []) {
if (seen.has(sa.id)) continue;
seen.add(sa.id);
out.push([sa, Math.min(d, MAX_DEPTH)]);
walk(sa.id, d + 1);
}
};
walk("", 0);
// one in a loop of parents is still shown, at the top
for (const sa of subs) if (!seen.has(sa.id)) { seen.add(sa.id); out.push([sa, 0]); walk(sa.id, 1); }
return out;
}
// subRow is one subagent of s: what it was asked, the agent it ran as,
// and a click shows what was said in it
function subRow(s, sa, d) {
const k = s.agent + "/" + s.id + "/" + sa.id;
const wrap = el("div", "sm-sub");
wrap.style.setProperty("--sub-in", String(d));
const r = el("button", "row sm-sub-row");
r.type = "button";
r.dataset.sub = sa.id;
const who = el("span", "who");
who.append(el("span", "name", sa.title || sa.kind || sa.id),
el("span", "sub", [sa.title ? sa.kind : "", sa.last || sa.start ? ago(sa.last || sa.start) : "", sa.id.slice(0, 8)].filter(Boolean).join(" · ")));
r.append(who);
const box = el("div", "sess-talk");
box.dataset.talk = k;
const show = () => {
const on = talkOpen.has(k);
r.setAttribute("aria-expanded", String(on));
wrap.classList.toggle("open", on);
box.hidden = !on;
if (on) drawTalk(box, s, sa.id);
};
r.onclick = (e) => {
e.stopPropagation();
if (window.getSelection()?.toString()) return;
if (talkOpen.has(k)) talkOpen.delete(k); else talkOpen.add(k);
show();
};
wrap.append(r, box);
show();
return wrap;
}
@@ -866,8 +1012,8 @@ magpie.plugin("sessions", (ctx) => {
// drawTalk fills box with what was said in a session, read from the
// agent's own file when it is first shown (only read, never written)
function drawTalk(box, s) {
const k = s.agent + "/" + s.id;
function drawTalk(box, s, sub = "") {
const k = s.agent + "/" + s.id + (sub ? "/" + sub : "");
const got = talks.get(k);
if (!got) {
box.replaceChildren(el("p", "cx-none", t("Reading…")));
@@ -879,10 +1025,10 @@ magpie.plugin("sessions", (ctx) => {
talks.set(k, value);
if (!talkOpen.has(k)) return;
for (const currentBox of page.querySelectorAll(".sess-talk")) {
if (currentBox.dataset.talk === k) drawTalk(currentBox, s);
if (currentBox.dataset.talk === k) drawTalk(currentBox, s, sub);
}
};
api("sessions/transcript?agent=" + encodeURIComponent(s.agent) + "&id=" + encodeURIComponent(s.id))
api("sessions/transcript?agent=" + encodeURIComponent(s.agent) + "&id=" + encodeURIComponent(s.id) + (sub ? "&sub=" + encodeURIComponent(sub) : ""))
.then((tr) => finish({ tr }), (err) => finish({ err: err.message }));
return;
}
@@ -2,6 +2,8 @@
// kernel adds them to i18n.js's (magpie.strings).
magpie.strings({
zh: {
"{n} subagent": "{n} 个子代理",
"{n} subagents": "{n} 个子代理",
"Relocate project": "迁移项目会话",
"New absolute project path": "新的项目绝对路径",
"Preview relocation": "预览迁移",
@@ -69,6 +71,8 @@ magpie.strings({
"Searched what was said in the latest {n} of {total} sessions.": "已搜索最近 {n} 个会话的对话内容(共 {total} 个)。",
},
"zh-TW": {
"{n} subagent": "{n} 個子代理",
"{n} subagents": "{n} 個子代理",
"Relocate project": "遷移專案會話",
"New absolute project path": "新的專案絕對路徑",
"Preview relocation": "預覽遷移",
@@ -136,6 +140,8 @@ magpie.strings({
"Searched what was said in the latest {n} of {total} sessions.": "已搜尋最近 {n} 個會話的對話內容(共 {total} 個)。",
},
ja: {
"{n} subagent": "{n} 個のサブエージェント",
"{n} subagents": "{n} 個のサブエージェント",
"Relocate project": "プロジェクトを移動",
"New absolute project path": "新しいプロジェクトの絶対パス",
"Preview relocation": "移動をプレビュー",
@@ -203,6 +209,8 @@ magpie.strings({
"Searched what was said in the latest {n} of {total} sessions.": "最新 {n} 件の会話の内容を検索しました(全 {total} 件)。",
},
de: {
"{n} subagent": "{n} Subagent",
"{n} subagents": "{n} Subagenten",
"Relocate project": "Projekt verschieben",
"New absolute project path": "Neuer absoluter Projektpfad",
"Preview relocation": "Verschieben prüfen",
@@ -96,3 +96,22 @@
.sm-record-clear:hover:not(:disabled) { color: var(--red); background: var(--red-soft); }
/* a folder's next page of sessions, under the ones drawn */
.sm-group .sm-more { margin: 4px 8px 6px; }
/* a session's subagents, folded under it (#2261): set in by how deep they
are, never marked off by a stripe */
.sm-subs { --sub-step: 16px; padding: 0 12px 6px calc(30px + var(--sub-depth, 0) * var(--sub-step)); }
.sm-subs-fold { font-size: 11.5px; }
.sm-subs-fold span { font-variant-numeric: tabular-nums; }
.sm-subs-list { display: flex; flex-direction: column; margin-top: 2px; border: 1px solid var(--line-2); border-radius: 9px; overflow: hidden; background: var(--card); }
.sm-subs-list > .sess-item .sess-detail { padding-left: 12px; }
/* set in, a thread's details have less room: a line's buttons go under it */
.sm-subs-list .sess-line { flex-wrap: wrap; }
.sm-subs-list > .sm-sub + .sm-sub, .sm-subs-list > .sess-item + .sm-sub, .sm-subs-list > .sm-sub + .sess-item { border-top: 1px solid var(--line-2); }
.sm-subs-list > .sess-item > .sm-subs { padding-left: calc(8px + var(--sub-step)); }
.sm-sub.open { background: color-mix(in srgb, var(--pill) 45%, transparent); }
.row.sm-sub-row { width: 100%; min-height: 38px; text-align: left; padding-left: calc(11px + var(--sub-in, 0) * var(--sub-step)); }
body.window .row.sm-sub-row { min-height: 42px; padding-left: calc(14px + var(--sub-in, 0) * var(--sub-step)); }
.row.sm-sub-row .who { display: flex; flex-direction: column; }
.sm-sub .sess-talk { margin: 0 10px 8px; }
@media (max-width: 560px) {
.sm-subs { --sub-step: 10px; padding-left: calc(12px + var(--sub-depth, 0) * var(--sub-step)); padding-right: 8px; }
}
@@ -0,0 +1,216 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// infinitr0us (#2261): a session's subagents sit under it, not beside it.
// A Claude Code session's subagents (s.subagents, as Claude Code, Qoder,
// OpenCode and Kimi Code list them) are folded under its row, "2
// subagents"; unfolded, each is a row of what it was asked and the agent
// it ran as, a subagent another one started set in under it, and a click
// shows what was said in it, read from sessions/transcript with the
// session and the subagent's id (sub=), once. A Codex thread whose
// parent_session is listed is drawn under that session, a session of its
// own still (its details open where it is), and only main sessions are on
// top; a loop of parents, or a parent not listed, leaves a thread on top.
// No click moves the page, nothing has a left-border accent, no <select>,
// nothing wider than the window. In every language, Chromium and WebKit,
// at 1100px and 420px; no backend, the API is faked.
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 at = (min) => new Date(Date.now() - min * 60e3).toISOString();
const sess = (agent, id, title, min, extra) => ({
agent, id, cwd: "/work/app", title, start: at(min + 5), last: at(min), models: [], resume: `${agent} --resume ${id}`,
path: `/x/${id}.jsonl`, size: 4096, messages: 6, files: 1, deletable: true, transcript: true, ...extra,
});
const CLAUDE = [
sess("claude", "c-1", "Refactor the parser", 5, {
files: 3,
subagents: [
{ id: "a1", title: "Inventory the parser's callers", kind: "Explore", start: at(9), last: at(8) },
{ id: "ac1d8e7a80d42178d", title: "Research MCP config", kind: "general-purpose", parent: "a1", start: at(8), last: at(7) },
],
}),
sess("claude", "c-2", "an older one", 50),
];
const CODEX = [
sess("codex", "x-1", "Lead the port", 5),
sess("codex", "x-2", "Port the lexer", 6, { role: "subagent", parent_session: "x-1", nickname: "Lexer" }),
sess("codex", "x-3", "Port the tokens", 7, { role: "subagent", parent_session: "x-2" }),
sess("codex", "x-4", "one of a loop", 20, { parent_session: "x-5" }),
sess("codex", "x-5", "the other of the loop", 21, { parent_session: "x-4" }),
sess("codex", "x-6", "its parent is gone", 30, { role: "subagent", parent_session: "x-gone" }),
];
const PARTS = [
{ role: "user", kind: "text", text: "Research task only" },
{ role: "assistant", kind: "text", text: "Kimi reads ~/.kimi/mcp.json" },
];
function serve(lang, calls) {
const store = { claude: CLAUDE, codex: CODEX };
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:false};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } });
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } });
if (url.pathname === "/api/sessions/manage") {
const agent = url.searchParams.get("agent") === "codex" ? "codex" : "claude";
return json({
agents: [
{ agent: "claude", count: CLAUDE.length, deletable: true, name: "Claude Code", icon: "claudecode-color" },
{ agent: "codex", count: CODEX.length, deletable: true, name: "Codex", icon: "codex" },
],
agent, sessions: store[agent], terminal: false, trash: [], trashDir: "~/trash",
});
}
if (url.pathname === "/api/sessions/transcript") {
const c = { agent: url.searchParams.get("agent"), id: url.searchParams.get("id") };
if (url.searchParams.has("sub")) c.sub = url.searchParams.get("sub");
calls.push(c);
return json({ parts: PARTS });
}
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)];
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
};
}
async function open(engine, lang, width, agent, t) {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage();
t.after(async () => {
if (process.env.ARTIFACT_DIR) {
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-${agent}-subagents.png`), fullPage: true });
}
await browser.close();
});
page.setDefaultTimeout(5000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
page.on("dialog", (d) => { errors.push("a browser dialog: " + d.message()); d.dismiss(); });
const calls = [];
await page.addInitScript((a) => { localStorage.setItem("magpie.sessionsAgent", a); }, agent);
await page.route("**/*", serve(lang, calls));
await page.goto("http://magpie.test/?view=providers");
await page.locator('#nav button[data-view="sessions"]').click();
const view = page.locator("#view-sessions");
const top = (l) => l.evaluate((e) => e.getBoundingClientRect().top);
const still = async (l, what, click) => {
const before = await top(l);
await click();
await page.waitForTimeout(250);
assert.equal(await top(l), before, `${what} moved the page`);
};
const tr = (k, v) => page.evaluate(([k, v]) => t(k, v), [k, v]);
const tidy = async () => {
assert.equal(await page.locator("select").count(), 0, "no native select");
const border = await page.evaluate(() => [...document.querySelectorAll("#view-sessions, #view-sessions *")]
.filter((e) => parseFloat(getComputedStyle(e).borderLeftWidth) > 1 && getComputedStyle(e).borderLeftColor !== getComputedStyle(e).borderRightColor).map((e) => e.className));
assert.deepEqual(border, [], "no left-border accent");
const wide = await page.evaluate(() => {
const box = document.querySelector("#view-sessions").getBoundingClientRect();
return [...document.querySelectorAll("#view-sessions .sm-subs *")].filter((e) => e.getBoundingClientRect().right > box.right + 1).map((e) => e.className);
});
assert.deepEqual(wide, [], "nothing under a session is wider than the page");
assert(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth), "the page doesn't scroll sideways");
};
return { page, view, calls, errors, still, tr, tidy };
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
for (const width of [1100, 420]) {
test(`${engine} ${lang} ${width}: a Claude Code session's subagents are folded under it and open to what was said`, async (t) => {
const { page, view, calls, errors, still, tr, tidy } = await open(engine, lang, width, "claude", t);
if (lang !== "en") {
const missing = await page.evaluate((lang) => ["{n} subagent", "{n} subagents"].filter((k) => !I18N[lang]?.[k]), lang);
assert.deepEqual(missing, [], `every new string has its ${lang}`);
}
const row = (id) => view.locator(`.row.sm-sess[data-id="${id}"]`);
await row("c-1").waitFor();
const item = row("c-1").locator("xpath=..");
const fold = item.locator(":scope > .sm-subs > .sm-subs-fold");
assert.equal(await fold.count(), 1);
assert.equal((await fold.textContent()).trim(), await tr("{n} subagents", { n: 2 }));
assert.equal(await fold.getAttribute("aria-expanded"), "false");
assert.equal(await view.locator(".sm-sub").count(), 0, "folded at first");
assert.equal(await row("c-2").locator("xpath=..").locator(".sm-subs").count(), 0, "a session with none has no fold");
await still(row("c-1"), "unfolding the subagents", () => fold.click());
assert.equal(await fold.getAttribute("aria-expanded"), "true");
assert.equal(await view.locator(".sess-detail").count(), 0, "the fold doesn't open the session");
const subs = item.locator(".sm-sub");
assert.deepEqual(await subs.locator(".sm-sub-row").evaluateAll((rs) => rs.map((r) => r.dataset.sub)), ["a1", "ac1d8e7a80d42178d"], "each under the one that started it");
assert.equal((await subs.nth(0).locator(".name").textContent()).trim(), "Inventory the parser's callers");
assert((await subs.nth(0).locator(".sub").textContent()).startsWith("Explore · "));
const inset = (i) => subs.nth(i).locator(".sm-sub-row .who").evaluate((e) => e.getBoundingClientRect().left);
assert(await inset(1) > await inset(0), "a subagent's own subagent is set in under it");
await tidy();
const a1 = subs.nth(1).locator(".sm-sub-row");
await still(a1, "opening a subagent", () => a1.click());
assert.equal(await a1.getAttribute("aria-expanded"), "true");
const talk = subs.nth(1).locator(".sess-talk");
await talk.locator(".cx-part").first().waitFor();
assert.deepEqual(calls, [{ agent: "claude", id: "c-1", sub: "ac1d8e7a80d42178d" }]);
assert.equal(await talk.locator(".cx-part").count(), PARTS.length);
assert((await talk.textContent()).includes("Kimi reads ~/.kimi/mcp.json"));
await tidy();
await a1.click();
assert.equal(await talk.isVisible(), false);
await a1.click();
await talk.locator(".cx-part").first().waitFor();
assert.equal(calls.length, 1, "read once");
// the session's own conversation is still its own
await row("c-1").locator(".who").click();
await view.locator(".sess-detail .sess-talk-btn").click();
await view.locator(".sess-detail .sess-talk .cx-part").first().waitFor();
assert.deepEqual(calls[1], { agent: "claude", id: "c-1" });
// folded again, it stays folded when the row is drawn again
await item.locator(".sm-subs-fold").first().click();
assert.equal(await view.locator(".sm-sub").count(), 0);
assert.deepEqual(errors, []);
});
test(`${engine} ${lang} ${width}: Codex threads sit under the session that started them`, async (t) => {
const { view, errors, still, tr, tidy } = await open(engine, lang, width, "codex", t);
const row = (id) => view.locator(`.row.sm-sess[data-id="${id}"]`);
await row("x-1").waitFor();
const tops = await view.locator(".sm-group > .sm-item > .row.sm-sess").evaluateAll((rs) => rs.map((r) => r.dataset.id));
assert.deepEqual(tops, ["x-1", "x-4", "x-5", "x-6"], "only main sessions on top; a loop or a parent not listed stays on top");
assert.equal((await view.locator(".sm-folder .note").textContent()).trim(), await tr("{n} sessions", { n: 6 }), "the folder counts the ones under others");
const fold = (id) => row(id).locator("xpath=..").locator(":scope > .sm-subs > .sm-subs-fold");
assert.equal((await fold("x-1").textContent()).trim(), await tr("{n} subagent", { n: 1 }));
for (const id of ["x-4", "x-5", "x-6"]) assert.equal(await fold(id).count(), 0, `${id} has none under it`);
await still(row("x-1"), "unfolding a Codex session", () => fold("x-1").click());
await row("x-2").waitFor();
await still(row("x-1"), "unfolding a thread", () => fold("x-2").click());
await row("x-3").waitFor();
const left = (id) => row(id).locator(".who").evaluate((e) => e.getBoundingClientRect().left);
assert(await left("x-2") > await left("x-1") && await left("x-3") > await left("x-2"), "each set in under its parent");
// a thread is a session of its own: its details open where it is
await still(row("x-3"), "opening a thread", () => row("x-3").locator(".who").click());
const d = row("x-3").locator("xpath=..").locator(":scope > .sess-detail");
await d.waitFor();
assert((await d.textContent()).includes("x-3"));
assert.equal(await row("x-3").isVisible(), true, "still under its parent");
await tidy();
// opening another closes it, and both stay where they are
await row("x-2").locator(".who").click();
await row("x-2").locator("xpath=..").locator(":scope > .sess-detail").waitFor();
assert.equal(await d.count(), 0);
assert.equal(await row("x-3").isVisible(), true);
assert.deepEqual(errors, []);
});
}
}
}