sessions: one place says which ids a ZCode request names, and drafts are one group (#5754)

On top of Flandern1211's cherry-picked fix (the commit before this one).
GatewayKeys gave the bare id of a ZCode session (sess_<id> in ZCode's
database, <id> in the gateway's record), but NativeIDs kept its own copy
of the keys: the management page still counted every ZCode session sent
through the gateway as a gateway-only session, its delete listed them,
and its search read them a second time. requestIDs is now the one place
that says which ids a request names a session by; GatewayKeys (Sessions
list, its spend, the stats' native set, viaOf, the manage search) and
NativeIDs (the manage page's count and delete) both read it.

ZCode runs a session started without a project in a folder it makes for
that session alone: <workspaceDirectory>/draft-<id> or <ms>-<uuid>, with
workspaceDirectory = ~/.zcode/workspace (read from ZCode 3.17.2's
out/host/index.js, downloaded from cdn-zcode.z.ai; never the live
~/.zcode). The reporter's group is renamed from "Scratch sessions" to
"Draft sessions" (草稿会话 / 草稿會話 / 下書きセッション /
Entwurfssitzungen), after ZCode's own word for them, with a GUI test of
its own. Comments no longer quote "Seen through the gateway", which
i18n-keys' plugin-words guard read as the core saying the word.

Run (mote, at this tree, rebased on 0eac4e6aa):
- gofmt -l: clean. go vet of sessions/gui/usage for darwin, linux
  (-tags nogui), windows; GOOS=linux -tags nogui and GOOS=windows
  go build: ok.
- go test -run 'ZCode|Gateway|Native|Manage|Merge|External'
  ./internal/sessions ./internal/usage ./internal/gui: ok.
- GUI, Chromium and WebKit: sessions-zcode-drafts (new, 5 languages x 2
  widths), sessions-folder-list, i18n-en-no-cjk: ok. i18n-keys' "a
  plugin's words are its own" is red at origin/main for three words not
  touched here, filed: #5332 (View routing), #5426 (No session ID),
  #5482 (Use the library's). The reporter's comments quoted "Seen
  through the gateway" and made a fourth; reworded.

Broken by hand:
- TestZCodeGatewayRowIsTheSessionItself on origin/main's raft.go,
  manage.go and external.go: red (keys lack zcode|main, fork_of_main,
  abc; NativeIDs lack them; 29 rows for 26 sessions).
- sessions-zcode-drafts on origin/main's Sessions client.js/i18n.js:
  red in every language and width.

Not tried:
- The full Go suite and the whole Sessions GUI set: queued behind other
  sessions on mote's suite lock; run after the push, reds filed.
- A real ZCode database: none on this machine; the reporter's own run
  over 1,105 sessions is in the issue.
- Windows/WSL GUI, and a ZCode data folder the user moved elsewhere
  (only ~/.zcode/workspace is matched).

Reported-by: flandern1211_58540 (Discord)
Refs #5754 (left open for the reporter)
This commit is contained in:
yetone
2026-11-09 18:55:01 +08:00
parent a39b63e886
commit 7cabf0da98
9 changed files with 200 additions and 44 deletions
+6 -2
View File
@@ -97,8 +97,12 @@ a prefix stripped (`sess_…`, a subagent's `sess_subagent_agent_…`:
`zcodeBareID`), its own as well as its forks' and subagents' (their files
are in its group, `Subs`, and `idInFile` reads their ids). Without it a
ZCode session whose files are here was a row under its folder and again a
row under Seen through the gateway (flandern1211_58540 on Discord;
`TestZCodeGatewayRowIsTheSessionItself`). A Claude Code
row under Seen through the gateway, and its spend counted twice
(flandern1211_58540 on Discord, #5754;
`TestZCodeGatewayRowIsTheSessionItself`). `requestIDs` is the one place
that says which ids a request names a session by: `GatewayKeys` (the
list, its spend, the stats' native set, `viaOf`, the management
page's search) and `NativeIDs` (its count and delete) both read it. A Claude Code
session Claude Desktop's Code tab ran is in Claude Code's folder, and only its lines' `entrypoint`
(`claude-desktop`, `claude-desktop-3p`) tells it apart: its parse keeps the
entrypoint of the line its folder came from (`state.Entry`), and the
+7 -6
View File
@@ -368,12 +368,13 @@ A row says the folder's name, the folder it is in (home as `~`, from the
manage reply's `home`), its newest session's title, when, and how many.
Temporary folders, the disk's root and apps' hidden folders under home
(`scratch`) wait folded under Other folders at the end; a search, or a
session opened from elsewhere, unfolds them. A ZCode session in a folder
ZCode made for that one session (`~/.zcode/workspace/<draft|time>-<uuid>`,
one for each session started without a project) is no project of the
reader's, and one folder each was 40 folders of one session: they stand as
one Scratch sessions group after the projects, before Other folders, and a
row's tooltip gives the folder it ran in (flandern1211_58540 on Discord).
session opened from elsewhere, unfolds them. A ZCode session started
without a project runs in a folder ZCode made for that one session
(`~/.zcode/workspace/draft-<id>` or `<ms>-<uuid>`, ZCode 3.17.2's host):
one folder each was 40 folders of one session each, folded under Other
folders. They stand as one Draft sessions group after the projects, and a row's
tooltip gives the folder it ran in (flandern1211_58540 on Discord, #5754;
`sessions-zcode-drafts.test.cjs`).
Checkboxes and the
Delete bar come only with Select, and Done lets the pick go. Relocate
project and Delete all sessions are in a folder's ⋯ menu, shown on hover
+16 -15
View File
@@ -88,28 +88,29 @@ magpie.plugin("sessions", (ctx) => {
const GW = "\x00gateway";
// A session its agent ran with no project of its own, in a folder the
// agent made for that one session: ZCode keeps ~/.zcode/workspace/
// <draft|time>-<uuid>, one for each session started without a project.
// draft-<id> or <ms>-<uuid> (its host, 3.17.2), one for each session
// started without a project.
// One "folder" each was 40 folders of one session, and they are no
// projects of the reader's (flandern1211_58540 on Discord): one group of
// their own, not "No folder", keeps them apart from sessions whose agent
// recorded no folder.
const SCRATCH = "\x00scratch";
const zcodeScratch = (s) => {
const DRAFTS = "\x00drafts";
const zcodeDraft = (s) => {
const home = (data?.home || "").replace(/\\/g, "/").replace(/\/+$/, "");
if (!home || s.agent !== "zcode" || !s.cwd) return false;
const c = s.cwd.replace(/\\/g, "/");
return c === home + "/.zcode/workspace" || c.startsWith(home + "/.zcode/workspace/");
};
const groupOf = (s) => zcodeScratch(s) ? SCRATCH : s.cwd || (s.gateway ? GW : "");
const groupOf = (s) => zcodeDraft(s) ? DRAFTS : s.cwd || (s.gateway ? GW : "");
const groupName = (k) => k === GW ? t("Seen through the gateway")
: k === SCRATCH ? t("Scratch sessions") : k ? baseName(k) : t("No folder");
: k === DRAFTS ? t("Draft sessions") : k ? baseName(k) : t("No folder");
// A folder an app or the system made, not a project of the reader's: the
// disk's root, a temp folder, or one under a hidden folder of a home
// (~/.some-agent/…). They go under a fold of their own after the
// projects (yetone: "/", "T" and folders named by UUIDs led the list).
const scratch = (k) => {
if (!k || k === GW || k === SCRATCH) return false;
if (!k || k === GW || k === DRAFTS) return false;
const p = k.replace(/\\/g, "/").replace(/\/+$/, "");
return p === "" || /^[a-z]:$/i.test(p)
|| /^\/(private\/)?(tmp|var\/tmp|var\/folders)(\/|$)/.test(p)
@@ -743,7 +744,7 @@ magpie.plugin("sessions", (ctx) => {
openedFor = data.agent;
opened.clear();
drawnIn.clear();
const first = list.find((s) => !scratch(groupOf(s)) && groupOf(s) !== SCRATCH) || list[0];
const first = list.find((s) => !scratch(groupOf(s)) && groupOf(s) !== DRAFTS) || list[0];
if (first) opened.add(groupOf(first));
}
nest(list);
@@ -772,15 +773,15 @@ magpie.plugin("sessions", (ctx) => {
const q = query.trim();
// the projects in one list, the folders apps and the system made
// folded under them, and the folders agents made one session each
// (SCRATCH) after the projects: they are no projects, but the reader
// (DRAFTS) after the projects: they are no projects, but the reader
// looks for the sessions in them, so not folded away either
const all = [...groups].filter(([k]) => !scratch(k) && k !== SCRATCH);
const all = [...groups].filter(([k]) => !scratch(k) && k !== DRAFTS);
const rest = [...groups].filter(([k]) => scratch(k));
const temp = groups.get(SCRATCH);
const temp = groups.get(DRAFTS);
if (all.length || temp) {
const box = el("div", "list sm-folders");
if (all.length) folderList(box, all, FOLDERS, q);
if (temp) box.append(folder(SCRATCH, temp, q));
if (temp) box.append(folder(DRAFTS, temp, q));
tree.append(box);
}
if (rest.length) tree.append(othersBox(rest, q));
@@ -900,7 +901,7 @@ magpie.plugin("sessions", (ctx) => {
const fold = el("button", "fold");
fold.type = "button";
fold.setAttribute("aria-expanded", String(open));
const path = cwd === GW || cwd === SCRATCH ? "" : cwd;
const path = cwd === GW || cwd === DRAFTS ? "" : cwd;
const line = el("span", "sm-fline");
line.append(el("span", "name", groupName(cwd)));
const where = path ? whereOf(path) : "";
@@ -1036,9 +1037,9 @@ magpie.plugin("sessions", (ctx) => {
sub.prepend(p, " ");
}
who.append(sub);
// a scratch session's folder is a UUID its agent made: the row says
// a draft session's folder is a name its agent made: the row says
// nothing of it otherwise (the group of them is one)
if (zcodeScratch(s)) r.title = s.cwd;
if (zcodeDraft(s)) r.title = s.cwd;
const hit = hitOf(s);
if (hit) who.append(hitLine(hit));
// what it spent, as the Usage page's list shows it
@@ -1480,7 +1481,7 @@ magpie.plugin("sessions", (ctx) => {
: folders ? t("Delete all {n} sessions in {k} folders?", { n: list.length, k: folders })
: t("Delete {n} sessions?", { n: list.length })));
ed.append(h);
if (folder && folder !== GW && folder !== SCRATCH) ed.append(el("p", "sub sm-ask-path", folder));
if (folder && folder !== GW && folder !== DRAFTS) ed.append(el("p", "sub sm-ask-path", folder));
const names = el("ul", "sm-ask-list");
for (const s of list.slice(0, 5)) names.append(el("li", "", s.title || s.id));
if (list.length > 5) names.append(el("li", "more", t("+{n} more", { n: list.length - 5 })));
+4 -4
View File
@@ -46,7 +46,7 @@ magpie.strings({
"This {agent} session is read only, so magpie can't delete it.": "这个 {agent} 会话是只读的,magpie 无法删除。",
"Select every session shown": "选中所有显示的会话",
"No folder": "无文件夹",
"Scratch sessions": "临时会话",
"Draft sessions": "草稿会话",
"deleted {when}": "{when}删除",
"Delete this session?": "删除这个会话?",
"Delete {n} sessions?": "删除这 {n} 个会话?",
@@ -136,7 +136,7 @@ magpie.strings({
"This {agent} session is read only, so magpie can't delete it.": "這個 {agent} 會話是唯讀的,magpie 無法刪除。",
"Select every session shown": "選中所有顯示的會話",
"No folder": "無資料夾",
"Scratch sessions": "暫存會話",
"Draft sessions": "草稿會話",
"deleted {when}": "{when}刪除",
"Delete this session?": "刪除這個會話?",
"Delete {n} sessions?": "刪除這 {n} 個會話?",
@@ -226,7 +226,7 @@ magpie.strings({
"This {agent} session is read only, so magpie can't delete it.": "この {agent} セッションは読み取り専用のため、magpie では削除できません。",
"Select every session shown": "表示中のセッションをすべて選択",
"No folder": "フォルダなし",
"Scratch sessions": "一時セッション",
"Draft sessions": "下書きセッション",
"deleted {when}": "{when}に削除",
"Delete this session?": "このセッションを削除しますか?",
"Delete {n} sessions?": "{n} 件のセッションを削除しますか?",
@@ -316,7 +316,7 @@ magpie.strings({
"This {agent} session is read only, so magpie can't delete it.": "Diese Sitzung von {agent} ist schreibgeschützt, daher kann magpie sie nicht löschen.",
"Select every session shown": "Alle angezeigten Sitzungen auswählen",
"No folder": "Kein Ordner",
"Scratch sessions": "Temporäre Sitzungen",
"Draft sessions": "Entwurfssitzungen",
"deleted {when}": "gelöscht {when}",
"Delete this session?": "Diese Sitzung löschen?",
"Delete {n} sessions?": "{n} Sitzungen löschen?",
+8 -1
View File
@@ -9,6 +9,7 @@ import (
"os"
"runtime"
"sort"
"strings"
"sync"
"time"
"unicode/utf8"
@@ -429,7 +430,13 @@ func searchSessions(ctx context.Context, agentID, query string, budget time.Dura
native := map[string]bool{}
if sessions.HasTranscript(agentID) {
for _, m := range sessions.ListAgent(agentID) {
native[m.ID] = true
// every id the gateway can know it by (a ZCode session's bare
// id, #5754), so its record is not searched again below
for _, k := range sessions.GatewayKeys(m.Session) {
if a, id, ok := strings.Cut(k, "|"); ok && a == agentID {
native[id] = true
}
}
jobs = append(jobs, job{m.Session, m.Last})
}
} else {
@@ -0,0 +1,122 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// ZCode runs a session started without a project in a folder it makes for
// that one session (~/.zcode/workspace/draft-<id> or <ms>-<uuid>). Those
// are one Draft sessions group after the projects, not one folder each folded under
// Other folders (flandern1211_58540 on Discord, #5754); a row says its
// folder in its tooltip, and the group's Delete all names no folder. In
// every language, Chromium and WebKit, wide and narrow; 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 = (id, cwd, title, min) => ({
agent: "zcode", id, cwd, title, start: at(min + 5), last: at(min), models: [],
path: "~/.zcode/cli/db/db.sqlite", size: 1024, messages: 4, files: 1, deletable: true,
});
function serve(lang, calls) {
let sessions = [
sess("sess_d1", "/home/me/.zcode/workspace/draft-k3v9", "draft one", 10),
sess("sess_a1", "/home/me/work/app", "fix the login", 20),
sess("sess_d2", "/home/me/.zcode/workspace/1791000000000-6182fe70-b234-4422-b716-09e08f8eb0dd", "draft two", 30),
sess("sess_t1", "/private/var/folders/15/p0yq/T", "a temp one", 40),
];
return async (route) => {
const req = route.request(), url = new URL(req.url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [], 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") {
return json({ agents: [{ agent: "zcode", count: sessions.length, deletable: true, name: "ZCode", icon: "zcode" }],
agent: "zcode", home: "/home/me", sessions, terminal: false, trash: [], trashDir: "~/.local/share/magpie/trash/sessions" });
}
if (url.pathname === "/api/sessions/delete") {
const body = req.postDataJSON();
calls.push(body);
sessions = sessions.filter((s) => !body.ids.includes(s.id));
return json({ deleted: body.ids, refused: [] });
}
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: "" }); }
};
}
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 [1000, 420]) {
test(`${engine} ${lang} ${width}px: ZCode's draft folders are one Draft sessions group`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const page = await (await browser.newContext({ viewport: { width, height: 700 }, 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}-sessions-zcode-drafts.png`) });
}
await browser.close();
});
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
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.route("**/*", serve(lang, calls));
await page.goto("http://magpie.test/?view=providers");
await page.evaluate(() => show("sessions"));
const view = page.locator("#view-sessions");
const tr = (k, vars) => page.evaluate(([k, vars]) => t(k, vars), [k, vars]);
const folders = view.locator(".sm-folders .row.sm-folder");
await folders.first().waitFor();
if (lang !== "en") {
assert.ok(await page.evaluate((lang) => I18N[lang]["Draft sessions"], lang), `${lang} says Draft sessions`);
}
// the project, then the drafts as one group, both in the one list;
// the project open, the drafts not
assert.deepEqual(await folders.locator(".fold .name").allTextContents(), ["app", await tr("Draft sessions")]);
const drafts = folders.nth(1);
assert.equal((await drafts.locator(".note").last().textContent()).trim(), await tr("{n} sessions", { n: 2 }));
assert.equal(await drafts.locator(".sm-path").count(), 0, "the group names no folder");
assert.equal(await drafts.locator(".fold").getAttribute("aria-expanded"), "false");
// only the temporary folder waits under Other folders
const others = view.locator(".sm-others");
await others.locator(".sm-others-fold").click();
assert.deepEqual(await others.locator(".row.sm-folder .fold .name").allTextContents(), ["T"]);
// a draft's row says where it ran
await drafts.locator(".fold").click();
const d1 = view.locator('.row.sm-sess[data-id="sess_d1"]');
await d1.waitFor();
assert.equal(await d1.getAttribute("title"), "/home/me/.zcode/workspace/draft-k3v9");
// Delete all asks without a folder's path, and deletes both drafts
await drafts.hover();
await drafts.locator(".sm-folder-more").click();
await page.locator(".row-menu").getByRole("menuitem", { name: await tr("Delete all sessions"), exact: true }).click();
const ask = page.locator("#modal .sm-ask");
await ask.waitFor();
assert.equal(await ask.locator(".sm-ask-path").count(), 0);
await ask.getByRole("button", { name: await tr("Delete"), exact: true }).click();
await ask.waitFor({ state: "detached" });
await page.waitForFunction(() => !document.querySelector('#view-sessions .row.sm-sess[data-id="sess_d1"]'));
assert.deepEqual(calls.map((c) => [...c.ids].sort()), [["sess_d1", "sess_d2"]]);
const wide = await page.evaluate(() => document.documentElement.scrollWidth > innerWidth);
assert.equal(wide, false, "nothing runs past the window");
assert.deepEqual(errors, []);
});
}
}
}
+7 -4
View File
@@ -260,10 +260,13 @@ func nativeIDsWith(agents map[string]bool, all []file, quick bool) map[string]ma
for _, fs := range groups {
id := sessionID(fs)
if a := fs[0].agent; agents[a] {
out[a][id] = true
// its subagents' calls are counted in it (subIDs)
for _, sub := range subIDs(fs, id) {
out[a][sub] = true
// by every id a request can name it (requestIDs, as
// GatewayKeys), its subagents' too: their calls are counted in
// it (subIDs)
for _, sid := range append([]string{id}, subIDs(fs, id)...) {
for _, rid := range requestIDs(a, sid) {
out[a][rid] = true
}
}
}
if fs[0].agent == "raft" && agents["pi"] {
+21 -11
View File
@@ -56,7 +56,7 @@ func raftFilesIn(dir string) []file {
// A ZCode request names its session by the id its database gives it with a
// prefix — sess_…, a subagent's sess_subagent_agent_… (zcodeBareID) — so the
// bare id is a key too: without it the same session was a row under its
// folder and again a row under "Seen through the gateway".
// folder and again a gateway-only row.
func GatewayKeys(s Session) []string {
k := []string{s.Agent + "|" + s.ID}
if s.Agent == "raft" {
@@ -69,17 +69,27 @@ func GatewayKeys(s Session) []string {
k = append(k, s.Agent+"|"+id)
}
for _, id := range s.Subs {
k = append(k, s.Agent+"|"+id)
for _, rid := range requestIDs(s.Agent, id) {
k = append(k, s.Agent+"|"+rid)
}
}
if s.Agent == "zcode" {
if bare := zcodeBareID(s.ID); bare != s.ID {
k = append(k, "zcode|"+bare)
}
for _, id := range s.Subs {
if bare := zcodeBareID(id); bare != id {
k = append(k, "zcode|"+bare)
}
}
for _, rid := range requestIDs(s.Agent, s.ID)[1:] {
k = append(k, s.Agent+"|"+rid)
}
return k
}
// requestIDs are the ids a request through the gateway can name the
// session id by, id itself first: ZCode's database gives an id a prefix
// (sess_…, a subagent's sess_subagent_agent_…) its requests leave out
// (zcodeBareID). GatewayKeys and NativeIDs both read it, so the Sessions
// list, its spend and the management page agree on which gateway record
// is a session here (#5754).
func requestIDs(agent, id string) []string {
if agent == "zcode" {
if bare := zcodeBareID(id); bare != id {
return []string{id, bare}
}
}
return []string{id}
}
+9 -1
View File
@@ -10,7 +10,7 @@ import (
// A ZCode request names its session by the id its database gives it with a
// prefix (sess_…, a subagent's sess_subagent_agent_…), so a session whose
// files are on this computer was listed twice: once under its folder, and
// again under "Seen through the gateway" as the same session under its bare
// again as a gateway-only row: the same session under its bare
// id. Its own id, its fork's and its subagent's bare ids are keys of it
// (eachGatewayKey), and those of neither of the two are rows of their own.
func TestZCodeGatewayRowIsTheSessionItself(t *testing.T) {
@@ -51,6 +51,14 @@ func TestZCodeGatewayRowIsTheSessionItself(t *testing.T) {
t.Errorf("keys %v lack %q", keys, want)
}
}
// the management page's ids (NativeIDs) are the same: its count of
// gateway-only sessions and its delete leave these records alone
native := NativeIDs(map[string]bool{"zcode": true})["zcode"]
for _, want := range []string{"sess_main", "main", "fork_of_main", "abc"} {
if !native[want] {
t.Errorf("NativeIDs lack %q: %v", want, native)
}
}
// what the gateway saw of them is that session's record: no row added
ext := []ExternalSession{
{Agent: "zcode", ID: "main"},