diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 7c08ca27d..0a4ef7e11 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -1010,6 +1010,9 @@ details.cx-part[open] > summary .cx-h { margin-bottom: 2px; } .sess-chart-head .segs .opt { height: 20px; padding: 0 9px; font-size: 11px; } .chart .sess-chart-head .peak { margin: 0; align-self: flex-end; } .sess-list { margin-top: 8px; } +/* the list is drawn in pages: the button that appends the next one, under + the rows it follows, as a card's "+N more" is */ +.sess-page-more { align-self: flex-start; margin: 6px 0 2px; font-size: 12px; } /* the overview: six figures, the calendar, and four cards two by two */ .sess-pane { container-type: inline-size; } .stats.six { grid-template-columns: repeat(6, minmax(0, 1fr)); } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 045770cc8..8f396dc6f 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -15607,6 +15607,22 @@ try { const k = localStorage.getItem("magpie.usageTab"); if (USAGE_TABS.some(([i let sessions = null; // { sessions, terminal, dirs } let sessAgent = "all"; let sessQuery = ""; +// The list is drawn in pages: every session is read (so the count beside it +// and the list agree), but a filter click or a keystroke in Search draws +// SESS_PAGE rows and no more, and "Show N more" appends the next page. A +// history of thousands rebuilt whole on every keystroke took ~300ms a +// keystroke on a fast Mac (yetone, #1019). sessShown resets to one page +// whenever the filters change, so what is drawn never grows with the history. +const SESS_PAGE = 200; +let sessShown = SESS_PAGE; +// What the last draw put in the list, for the note under it to say: drawn is +// the rows drawn and total the rows the filters kept — the same list, so a +// search that matches one session says "1 session", never "1 of 2600" (the +// note is about the list, not about every session on the computer). +let sessDrawn = null, sessTotal = null; +// what the drawn list was filtered by, so a redraw from the same filters +// keeps the pages opened and a changed one starts again at the first +let sessListKey = null; // The totals and the chart are every session's, by day, over a range; the // list is the latest sessions within it. [id, name, days (0: all)] const SESS_RANGES = [["today", "Today", 1], ["7d", "7 days", 7], ["30d", "30 days", 30], ["90d", "90 days", 90], ["all", "All", 0]]; @@ -16196,6 +16212,8 @@ function renderSessions() { box.hidden = true; chart.hidden = true; grid.hidden = true; + sessDrawn = 0; + sessTotal = 0; // the search stays where it was typed, to be cleared head.hidden = !q; } else { @@ -16237,11 +16255,37 @@ function renderSessions() { renderSessSkills(); head.hidden = !list.length && !q; box.hidden = !list.length && !q; - for (const s of list) box.append(sessionItem(s)); + // a page of the list, not all of it: the same filters keep the pages + // opened, a changed one starts at the first (see sessListKey) + const key = [sessAgent, sessModel, sessFolder, sessRange, q].join("\0"); + if (key !== sessListKey) { sessListKey = key; sessShown = SESS_PAGE; } + const page = list.slice(0, sessShown); + sessDrawn = page.length; + sessTotal = list.length; + for (const s of page) box.append(sessionItem(s)); + if (list.length > page.length) { + const more = el("button", "text sess-page-more"); + more.textContent = t("Show {n} more", { n: Math.min(SESS_PAGE, list.length - page.length) }); + more.onclick = () => { sessShown += SESS_PAGE; renderSessions(); }; + box.append(more); + } if (!list.length && q) box.append(el("div", "empty-state", t("No session matches."))); } const dirs = (sessions?.dirs || []).join(" · "); - $("#sessNote").textContent = t("Totals count every session in the agents' own files; the list is the latest {n} by activity · {dirs}", { n: all.length, dirs }); + // The list is every session the filters keep, drawn in pages, so the note + // counts that list and not every session on the computer: a search that + // matches one session says "1 session", not "1 of 2600", which read as if + // the rest were behind a "Show more" that isn't there (yetone, #1019). + // Nothing left to draw, the note is just the list's length, in words a + // reader uses: one session is a session, not "1 sessions". + const parts = [t("Totals count every session in the agents' own files")]; + if (sessDrawn !== null) { + parts.push(sessDrawn < sessTotal + ? t("showing {drawn} of {n}", { drawn: sessDrawn, n: sessTotal }) + : t(sessTotal === 1 ? "{n} session" : "{n} sessions", { n: sessTotal })); + } + if (dirs) parts.push(dirs); + $("#sessNote").textContent = parts.join(" · "); } // sessSums adds up usage rows by one of their fields, the most tokens first diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 68ada4fa8..ae25b19b7 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2049,6 +2049,8 @@ const I18N = { "No sessions yet. Claude Code's, Codex's, Hermes, OpenCode's and Pi's sessions on this computer show up here, with what each cost and the command that resumes it.": "还没有会话。本机 Claude Code、Codex、Hermes、OpenCode 和 Pi 的会话会显示在这里,附费用和继续会话的命令。", "Reading the agents' session files…": "正在读取 Agent 的会话文件…", "Totals count every session in the agents' own files; the list is the latest {n} by activity · {dirs}": "合计含 Agent 文件中的全部会话;列表为最近活动的 {n} 个 · {dirs}", + "Totals count every session in the agents' own files": "合计含 Agent 文件中的全部会话", + "showing {drawn} of {n}": "显示 {n} 个中的 {drawn} 个", "90 days": "90 天", "All folders": "全部文件夹", "Search {n}…": "搜索 {n} 项…", @@ -5596,6 +5598,8 @@ const I18N = { "No sessions yet. Claude Code's, Codex's, Hermes, OpenCode's and Pi's sessions on this computer show up here, with what each cost and the command that resumes it.": "セッションはまだありません。このコンピュータ上の Claude Code、Codex、Hermes、OpenCode、Pi のセッションが、それぞれの費用と再開コマンドとともにここに表示されます。", "Reading the agents' session files…": "エージェントのセッションファイルを読み取り中…", "Totals count every session in the agents' own files; the list is the latest {n} by activity · {dirs}": "合計はエージェント自身のファイルにあるすべてのセッションを集計しています。一覧は最近のアクティビティ順で {n} 件 · {dirs}", + "Totals count every session in the agents' own files": "合計はエージェント自身のファイルにあるすべてのセッションを集計しています", + "showing {drawn} of {n}": "{n} 件中 {drawn} 件を表示", "90 days": "90 日", "All folders": "すべてのフォルダ", "Search {n}…": "{n} 件を検索…", @@ -9141,6 +9145,8 @@ const I18N = { "No sessions yet. Claude Code's, Codex's, Hermes, OpenCode's and Pi's sessions on this computer show up here, with what each cost and the command that resumes it.": "Noch keine Sitzungen. Sitzungen von Claude Code, Codex, Hermes, OpenCode und Pi auf diesem Computer erscheinen hier, jeweils mit Kosten und dem Befehl zum Fortsetzen.", "Reading the agents' session files…": "Sitzungsdateien der Agenten werden gelesen…", "Totals count every session in the agents' own files; the list is the latest {n} by activity · {dirs}": "Summen zählen jede Sitzung in den Dateien der Agenten; die Liste zeigt die {n} zuletzt aktiven · {dirs}", + "Totals count every session in the agents' own files": "Summen zählen jede Sitzung in den Dateien der Agenten", + "showing {drawn} of {n}": "{drawn} von {n} angezeigt", "90 days": "90 Tage", "All folders": "Alle Ordner", "Search {n}…": "{n} durchsuchen…", diff --git a/internal/gui/sessions.go b/internal/gui/sessions.go index 64ce793e3..eaa8cf6a9 100644 --- a/internal/gui/sessions.go +++ b/internal/gui/sessions.go @@ -41,6 +41,16 @@ func sessionRoutes(mux *http.ServeMux, w Windows) { warmSessions() mux.HandleFunc("GET /api/sessions", func(rw http.ResponseWriter, r *http.Request) { n, _ := strconv.Atoi(r.URL.Query().Get("limit")) + // The page draws a session count taken from every session + // (statsFor's Overview) beside this list, so the list is read as + // long as the count: at sessions.Limit the page said "238 sessions" + // over a list that stopped at 200, and the agents whose sessions + // were oldest fell off it whole — Codex had 121 and the list showed + // 7. Only a caller that asks for a number of its own gets one. The + // page draws this many rows in pages of its own (renderSessions). + if n <= 0 { + n = sessions.All + } agents := map[string]*agent.Agent{} for _, a := range agent.Clients() { agents[a.ID] = a diff --git a/internal/gui/sessions_list_test.go b/internal/gui/sessions_list_test.go new file mode 100644 index 000000000..ca37f7253 --- /dev/null +++ b/internal/gui/sessions_list_test.go @@ -0,0 +1,87 @@ +package gui + +import ( + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + + "github.com/yetone/magpie/internal/sessions" +) + +// The Sessions page draws a session count taken from every session beside its +// list, so the list has to be as long as that count. The endpoint used to fall +// back to sessions.Limit (200) when the page asked for no number — and the +// page never asks for one — so the page said "N sessions" over a list that +// stopped at 200 and the agents whose sessions were oldest fell off it whole. +// A caller that asks for a number of its own still gets it. +func TestSessionsListIsAsLongAsTheCount(t *testing.T) { + h := sandboxHome(t) + claude := filepath.Join(h, ".claude") + // five past sessions.Limit, which is also the window traceRecentFiles + // sizes gateway attribution over + const n = sessions.Limit + 5 + line := `{"parentUuid":null,"isSidechain":false,"type":"user","message":{"role":"user","content":"hi %d"},"uuid":"u","timestamp":"2026-09-20T10:00:0%d.000Z","cwd":"/work","sessionId":"%s"}` + "\n" + + `{"parentUuid":"u","isSidechain":false,"message":{"model":"claude-sonnet-5","id":"msg_1","type":"message","role":"assistant","content":[{"type":"text","text":"done"}],"usage":{"input_tokens":10,"output_tokens":2}},"requestId":"req_1","type":"assistant","uuid":"a","timestamp":"2026-09-20T10:00:0%d.000Z","cwd":"/work","sessionId":"%s"}` + "\n" + // as Claude Code keeps them: a session's own .jsonl in its project's + // folder, one folder per project + proj := filepath.Join(claude, "projects", "-work") + if err := os.MkdirAll(proj, 0o755); err != nil { + t.Fatal(err) + } + for i := 0; i < n; i++ { + id := fmt.Sprintf("%08d-1111-2222-3333-444444444444", i) + b := []byte(fmt.Sprintf(line, i, i%10, id, (i%10)+1, id)) + if err := os.WriteFile(filepath.Join(proj, id+".jsonl"), b, 0o644); err != nil { + t.Fatal(err) + } + } + t.Setenv("CLAUDE_CONFIG_DIR", claude) + sessions.Reset() + t.Cleanup(sessions.Reset) + + mux := http.NewServeMux() + sessionRoutes(mux, folderOnly{}) + get := func(q string) []struct { + ID string `json:"id"` + When int64 `json:"t"` + } { + w := httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest("GET", "/api/sessions"+q, nil)) + if w.Code != 200 { + t.Fatalf("%s: %d %s", q, w.Code, w.Body) + } + var out struct { + Sessions []struct { + ID string `json:"id"` + When int64 `json:"t"` + } `json:"sessions"` + } + if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil { + t.Fatal(err) + } + return out.Sessions + } + // no number asked for: the whole set, as the count beside the list is + all := get("") + if len(all) != n { + t.Fatalf("the list holds %d sessions, want %d (every one of them)", len(all), n) + } + // newest first by last activity: the last one written is the first listed + for i := 1; i < len(all); i++ { + if all[i-1].When < all[i].When { + t.Fatalf("not newest first at %d: %d before %d", i, all[i-1].When, all[i].When) + } + } + // a number of the caller's own is still honoured + if few := get("?limit=5"); len(few) != 5 { + t.Fatalf("?limit=5 gave %d sessions, want 5", len(few)) + } + // and one past sessions.Limit is not quietly clipped to it + if over := get("?limit=" + fmt.Sprint(sessions.Limit+1)); len(over) != sessions.Limit+1 { + t.Fatalf("?limit=%d gave %d, want %d", sessions.Limit+1, len(over), sessions.Limit+1) + } +} diff --git a/internal/gui/tests/sessions-paging.test.cjs b/internal/gui/tests/sessions-paging.test.cjs new file mode 100644 index 000000000..42b2bfad4 --- /dev/null +++ b/internal/gui/tests/sessions-paging.test.cjs @@ -0,0 +1,168 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// The Sessions tab's list is every session the filters keep, drawn a page at a +// time: a filter click or a keystroke in Search draws the first page and no +// more, "Show N more" appends the next, and the note under the list says how +// many of how many are drawn. Without the pages a history of thousands was +// rebuilt whole on every keystroke (~300 ms a keystroke on a fast Mac, and +// worse on Windows: yetone, #1019). The data stays complete, so the count +// beside the list and the list still agree. 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 reader = require("./reader.cjs"); + +const assets = path.resolve(__dirname, "../assets"); +const to = new Date(2026, 8, 28); +const iso = (d) => [d.getFullYear(), d.getMonth() + 1, d.getDate()].map((n) => String(n).padStart(2, "0")).join("-"); +const N = 2600; // past two pages of 200, so a third page is left over +const DAYS = 30; + +// N sessions, newest first, one every few minutes; every 25th names another +// model, so a filter has something to narrow to +const sessions = Array.from({ length: N }, (_, i) => ({ + agent: "claude", name: "Claude Code", icon: "claude", id: "s" + i, + cwd: i % 2 ? "/work/alpha" : "/work/beta", title: i === 0 ? "Fix the session list" : "Session " + i, + start: new Date(to.getTime() - (i + 30) * 60e3).toISOString(), + last: new Date(to.getTime() - (i + 1) * 60e3).toISOString(), + input: 1000 + i, output: 100, cache_read: 0, cache_write: 0, cost: 0.01, priced: true, + models: [{ model: i % 25 === 0 ? "claude-opus-4" : "claude-sonnet-5", input: 1000 + i, output: 100, cost: 0.01, priced: true }], + resume: "claude --resume s" + i, +})); +const days = Array.from({ length: DAYS }, (_, i) => { + const d = new Date(to); d.setDate(d.getDate() - (DAYS - 1 - i)); + return { date: iso(d), usage: [{ agent: "claude", cwd: "/work/alpha", model: "claude-opus-4", input: 30000, output: 4000, cache_read: 0, cache_write: 0, cost: 1.5, priced: true }], active: [] }; +}); + +function serve(lang) { + const state = { agents: [{ id: "claude", name: "Claude Code", path: "/t.json", fields: [] }], profiles: [], settings: { lang, theme: "light" } }; + 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:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state); + if (url.pathname === "/api/sessions/progress") return json({ indexing: false }); + if (url.pathname === "/api/sessions") return json({ sessions, dirs: ["/test/sessions"] }); + if (url.pathname === "/api/sessions/stats") return json({ from: days[0].date, to: iso(to), days, agents: { claude: "Claude Code" } }); + if (url.pathname === "/api/sessions/overview") return json({ + count: N, median: 120000, p90: 880000, days: days.map(() => 1), + top: { tokens: [], cost: [], active: [] }, messages: days.map(() => 30), output: days.map(() => 0), + shape: { + messages: { edges: [1, 6, 16, 31, 61, 121], counts: [3, 10, 14, 9, 4, 2], total: N }, + minutes: { edges: [1, 6, 16, 31, 61, 121], counts: [20, 12, 6, 3, 1, 0], total: N }, + autonomy: { edges: [0, 1, 3, 6, 11, 21], counts: [5, 7, 10, 12, 6, 2], total: N }, + }, + tools: { calls: 0, sessions: 0, top: [], categories: [], weeks: [] }, + skills: { calls: 0, count: 0, top: [] }, + }); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + if (url.pathname === "/api/usage/quotas") return json([]); // an array, as the Go side writes it + if (url.pathname === "/api/usage/quotas/history") return json({ days: [] }); + 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: "" }); + }; +} + +const words = { + en: { + more: /^Show 200 more$/, + // The note counts the list the filters kept, not every session on the + // computer: a page of them reads "showing 200 of 2600", and a list drawn + // whole reads its own length — "1 session" for one, "N sessions" for + // more. The number picks the word, so the regex does too: `sessions?` + // would let "1 sessions" through. + showing: (drawn, total) => new RegExp(`showing ${drawn} of ${total}`), + whole: (n) => new RegExp(`· ${n} ${n === 1 ? "session" : "sessions"} ·`), + none: "No session matches.", + }, + zh: { + more: /^显示其余 200 个$/, + showing: (drawn, total) => new RegExp(`显示 ${total} 个中的 ${drawn} 个`), + // Chinese has no plural: one word either way + whole: (n) => new RegExp(`· ${n} 个会话 ·`), + none: "没有匹配的会话。", + }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh"]) { + test(`${engine} ${lang}: the Sessions list is drawn in pages over a long history`, async (t) => { + const w = words[lang]; + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const page = await (await browser.newContext({ viewport: { width: 1000, height: 760 }, reducedMotion: "reduce" })).newPage(); + t.after(() => browser.close()); + page.setDefaultTimeout(10000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + // the Sessions tab, over all ranges, as it was left + await page.addInitScript(() => { localStorage.setItem("magpie.usageTab", "sessions"); localStorage.setItem("magpie.sessRange", "all"); }); + await page.route("**/*", serve(lang)); + await page.goto("http://magpie.test/?view=usage"); + await page.locator("#sessGrid:not([hidden])").waitFor(); + const rows = page.locator("#sessList .row.sess"); + const more = page.locator("#sessList .sess-page-more"); + + // the first page and no more: 200 rows of the 2600 the list holds + assert.equal(await rows.count(), 200, "the first page"); + assert.equal(await more.count(), 1, "a way to the next page"); + assert.match(await more.innerText(), w.more); + assert.match(await page.locator("#sessNote").innerText(), w.showing(200, N)); + + // The next page appends 200 more, and the note follows. The button is + // under 200 rows, so it is pressed through the DOM: what this test is + // about is the pages, not bringing a control into sight (click-scroll + // and reader.cjs cover that). + await more.evaluate((b) => b.click()); + assert.equal(await rows.count(), 400, "the second page, on top of the first"); + assert.match(await page.locator("#sessNote").innerText(), w.showing(400, N)); + // and the rows already drawn are the same elements, not rebuilt + const first = await rows.first().getAttribute("data-key"); + await more.evaluate((b) => b.click()); + assert.equal(await rows.count(), 600, "the third page"); + assert.equal(await rows.first().getAttribute("data-key"), first, "the rows above stayed where they were"); + assert.match(await page.locator("#sessNote").innerText(), w.showing(600, N)); + + // a keystroke in Search is a new list: it starts at the first page again + // and, over 2600 sessions, does not take the time the whole list would. + // 1111 of them name "Session 1" ("1", "1x", "1xx", "1xxx"), so the note + // counts that list — 200 of 1111, not of the 2600 on the computer + const q = page.locator("#sessQ"); + const at = Date.now(); + await q.fill("Session 1"); + const took = Date.now() - at; + assert(await rows.count() <= 200, "a search draws a page, not the history"); + assert.equal(await rows.count(), 200, "a page of the matches"); + assert.match(await page.locator("#sessNote").innerText(), w.showing(200, 1111)); + assert(took < 250, `a keystroke over ${N} sessions took ${took}ms`); + + // a filter that keeps nothing says so, and the note counts nothing + await q.fill("nothing matches this at all"); + await page.locator("#sessList .empty-state").waitFor(); + assert.equal(await rows.count(), 0); + assert.match(await page.locator("#sessNote").innerText(), w.whole(0)); + await q.press("Escape"); + await page.locator("#sessList .row.sess").first().waitFor(); + assert.equal(await rows.count(), 200, "clearing the search draws the first page again"); + assert.match(await page.locator("#sessNote").innerText(), w.showing(200, N)); + + // A search that matches fewer than a page holds them all: the note says + // "1 session", not "1 of 2600" — there is no "Show more" for the other + // 2599, and saying so would send the reader looking for one. The whole + // list is drawn, so it is the length and not "1 of 1" (yetone, #1019). + await q.fill("Fix the session list"); + await page.locator("#sessList .row.sess").first().waitFor(); + assert.equal(await rows.count(), 1, "the one match"); + assert.equal(await more.count(), 0, "a list shorter than a page has no way to more"); + assert.match(await page.locator("#sessNote").innerText(), w.whole(1)); + assert.doesNotMatch(await page.locator("#sessNote").innerText(), new RegExp(String(N)), "the note doesn't count the whole history"); + + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go index 7ae36fff3..48809f44a 100644 --- a/internal/sessions/sessions.go +++ b/internal/sessions/sessions.go @@ -121,9 +121,19 @@ type Session struct { // so a swapped one prices against the same copy as the default does. var PriceOf = priceOf -// Limit is how many sessions, the latest by last activity, List reads. +// Limit is how many sessions, the latest by last activity, List reads when +// the caller asks for no particular number. traceRecentFiles sizes the +// window gateway attribution is judged over by it too, so it is not raised +// to make a listing longer: a caller that wants more asks for more. const Limit = 200 +// All is what a listing that means every session asks List for: the count a +// page or a command shows beside the list is taken from every session, so +// the list has to be as long as the count, and this is long past any history +// a computer has. Limit stays what it is because traceRecentFiles sizes +// gateway attribution by it. +const All = 5000 + // state is what one file's parse has come to, enough to read on from Off. type state struct { Codex *codexUsageState `json:"-"` diff --git a/internal/tui/sessions.go b/internal/tui/sessions.go index e14cf3350..650e24c8c 100644 --- a/internal/tui/sessions.go +++ b/internal/tui/sessions.go @@ -43,7 +43,11 @@ type sessFilterMsg struct { func (m *model) reloadSessions() { m.sstats = sessions.StatsFor(sessRanges[m.srange].days) - m.slist = sessions.List(0) + // the whole set, as the page's count beside it is taken from: the list + // head says how many there are, and the range filter narrows what is + // shown of them. sessions.Limit is the window gateway attribution is + // judged over, not a listing's length, so this asks for sessions.All + m.slist = sessions.List(sessions.All) m.ssel = clamp(m.ssel, len(m.sessShown())) } diff --git a/internal/tui/sessions_test.go b/internal/tui/sessions_test.go index b1c57a1a3..abef21130 100644 --- a/internal/tui/sessions_test.go +++ b/internal/tui/sessions_test.go @@ -231,3 +231,45 @@ func TestSessChart(t *testing.T) { t.Error("a chart of one day") } } + +// The page's list is the whole set, not sessions.Limit: the head says how +// many sessions there are, and the list has to be as long as that. It read +// List(sessions.Limit+1) — 201 — which kept the bug the GUI had, only past a +// different number (yetone, #1019). +func TestSessionsListIsNotCutAtTheLimit(t *testing.T) { + sessionsHome(t) + claude := os.Getenv("CLAUDE_CONFIG_DIR") + proj := filepath.Join(claude, "projects", "-work-many") + if err := os.MkdirAll(proj, 0o755); err != nil { + t.Fatal(err) + } + // past sessions.Limit and past a page of the GUI's list, as Claude Code + // keeps them: one .jsonl per session in its project's folder + const n = sessions.Limit + 10 + for i := range n { + id := fmt.Sprintf("%08d-1111-2222-3333-444444444444", i) + line := fmt.Sprintf(`{"parentUuid":null,"isSidechain":false,"type":"user","message":{"role":"user","content":"hi %d"},"uuid":"u","timestamp":"2026-09-20T10:00:00.000Z","cwd":"/work/many","sessionId":"%s"}`+"\n"+ + `{"parentUuid":"u","isSidechain":false,"message":{"model":"claude-opus-5-5","id":"msg_1","type":"message","role":"assistant","content":[{"type":"text","text":"done"}],"usage":{"input_tokens":10,"output_tokens":2}},"requestId":"req_1","type":"assistant","uuid":"a","timestamp":"2026-09-20T10:00:05.000Z","cwd":"/work/many","sessionId":"%s"}`+"\n", i, id, id) + if err := os.WriteFile(filepath.Join(proj, id+".jsonl"), []byte(line), 0o644); err != nil { + t.Fatal(err) + } + } + sessions.Reset() + m := model{w: 160, h: 40, srange: len(sessRanges) - 1} // every range + m.reloadSessions() + // the fixtures' own sessions are here too: what matters is that the ten + // past sessions.Limit are, which a list cut at the limit would drop + seen := map[string]bool{} + for _, s := range m.slist { + seen[s.ID] = true + } + for i := range n { + id := fmt.Sprintf("%08d-1111-2222-3333-444444444444", i) + if !seen[id] { + t.Fatalf("the list of %d is missing %s: it was cut at the limit", len(m.slist), id) + } + } + if got := len(m.sessShown()); got < n { + t.Fatalf("the page shows %d sessions, want at least %d", got, n) + } +} diff --git a/sessions_cli.go b/sessions_cli.go index 86bf89a12..35c775341 100644 --- a/sessions_cli.go +++ b/sessions_cli.go @@ -104,7 +104,12 @@ func sessionsTo(w io.Writer, args []string, now time.Time) error { if o.days >= 0 { return sessionStats(w, o, sessions.StatsAt(o.days, now), now) } - return sessionList(w, o, sessions.List(0), now) + // the list reads every session, as the "%d more" foot and a model or + // folder picked among them are counted over the whole set: sessions.Limit + // cut it to 200 whatever --limit said, so --limit 500 could never show + // more than 200 and the foot was counted off that truncated list. Only + // o.limit rows are printed, so reading the rest costs a parse, not output + return sessionList(w, o, sessions.List(sessions.All), now) } // resolve finds what was typed among what there is: the same, then the diff --git a/sessions_cli_test.go b/sessions_cli_test.go index 0cbcff22d..9fad118b8 100644 --- a/sessions_cli_test.go +++ b/sessions_cli_test.go @@ -3,6 +3,7 @@ package main import ( "bytes" "encoding/json" + "fmt" "os" "path/filepath" "strings" @@ -131,6 +132,55 @@ func TestSessionsCmd(t *testing.T) { } } +// The "%d more with --limit" foot is counted over every session, not over a +// list cut at sessions.Limit: with the default --limit 20 the command read +// only 200, so a history longer than that reported a remainder that was +// wrong, and a model or folder filter picked among the rest could never be +// resolved (yetone, #1019). +func TestSessionsMoreCountsTheWholeSet(t *testing.T) { + now := sessionsHome(t) + claude := os.Getenv("CLAUDE_CONFIG_DIR") + proj := filepath.Join(claude, "projects", "-work-many") + if err := os.MkdirAll(proj, 0o755); err != nil { + t.Fatal(err) + } + // past sessions.Limit: the fixtures hold 2, so 210 more + const n = sessions.Limit + 10 + for i := range n { + id := fmt.Sprintf("%08d-1111-2222-3333-444444444444", i) + line := fmt.Sprintf(`{"parentUuid":null,"isSidechain":false,"type":"user","message":{"role":"user","content":"hi %d"},"uuid":"u","timestamp":"2026-09-20T10:00:00.000Z","cwd":"/work/many","sessionId":"%s"}`+"\n"+ + `{"parentUuid":"u","isSidechain":false,"message":{"model":"claude-opus-5-5","id":"msg_1","type":"message","role":"assistant","content":[{"type":"text","text":"done"}],"usage":{"input_tokens":10,"output_tokens":2}},"requestId":"req_1","type":"assistant","uuid":"a","timestamp":"2026-09-20T10:00:05.000Z","cwd":"/work/many","sessionId":"%s"}`+"\n", i, id, id) + if err := os.WriteFile(filepath.Join(proj, id+".jsonl"), []byte(line), 0o644); err != nil { + t.Fatal(err) + } + } + sessions.Reset() + + // the default --limit 20 prints 20 rows and says how many are left of all + got := runSessions(t, now, "--limit", "20") + if !strings.Contains(got, "latest 20") { + t.Fatalf("the foot of the default:\n%s", got) + } + total := 2 + n // the fixtures' own two and these + if want := fmt.Sprintf("· %d more with --limit", total-20); !strings.Contains(got, want) { + t.Errorf("the foot says %q, want %q:\n%s", footOf(got), want, got) + } + // and --limit past 200 shows that many, which the old read could not + if got := runSessions(t, now, "--limit", "205"); !strings.Contains(got, "latest 205") { + t.Errorf("--limit 205:\n%s", got) + } +} + +// footOf is the line the command's foot is on, for a failure message. +func footOf(out string) string { + for _, l := range strings.Split(out, "\n") { + if strings.Contains(l, "with --limit") || strings.Contains(l, "latest ") { + return strings.TrimSpace(l) + } + } + return "" +} + // The hit rate is of all the prompts came to: what was written to the // cache counts in it, as Input leaves it out — a prompt written again at // every turn showed near 100% otherwise.