diff --git a/docs/subsystems/gateway-sessions.md b/docs/subsystems/gateway-sessions.md index 8cec7c260..f8f848032 100644 --- a/docs/subsystems/gateway-sessions.md +++ b/docs/subsystems/gateway-sessions.md @@ -66,7 +66,19 @@ the gateway's `omp|` is its own in the same places as Raft's `pi|` key, and is never a second session counted again (Jumy, Discord 10-30: `TestOmpSubagentsAreTheSessionsToTheGateway`, `TestOmpSubagentCountedOnceWithTheGateway`). A Claude Code session's -copies (`Copies`) are among its keys the same way. On `/api/sessions/manage`, in its +copies (`Copies`) are among its keys the same way. 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 +session is listed under `claude` with `App` `claude-desktop`. It is the +gateway's `claude-desktop|` too, as the gateway knows the Code tab by +Desktop's user agent, in `MergeExternal`, the stats' native keys, the GUI's +list and Via. Usage counts it under Desktop, as its calls are: the stats' +rows and its summary carry `claude-desktop`, its key stays `claude:`, +and Usage › Sessions files it under its `app` (`TestStatsDesktopCodeTab`, +`usage-sessions-desktop-app.test.cjs`). `NativeIDs` for `claude-desktop` +doesn't read Claude Code's files yet (#4333). On `/api/sessions/manage`, +in its counts as in its list, and on `/api/sessions/delete`, a native session is any session file the agent keeps, one nothing was said in too, with no limit (`sessions.NativeIDs`); one pass over the agents' files (`sessions.Manage`) diff --git a/internal/gui/assets/plugins/usage/page.js b/internal/gui/assets/plugins/usage/page.js index a8771a42e..f25caec50 100644 --- a/internal/gui/assets/plugins/usage/page.js +++ b/internal/gui/assets/plugins/usage/page.js @@ -2963,11 +2963,13 @@ function renderSessions() { // the agent filter is a menu, as the model and folder ones beside it: a // strip of a segment per agent ran past the window with a dozen of them // in range, and scrolled sideways to reach the last - const agents = [...new Map([...all.map((s) => [s.agent, s.name]), ...Object.entries(st.agents || {})]).entries()]; + // a session is under the agent it ran in: s.app, when its files are + // another's (Claude Desktop's Code tab's, in Claude Code's folder) + const agents = [...new Map([...all.map((s) => [s.app || s.agent, s.name]), ...Object.entries(st.agents || {})]).entries()]; if (sessAgent !== "all" && !agents.some(([id]) => id === sessAgent)) sessAgent = "all"; // the model and folder filters offer what the range has, under the other filters - const byAgent = (x) => sessAgent === "all" || x.agent === sessAgent; + const byAgent = (x) => sessAgent === "all" || (x.app || x.agent) === sessAgent; const byModel = (x) => !sessModel || x.model === sessModel; const byFolder = (x) => !sessFolder || x.cwd === sessFolder; const spent = (list, key) => { @@ -3471,7 +3473,7 @@ function renderSessTop() { const list = ov.top?.[sessTopBy] || []; const body = el("div", "sess-tops"); if (!list.length) body.append(el("div", "sess-none", ov.top ? t("Nothing in this range.") : "…")); - const icons = new Map((sessions?.sessions || []).map((s) => [s.agent, s.icon])); + const icons = new Map((sessions?.sessions || []).map((s) => [s.app || s.agent, s.icon])); const names = sessStats?.agents || {}; for (const s of list) { const open = sessTopOpen === s.key; diff --git a/internal/gui/sessions.go b/internal/gui/sessions.go index fe0b4e8ba..45f3fa359 100644 --- a/internal/gui/sessions.go +++ b/internal/gui/sessions.go @@ -143,8 +143,10 @@ func sessionRoutes(mux *http.ServeMux, w Windows) { // was copied through every size on the way, ~140 MB of eight (#2278) out.Sessions = make([]sessionJSON, 0, len(list)) for _, s := range list { + // drawn as the agent it ran in: Claude Desktop's Code tab's + // sessions are in Claude Code's folder (Session.App) j := sessionJSON{Session: s, Name: s.Agent, Icon: "generic", Via: viaOf(vias, s)} - if a := agents[s.Agent]; a != nil { + if a := agents[cmp.Or(s.App, s.Agent)]; a != nil { j.Name, j.Icon = a.SharedName(), a.Icon } j.Name = wslName(j.Name, s) @@ -264,7 +266,7 @@ func sessionRoutes(mux *http.ServeMux, w Windows) { } j := sessionJSON{Session: s, Name: s.Agent, Icon: "generic"} for _, a := range agent.Clients() { - if a.ID == s.Agent { + if a.ID == cmp.Or(s.App, s.Agent) { j.Name, j.Icon = a.SharedName(), a.Icon } } diff --git a/internal/gui/tests/usage-sessions-desktop-app.test.cjs b/internal/gui/tests/usage-sessions-desktop-app.test.cjs new file mode 100644 index 000000000..770323ac4 --- /dev/null +++ b/internal/gui/tests/usage-sessions-desktop-app.test.cjs @@ -0,0 +1,98 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Usage › Sessions: a session Claude Desktop's Code tab ran has its files in +// Claude Code's folder, so /api/sessions lists it under agent "claude", with +// the agent it ran in as "app" (CyberCaius on Discord: Desktop's sessions +// shown under Claude Code). The agent filter goes by the app: Claude +// Desktop lists it, Claude Code doesn't, and its row keeps Claude Code's +// key. English and Chinese, Chromium and WebKit. +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 iso = (d) => [d.getFullYear(), d.getMonth() + 1, d.getDate()].map((n) => String(n).padStart(2, "0")).join("-"); +const today = iso(new Date()); +const now = new Date().toISOString(); +const tok = { input: 1000, output: 100, cache_read: 0, cache_write: 0 }; +const sessions = [ + { agent: "claude", app: "claude-desktop", id: "s3p", name: "Claude Desktop", icon: "claude-color", title: "Desktop task", cwd: "/work/app", start: now, last: now, models: [{ model: "m1", ...tok }], ...tok }, + { agent: "claude", id: "sess1", name: "Claude Code", icon: "claude-color", title: "Terminal task", cwd: "/work/app", start: now, last: now, models: [{ model: "m2", ...tok }], ...tok }, +]; +const stats = { + from: today, to: today, keys: ["claude:s3p", "claude:sess1"], + agents: { "claude-desktop": "Claude Desktop", claude: "Claude Code" }, + days: [{ + date: today, + usage: [ + { agent: "claude-desktop", cwd: "/work/app", model: "m1", ...tok, cost: 0.1, priced: true }, + { agent: "claude", cwd: "/work/app", model: "m2", ...tok, cost: 0.1, priced: true }, + ], + active: [], + }], +}; + +function serve(lang) { + 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/sessions/progress") return json({ indexing: false }); + if (url.pathname === "/api/sessions") return json({ sessions, dirs: [] }); + if (url.pathname === "/api/sessions/stats") return json(stats); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/usage/quotas") return json([]); + 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)]; + const body = await fs.readFile(file).catch(() => null); + return body ? route.fulfill({ body, contentType }) : route.fulfill({ status: 404, body: "" }); + }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh"]) { + test(`${engine} ${lang}: a Code tab session is listed under Claude Desktop`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width: 860, height: 700 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(8000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang)); + await page.addInitScript(() => { localStorage.setItem("magpie.usageTab", "sessions"); localStorage.setItem("magpie.sessRange", "all"); localStorage.setItem("magpie.usageEvery", "0"); }); + await page.goto("http://magpie.test/?view=usage"); + const pick = page.locator("#sessAgent"); + await pick.waitFor({ state: "visible" }); + const listed = () => page.locator("#sessList .sess-item .who .name").allInnerTexts(); + await page.waitForFunction(() => document.querySelectorAll("#sessList .sess-item").length === 2); + assert.deepEqual((await listed()).sort(), ["Desktop task", "Terminal task"]); + + const choose = async (name) => { + await pick.click(); + const menu = page.locator(".pop.proto-menu.sess-menu"); + await menu.waitFor(); + await menu.locator(".pm-item", { hasText: name }).click(); + await menu.waitFor({ state: "detached" }); + await page.waitForFunction((n) => document.querySelector("#sessAgent span")?.textContent === n, name); + }; + // the menu has each agent once: the session's app, not a second + // Claude Code from its folder + await pick.click(); + const names = await page.locator(".pop.proto-menu.sess-menu .pm-item .pm-name").allInnerTexts(); + assert.deepEqual(names.slice(1).sort(), ["Claude Code", "Claude Desktop"]); + await page.keyboard.press("Escape"); + await page.locator(".pop.proto-menu.sess-menu").waitFor({ state: "detached" }); + + await choose("Claude Desktop"); + await page.waitForFunction(() => document.querySelectorAll("#sessList .sess-item").length === 1); + assert.deepEqual(await listed(), ["Desktop task"]); + await choose("Claude Code"); + await page.waitForFunction(() => [...document.querySelectorAll("#sessList .sess-item .who .name")].map((e) => e.textContent).join() === "Terminal task"); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/sessions/claude.go b/internal/sessions/claude.go index 86d08b45e..12a8ef6e4 100644 --- a/internal/sessions/claude.go +++ b/internal/sessions/claude.go @@ -26,6 +26,7 @@ type ccLine struct { AITitle string `json:"aiTitle"` CustomTitle string `json:"customTitle"` Summary string `json:"summary"` + Entrypoint string `json:"entrypoint"` Message struct { ID string `json:"id"` Model string `json:"model"` @@ -49,6 +50,7 @@ var ( ccCustom = []byte(`"type":"custom-title"`) ccSummary = []byte(`"type":"summary"`) ccCwd = []byte(`"cwd":"`) + ccEntry = []byte(`"entrypoint":"`) ) var ( @@ -167,10 +169,15 @@ func ccRandomUUID(u string) bool { } // ccWhere takes the session's folder and id from the end of a line, while -// they are not known. +// they are not known, and the entrypoint from the line the folder was +// found in: each line names both, and a file of an older Claude Code that +// names no entrypoint isn't searched for one on every line. func ccWhere(s *state, b []byte) { if s.Cwd == "" { s.Cwd = strAt(b, ccCwd) + if s.Cwd != "" { + s.Entry = strAt(b, ccEntry) + } } if s.ID == "" { s.ID = strAt(b, ccSession) @@ -326,7 +333,7 @@ func claudeFull(s *state, b []byte, main bool) { return } if s.Cwd == "" && l.Cwd != "" { - s.Cwd = l.Cwd + s.Cwd, s.Entry = l.Cwd, l.Entrypoint } if s.ID == "" && l.SessionID != "" { s.ID = l.SessionID diff --git a/internal/sessions/external.go b/internal/sessions/external.go index 5c55b90a7..8ef08ce17 100644 --- a/internal/sessions/external.go +++ b/internal/sessions/external.go @@ -45,6 +45,9 @@ func MergeExternal(native []Session, external []ExternalSession) []Session { if s.Agent == "raft" { seen[agentID{"pi", s.ID}] = struct{}{} } + if s.App != "" { + seen[agentID{s.App, s.ID}] = struct{}{} + } for _, id := range s.Copies { seen[agentID{s.Agent, id}] = struct{}{} } diff --git a/internal/sessions/raft.go b/internal/sessions/raft.go index 5e4772d41..c304fcf4b 100644 --- a/internal/sessions/raft.go +++ b/internal/sessions/raft.go @@ -48,14 +48,18 @@ func raftFilesIn(dir string) []file { // GatewayKeys are the "agent|id" keys a session's gateway record can // carry: its own; for Raft's, Pi's, as Raft's Pi tells the gateway it is -// Pi; the ids of the copies of its conversation (ccCopies); and its -// subagents' own ids (subIDs), whose calls it counts already. -// MergeExternal keeps the same keys as pairs. +// Pi; for one Claude Desktop's Code tab ran, Desktop's, as the gateway +// knows its requests by Desktop's user agent; the ids of the copies of its +// conversation (ccCopies); and its subagents' own ids (subIDs), whose calls +// it counts already. MergeExternal keeps the same keys as pairs. func GatewayKeys(s Session) []string { k := []string{s.Agent + "|" + s.ID} if s.Agent == "raft" { k = append(k, "pi|"+s.ID) } + if s.App != "" { + k = append(k, s.App+"|"+s.ID) + } for _, id := range s.Copies { k = append(k, s.Agent+"|"+id) } diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go index 77974d202..69effdd51 100644 --- a/internal/sessions/sessions.go +++ b/internal/sessions/sessions.go @@ -137,6 +137,11 @@ type Session struct { Unpriced int `json:"unpriced"` // models that spent tokens but have no known price Resume string `json:"resume"` // the command that picks the session up again Path string `json:"path"` // its (main) file + // App is the agent the session ran in when it isn't the one whose files + // hold it: claude-desktop for a Claude Code session Claude Desktop's Code + // tab ran (its entrypoint, desktopEntrypoint). Usage counts the session + // under App; the key, resume and transcript stay Agent's. + App string `json:"app,omitempty"` // Carry are the other agents that can carry the session on, reading its // file as it is (carry.go) Carry []Carry `json:"carry,omitempty"` @@ -213,6 +218,9 @@ type state struct { // Days is Models again, split by the local date each message was // written on: a session that runs past midnight counts on both days. Days named[*day] `json:"days,omitempty"` + // Claude Code: the entrypoint its first line naming one says, which + // tells a session Claude Desktop's Code tab ran (desktopEntrypoint) + Entry string `json:"entry,omitempty"` // Claude Code: the message last counted, whose later lines repeat it, // and the day it was counted on Msg string `json:"msg,omitempty"` @@ -1046,7 +1054,8 @@ func CachePath() string { return filepath.Join(filepath.Dir(catalog.CachePath()) // 26: Grok Build's tool calls and skills. // 27: Factory Droid's skills (its Skill tool and / prompts). // 28: OpenCode 2's, Cline's and dsh's tool calls and skills. -const cacheVersion = 28 +// 29: Claude Code's entrypoint (Entry), Desktop's Code tab apart. +const cacheVersion = 29 type cacheFile struct { Version int `json:"version"` @@ -1675,6 +1684,9 @@ func assembleListed(fs []file, price func(string) *catalog.Price, codexTitle fun if first == "" { first = st.First } + if s.Agent == "claude" && s.App == "" && desktopEntrypoint(st.Entry) { + s.App = "claude-desktop" + } s.Convs = append(s.Convs, st.Convs...) } if s.Agent == "codex" && st.CodexNickname != "" { diff --git a/internal/sessions/stats.go b/internal/sessions/stats.go index 5d659b38c..c9fac94f4 100644 --- a/internal/sessions/stats.go +++ b/internal/sessions/stats.go @@ -272,6 +272,20 @@ func statsKept(ranges []int, now time.Time, wantNative bool) ([]Stats, map[strin return out, keptStats.native } +// appsOf is the agent each session ran in, by key, where it isn't the one +// whose files hold it (Session.App): a Claude Code session Claude Desktop's +// Code tab ran is Desktop's, as its calls are (claudeCallLine), though its +// transcript is in Claude Code's own folder. +func appsOf(files []file) map[string]string { + out := map[string]string{} + for _, f := range files { + if st := cache[f.path]; f.main && f.agent == "claude" && st != nil && desktopEntrypoint(st.Entry) { + out[f.key] = "claude-desktop" + } + } + return out +} + // statsOfRange is one range's Stats from what statsReadAll read, with the // locks it holds. listed is every session as listed, by key, or nil to // assemble the range's own. @@ -317,6 +331,7 @@ func statsOfRange(days int, today time.Time, files []file, copies map[string]str perDate []dayShare } shares := map[string]*share{} + apps := appsOf(files) for _, f := range files { if f.mod.Before(since) || (copies[f.key] != "" && copied[f.path] == nil) { continue @@ -335,6 +350,7 @@ func statsOfRange(days int, today time.Time, files []file, copies map[string]str if cwd == "" { cwd = st.Cwd } + agent := cmp.Or(apps[f.key], f.agent) for date, d := range st.Days.all() { if date == "" || date < from || date > out.To { continue @@ -343,14 +359,14 @@ func statsOfRange(days int, today time.Time, files []file, copies map[string]str if t.zero() { continue } - k := uk{date, f.agent, cwd, model} + k := uk{date, agent, cwd, model} u := use[k] u.add(t) use[k] = u dates[date] = true } if d.Active > 0 { - k := ak{date, f.agent, cwd} + k := ak{date, agent, cwd} a := act[k] if a == nil { a = &act0{} @@ -502,7 +518,7 @@ func statsOfRange(days int, today time.Time, files []file, copies map[string]str } setSessionCodexIdentity(&s, identities) setSessionCodexTaskTitle(&s, taskTitles) - sum := Summary{Key: key, Agent: s.Agent, ID: s.ID, Cwd: cmp.Or(folder[key], s.Cwd), Title: clip(s.Title, titleKept), + sum := Summary{Key: key, Agent: cmp.Or(s.App, s.Agent), ID: s.ID, Cwd: cmp.Or(folder[key], s.Cwd), Title: clip(s.Title, titleKept), Nickname: s.Nickname, Last: s.Last, Role: s.Role, ParentSession: s.ParentSession, RootSession: s.RootSession, Priced: true, Active: sh.active / 1000, Models: []string{}, Days: []int{}, Prompts: sh.prompts, Replies: sh.replies, tools: countsOf(sh.tools, nil), skills: countsOf(sh.skills, sh.skillLast)} diff --git a/internal/sessions/stats_desktop_test.go b/internal/sessions/stats_desktop_test.go new file mode 100644 index 000000000..05e148334 --- /dev/null +++ b/internal/sessions/stats_desktop_test.go @@ -0,0 +1,68 @@ +package sessions + +import ( + "path/filepath" + "testing" +) + +// A session Claude Desktop's Code tab ran is kept in Claude Code's own +// folder, and only its lines' entrypoint tells it apart. Usage counts it +// under Desktop, as its calls are (TestCallsDesktop3pCodeTab), not under +// Claude Code (CyberCaius on Discord: Desktop's sessions under Claude +// Code); its key, resume and transcript stay Claude Code's, and the +// gateway's record of it under Desktop is the same session, not another. +func TestStatsDesktopCodeTab(t *testing.T) { + for _, entry := range []string{"claude-desktop", "claude-desktop-3p"} { + t.Run(entry, func(t *testing.T) { + d := setupCalls(t) + writeLines(t, filepath.Join(d.claude, "projects", "-work-app", "s3p.jsonl"), + // first an attachment, whose folder and entrypoint are taken + // without reading it whole (ccWhere) + `{"parentUuid":null,"isSidechain":false,"attachment":{"type":"skill_listing"},"type":"attachment","uuid":"a1","timestamp":"`+stamp(0)+`","cwd":"/work/app","sessionId":"s3p","entrypoint":"`+entry+`"}`, + `{"type":"user","timestamp":"`+stamp(0)+`","message":{"role":"user","content":"hello"},"cwd":"/work/app","sessionId":"s3p","entrypoint":"`+entry+`"}`, + swap(swap(claudeMsg("m1", "claude-haiku-5-5", 1, 2, 3, 4, 1), `"entrypoint":"cli"`, `"entrypoint":"`+entry+`"`), `"sessionId":"sess1"`, `"sessionId":"s3p"`)) + writeLines(t, filepath.Join(d.claude, "projects", "-work-app", "sess1.jsonl"), + `{"type":"user","timestamp":"`+stamp(0)+`","message":{"role":"user","content":"hi"},"cwd":"/work/app","sessionId":"sess1","entrypoint":"cli"}`, + claudeMsg("m2", "claude-opus-5-5", 1, 2, 3, 4, 2)) + + apps := map[string]string{} + for _, s := range List(All) { + if s.Agent != "claude" { + t.Fatalf("listed under %q: %+v", s.Agent, s) + } + apps[s.ID] = s.App + } + if len(apps) != 2 || apps["s3p"] != "claude-desktop" || apps["sess1"] != "" { + t.Fatalf("apps %v", apps) + } + + st, native := StatsAndNative(0) + byModel := map[string]string{} + for _, day := range st.Days { + for _, u := range day.Usage { + byModel[u.Model] = u.Agent + } + } + if byModel["claude-haiku-5-5"] != "claude-desktop" || byModel["claude-opus-5-5"] != "claude" { + t.Fatalf("usage by model's agent %v", byModel) + } + sums := map[string]Summary{} + for _, s := range st.Sessions { + sums[s.ID] = s + } + if s := sums["s3p"]; s.Agent != "claude-desktop" || s.Key != "claude:s3p" { + t.Fatalf("desktop summary %+v", s) + } + if s := sums["sess1"]; s.Agent != "claude" || s.Key != "claude:sess1" { + t.Fatalf("cli summary %+v", s) + } + if !native["claude|s3p"] || !native["claude-desktop|s3p"] || native["claude-desktop|sess1"] { + t.Fatalf("native %v", native) + } + merged := MergeExternal(List(All), []ExternalSession{{Agent: "claude-desktop", ID: "s3p"}, {Agent: "claude-desktop", ID: "sess1"}}) + if len(merged) != 3 { + t.Fatalf("merged %d: %+v", len(merged), merged) + } + }) + } +}