sessions: the Sessions page answers before a first read of a long history
hey_boyce on X: "会话tab等的时间有点长", the page standing on its skeleton rows on its first open. /api/sessions/manage read every file it had no usable parse of whole before answering: the agent shown, and every agent with a gateway session for its ids (Codex's 52 GB too while Claude Code's page was shown). That is every file after a first start, a cacheVersion bump, or a Claude Code or Codex file whose kept parse can't be read on after a restart.536a98316,936bdccfa,926ef769f,f193c3865andefd1b697emade polls and warm reads cheap; this is the cold one. Now Manage reads at once only what is cheap (a parse that has only grown). Once more than 32 MB (quickBytes) would be read whole, those files are read behind the answer, as Stats and List read them, and their rows stand on the parse kept or on a glance: the file's first 256 KB with its agent's own line parser (id, folder, first prompt, start) and, for Claude Code, the titles in its last 64 KB, with the file's time as its last activity. Such a row has pending: true and no counts. The Sessions page asks again every 1.5 s while any row is pending, and redraws only the list, so the filter keeps its focus and the folders shown stay. A glance is never saved in the index (savable), and a refresh never takes it as a parse (parsed). A small store is read whole as before, so its rows come complete the first time. Measured on the Linux box (magpie-desktop), a sandbox HOME with 1,200 Claude Code files and 600 Codex rollouts (1,985 MB, 2% 20 MB, 10% 2-8 MB) and one Codex gateway record. Each mode ran in a fresh process, twice, origin/main449231c19against this change: - no index, Claude Code's page, first answer: 1.94 s / 1.83 s before, 282 ms / 343 ms after; - no index, Codex's page after it: 8.93 s / 0.73 s before, 1.63 s / 1.73 s after; - no index, every row read whole: 10.9 s / 2.6 s before, 2.0 s / 2.1 s after; - with the index: Claude Code 51-61 ms before, 49-51 ms after; Codex 700-714 ms before, 718-800 ms after. On the owner's real store (13 GB of Claude Code and 52 GB of Codex files, counted read-only), a cold first answer read all 65 GB. A glance reads at most 320 KB a file. The fixture was in the page cache, so these numbers undersell a cold disk. Tests: - TestManageAnswersBeforeFirstReads holds every whole read on parseHook. On this change Manage answers with pending, glanced rows and Codex's ids, leaves no glance in the cache or a save, and answers a second ask while the read is under way. After the read, the rows are counted, no longer pending, and have the folder and title the glance showed. Broken by hand (Manage back on plain refresh): red at its 30 s fail-safe, "Manage waited for the whole read (2 files being read)". - sessions-pending-fill.test.cjs: pending rows show at once, are asked for again on the page clock and filled in with the filter still focused and typed into, and then no more asks. What was run: - mote: go vet ./internal/sessions ./internal/gui; go test ./internal/sessions ok. - go test ./internal/gui on mote at load 35-67, under another session's full GUI suite: TestCoreScriptBudget was red on origin/main too (#4133, fixed since in 3959192e9; this change adds no core bytes). Ten real-window AppKit tests were killed at their deadlines (#2645, #4125). - Linux (wsl-run): gofmt, go vet -tags nogui, go test ./internal/sessions ok. go test -tags nogui -timeout 40m ./internal/gui (1021 s): red only in TestCoreScriptBudget (#4133, the base's) and TestRestartHandsTheGatewayOver, a request reaching the old pid after the handover (#4167, not on this path). Rebased onaad6546cd, both pass 3 of 3 with -count=3. GUI files sessions-pending-fill, sessions-manage, sessions-manage-paging, sessions-folder-paging, sessions-search and sessions-toolbar in Chromium and WebKit: 44 of 44 pass. Not run: - The full go test ./... suite and the whole GUI suite: mote went unreachable mid-run, and WebKit hung there on existing tests too (#4125). - No real account: the bench uses a generated store.
This commit is contained in:
@@ -48,6 +48,19 @@ 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`)
|
||||
reads only the agent shown and the agents with gateway sessions (#2776).
|
||||
It answers before a first read of a long history (hey_boyce on X: the page
|
||||
stood on its placeholder rows on its first open). A file it would read whole
|
||||
(no parse kept, an older index, a file written over, or a Claude Code or
|
||||
Codex parse that can't be read on after a restart) is read behind the
|
||||
answer once more than `quickBytes` (32 MB) of them is waiting; until then its
|
||||
row stands on the parse kept, or on a glance at its first 256 KB (id,
|
||||
folder, first prompt, start) and, for Claude Code, the titles in its last
|
||||
64 KB, with its last activity the file's time. Such a row has `pending:
|
||||
true` and no counts, the page asks again every 1.5 s until none is, and a
|
||||
glance is never saved in the index (`savable`) nor taken by a refresh as a
|
||||
parse (`parsed`). See
|
||||
[`internal/sessions/manage_quick.go`](../../internal/sessions/manage_quick.go),
|
||||
`TestManageAnswersBeforeFirstReads` and `sessions-pending-fill.test.cjs`.
|
||||
Gateway projections have no path,
|
||||
resume command or terminal action: the agent's own files of them are not on
|
||||
this computer. Their rows carry `gateway: true`; the Sessions page groups them
|
||||
|
||||
@@ -114,8 +114,29 @@ magpie.plugin("sessions", (ctx) => {
|
||||
const UNDO = "M5.5 3.5 2.5 6.5l3 3M2.5 6.5H10a3.5 3.5 0 0 1 0 7H7";
|
||||
const MOVE = "M2.5 8h10M9.5 5l3 3-3 3";
|
||||
|
||||
// fillIn asks again, while rows are still pending (a file of theirs not
|
||||
// read whole yet: their first lines are what shows), for what the read
|
||||
// behind the answer has found; only the list is drawn again, so the
|
||||
// filter keeps its focus and an open menu stays.
|
||||
let fillT = 0;
|
||||
function fillSoon() {
|
||||
clearTimeout(fillT);
|
||||
if (!data?.sessions?.some((s) => s.pending)) return;
|
||||
const n = loading, was = data.agent;
|
||||
fillT = setTimeout(async () => {
|
||||
if (n !== loading || view !== "sessions") return;
|
||||
let d;
|
||||
try { d = await api("sessions/manage?agent=" + encodeURIComponent(was)); } catch { return fillSoon(); }
|
||||
if (n !== loading || !data || data.agent !== was || d?.agent !== was) return;
|
||||
data = { ...data, ...d, agents: d?.agents || [], sessions: (d?.sessions || []).map((s) => ({ ...s, models: s.models || [] })), trash: d?.trash || [], agent: was };
|
||||
if (view === "sessions" && !trashOn) redrawList(); // the pages shown stay
|
||||
fillSoon();
|
||||
}, 1500);
|
||||
}
|
||||
|
||||
async function load(name) {
|
||||
const n = ++loading;
|
||||
clearTimeout(fillT);
|
||||
if (!data) draw();
|
||||
try {
|
||||
const d = await api("sessions/manage?agent=" + encodeURIComponent(name ?? agent));
|
||||
@@ -131,6 +152,7 @@ magpie.plugin("sessions", (ctx) => {
|
||||
failed = e.message;
|
||||
}
|
||||
if (view === "sessions") draw();
|
||||
if (n === loading) fillSoon();
|
||||
}
|
||||
|
||||
// reveal: the Sessions page, from the Usage page's list (#752):
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// hey_boyce on X: the Sessions page stood on its placeholder rows for a
|
||||
// long time on its first open. magpie now answers before it has read a
|
||||
// long history whole: rows it hasn't read yet come from their files' first
|
||||
// lines and say they are pending, and the page asks again until none is.
|
||||
// Here the first answer has every row pending and no messages counted; the
|
||||
// page shows its rows at once, asks again on its own clock, and draws the
|
||||
// counts in without taking the filter's focus, then stops asking.
|
||||
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 nap = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const at = (min) => new Date(Date.now() - min * 60e3).toISOString();
|
||||
const sess = (id, cwd, title, min, extra) => ({
|
||||
agent: "claude", id, cwd, title, start: at(min + 5), last: at(min), models: [],
|
||||
resume: `cd ${cwd} && claude --resume ${id}`, path: `~/.claude/projects/x/${id}.jsonl`, size: 4096, files: 1, deletable: true, ...extra,
|
||||
});
|
||||
|
||||
function serve(lang, seen) {
|
||||
const state = { agents: [], 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/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") {
|
||||
seen.manage++;
|
||||
const read = seen.manage > 1; // read whole by the second ask
|
||||
const extra = read ? { messages: 6 } : { pending: true };
|
||||
return json({
|
||||
agents: [{ agent: "claude", count: 2, deletable: true, name: "Claude Code", icon: "claudecode-color" }],
|
||||
agent: "claude", sessions: [sess("a-1", "/work/app", "fix the login form", 3, extra), sess("a-2", "/work/app", "older task", 90, extra)],
|
||||
terminal: true, trash: [], trashDir: "~/trash",
|
||||
});
|
||||
}
|
||||
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: { nav: "Sessions", six: "6 messages" },
|
||||
zh: { nav: "会话", six: "6 条消息" },
|
||||
"zh-TW": { nav: "會話", six: "6 條訊息" },
|
||||
ja: { nav: "セッション", six: "6 件のメッセージ" },
|
||||
de: { nav: "Sitzungen", six: "6 Nachrichten" },
|
||||
};
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const [lang, width] of [["en", 900], ["zh", 900], ["zh-TW", 700], ["ja", 700], ["de", 420]]) {
|
||||
const w = words[lang];
|
||||
test(`${engine} ${lang} ${width}px: pending rows show at once and fill in`, 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, height: 560 }, reducedMotion: "reduce" })).newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
const errors = [], seen = { manage: 0 };
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", serve(lang, seen));
|
||||
await page.clock.install();
|
||||
await page.goto("http://magpie.test/?view=providers");
|
||||
await page.locator("#nav").getByRole("button", { name: w.nav, exact: true }).click();
|
||||
const view = page.locator("#view-sessions");
|
||||
const row = view.locator('.row.sm-sess[data-id="a-1"]');
|
||||
await row.waitFor();
|
||||
assert.equal(seen.manage, 1);
|
||||
assert.ok(!(await row.textContent()).includes(w.six), "counted before the read");
|
||||
// the reader is typing in the filter when the counts come in
|
||||
const filter = view.locator(".sm-filter");
|
||||
await filter.click();
|
||||
await filter.pressSequentially("fi");
|
||||
await page.clock.runFor(2000);
|
||||
for (let i = 0; i < 100 && !(await row.textContent()).includes(w.six); i++) await nap(20);
|
||||
assert.ok((await row.textContent()).includes(w.six), "the counts were not drawn in");
|
||||
assert.equal(seen.manage, 2);
|
||||
assert.equal(await page.evaluate(() => document.activeElement?.classList.contains("sm-filter")), true, "the filter lost its focus");
|
||||
assert.equal(await filter.inputValue(), "fi");
|
||||
await filter.pressSequentially("x");
|
||||
assert.equal(await filter.inputValue(), "fix");
|
||||
// none pending: no more asks
|
||||
await page.clock.runFor(6000);
|
||||
await nap(100);
|
||||
assert.equal(seen.manage, 2, "asked again with nothing pending");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -49,6 +49,10 @@ type Managed struct {
|
||||
Messages int `json:"messages"`
|
||||
Files int `json:"files"`
|
||||
Deletable bool `json:"deletable"`
|
||||
// Pending: a file of it is still being read for the first time, and
|
||||
// what it spent and its messages aren't counted yet (the Sessions page
|
||||
// answers before such a read, manage_quick.go)
|
||||
Pending bool `json:"pending,omitempty"`
|
||||
// Codex: the provider the session was made with, and the one its Codex
|
||||
// uses now, whose sessions alone its history lists (#887)
|
||||
Provider string `json:"provider,omitempty"`
|
||||
@@ -167,14 +171,24 @@ func Manage(native map[string]bool, pick func([]AgentCount, map[string]map[strin
|
||||
loadCache()
|
||||
defer useDBs()()
|
||||
all := allFiles()
|
||||
v := ManageView{Agents: agentCounts(all), Native: nativeIDs(native, all)}
|
||||
v := ManageView{Agents: agentCounts(all), Native: nativeIDsWith(native, all, true)}
|
||||
v.Agent = pick(v.Agents, v.Native)
|
||||
if v.Agent != "" {
|
||||
v.Sessions = listAgent(v.Agent, all)
|
||||
v.Sessions = listAgentWith(v.Agent, all, true)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// readFor brings want's parses up to date: all of them, or, quick, as
|
||||
// quickRead does, with pending the paths still being read.
|
||||
func readFor(want, all []file, quick bool) (pending map[string]bool, done func()) {
|
||||
if !quick {
|
||||
refresh(want, all)
|
||||
return nil, func() {}
|
||||
}
|
||||
return quickRead(want, all)
|
||||
}
|
||||
|
||||
// idInFile says which agents' session ids are read from inside the
|
||||
// session's file, not taken from its name (as assemble does).
|
||||
func idInFile(agent string) bool {
|
||||
@@ -186,6 +200,10 @@ func idInFile(agent string) bool {
|
||||
}
|
||||
|
||||
func nativeIDs(agents map[string]bool, all []file) map[string]map[string]bool {
|
||||
return nativeIDsWith(agents, all, false)
|
||||
}
|
||||
|
||||
func nativeIDsWith(agents map[string]bool, all []file, quick bool) map[string]map[string]bool {
|
||||
groups := byKey(all, func(f *file) bool { return agents[f.agent] })
|
||||
var want []file
|
||||
for _, f := range all {
|
||||
@@ -196,7 +214,8 @@ func nativeIDs(agents map[string]bool, all []file) map[string]map[string]bool {
|
||||
want = append(want, f)
|
||||
}
|
||||
}
|
||||
refresh(want, all)
|
||||
_, done := readFor(want, all, quick)
|
||||
defer done()
|
||||
out := map[string]map[string]bool{}
|
||||
for a := range agents {
|
||||
out[a] = map[string]bool{}
|
||||
@@ -208,6 +227,10 @@ func nativeIDs(agents map[string]bool, all []file) map[string]map[string]bool {
|
||||
}
|
||||
|
||||
func listAgent(agent string, all []file) []Managed {
|
||||
return listAgentWith(agent, all, false)
|
||||
}
|
||||
|
||||
func listAgentWith(agent string, all []file, quick bool) []Managed {
|
||||
groups := byKey(all, func(f *file) bool { return f.agent == agent })
|
||||
var mine []file
|
||||
for _, f := range all {
|
||||
@@ -215,7 +238,8 @@ func listAgent(agent string, all []file) []Managed {
|
||||
mine = append(mine, f)
|
||||
}
|
||||
}
|
||||
refresh(mine, all)
|
||||
pending, done := readFor(mine, all, quick)
|
||||
defer done()
|
||||
identities := map[string]CodexIdentity(nil)
|
||||
taskTitles := map[codexTaskTitle]string(nil)
|
||||
if agent == "codex" {
|
||||
@@ -239,6 +263,7 @@ func listAgent(agent string, all []file) []Managed {
|
||||
m := Managed{Session: s, Files: len(fs), Deletable: Deletable(agent) && !s.ReadOnly}
|
||||
for _, f := range fs {
|
||||
m.Size += f.size
|
||||
m.Pending = m.Pending || pending[f.path]
|
||||
if st := cache[f.path]; st != nil && f.main {
|
||||
for _, d := range st.Days.all() {
|
||||
m.Messages += d.Prompts + d.Replies
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
package sessions
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"maps"
|
||||
"runtime"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// The Sessions page answers before the files it has never read are read
|
||||
// whole (hey_boyce on X: the page showed its placeholder rows for a long
|
||||
// time on its first open). A first read of a long history (13 GB of Claude
|
||||
// Code's and 52 GB of Codex's files on one computer) takes minutes, and
|
||||
// Manage used to read all of it before it answered: the agent shown, and
|
||||
// every agent with a gateway session for its ids, Codex's too while Claude
|
||||
// Code was shown. It still reads at once what is cheap: a file it has a
|
||||
// parse of that has only grown, read on from where the parse left off. A
|
||||
// file it would read whole (none kept, an older magpie's index, a file
|
||||
// written over, or a Claude Code or Codex file whose kept parse can't be
|
||||
// read on after a restart) is read behind the answer, as Stats and List
|
||||
// read it, and until then its row stands on what is known now: the parse
|
||||
// kept of it, or a glance at its first lines (its id, folder, first prompt
|
||||
// and start), with its last activity the file's time. Such a row says it
|
||||
// is Pending, and the page asks again until none is.
|
||||
|
||||
// glanceBytes is how far into a file a glance reads at most.
|
||||
const glanceBytes = 256 << 10
|
||||
|
||||
// quickBytes is how much reading whole the page still waits for: a store
|
||||
// that small is read in well under a second, even on a slow disk, and its
|
||||
// rows come complete the first time.
|
||||
var quickBytes int64 = 32 << 20
|
||||
|
||||
var (
|
||||
// glances are the files glanced at, by path, while their whole read
|
||||
// is under way; each stands for the size and time it was read at
|
||||
glances = map[string]*state{}
|
||||
// overlaid are the glances put into the cache for one pass of
|
||||
// Manage, never saved with it
|
||||
overlaid = map[string]*state{}
|
||||
// behind are the paths a read behind an answer has taken, and
|
||||
// behindRuns the reads, waited for by Reset
|
||||
behind = map[string]bool{}
|
||||
behindRuns sync.WaitGroup
|
||||
)
|
||||
|
||||
// readsWhole says whether bringing f's parse up to date reads the file
|
||||
// from its start: no parse of it is kept, or the one kept can't be read on.
|
||||
// Only the agents read line by line can be glanced at; the others are read
|
||||
// as before.
|
||||
func readsWhole(f file, old *state) bool {
|
||||
p := parserFor(f.agent)
|
||||
if p.line == nil {
|
||||
return false
|
||||
}
|
||||
if old == nil || f.size < old.Size || old.Off > f.size {
|
||||
return true
|
||||
}
|
||||
if f.agent == "codex" && old.Codex == nil {
|
||||
return true
|
||||
}
|
||||
return p.claude && old.Claude == nil
|
||||
}
|
||||
|
||||
func current(f file, s *state) bool {
|
||||
return s != nil && s.Size == f.size && s.Mod == f.mod.UnixNano()
|
||||
}
|
||||
|
||||
// quickRead is refresh for the Sessions page, under mu: what is cheap is
|
||||
// read now, and what would be read whole is read behind. pending are the
|
||||
// paths not read yet, and done takes the glances back out of the cache;
|
||||
// nothing may let mu go between the two.
|
||||
func quickRead(want, all []file) (pending map[string]bool, done func()) {
|
||||
var now, later []file
|
||||
for _, f := range want {
|
||||
if f.cold {
|
||||
continue
|
||||
}
|
||||
if old := cache[f.path]; !current(f, old) && readsWhole(f, old) {
|
||||
later = append(later, f)
|
||||
continue
|
||||
}
|
||||
now = append(now, f)
|
||||
}
|
||||
var whole int64
|
||||
for _, f := range later {
|
||||
whole += f.size
|
||||
}
|
||||
if whole <= quickBytes {
|
||||
now, later = append(now, later...), nil
|
||||
}
|
||||
refresh(now, all)
|
||||
pending = map[string]bool{}
|
||||
var start, look []file
|
||||
for _, f := range later {
|
||||
old := cache[f.path]
|
||||
if current(f, old) {
|
||||
continue // read meanwhile
|
||||
}
|
||||
pending[f.path] = true
|
||||
if !behind[f.path] {
|
||||
start = append(start, f)
|
||||
}
|
||||
if old == nil && f.main && !current(f, glances[f.path]) {
|
||||
look = append(look, f)
|
||||
}
|
||||
}
|
||||
if len(start) > 0 {
|
||||
readBehind(start)
|
||||
}
|
||||
if len(look) > 0 {
|
||||
mu.Unlock()
|
||||
seen := glanceAll(look)
|
||||
mu.Lock()
|
||||
for i, f := range look {
|
||||
if seen[i] != nil {
|
||||
glances[f.path] = seen[i]
|
||||
}
|
||||
}
|
||||
}
|
||||
put := map[string]*state{}
|
||||
for p := range pending {
|
||||
if cache[p] == nil && glances[p] != nil {
|
||||
put[p] = glances[p]
|
||||
}
|
||||
}
|
||||
for p, g := range put {
|
||||
cache[p], overlaid[p] = g, g
|
||||
}
|
||||
return pending, func() {
|
||||
for p, g := range put {
|
||||
if cache[p] == g {
|
||||
delete(cache, p)
|
||||
}
|
||||
delete(overlaid, p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// readBehind reads fs whole after the answer, as refresh does, and lets
|
||||
// their glances go once read.
|
||||
func readBehind(fs []file) {
|
||||
for _, f := range fs {
|
||||
behind[f.path] = true
|
||||
}
|
||||
behindRuns.Add(1)
|
||||
go func() {
|
||||
defer behindRuns.Done()
|
||||
storeMu.RLock()
|
||||
defer storeMu.RUnlock()
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
loadCache()
|
||||
refresh(fs, nil)
|
||||
for _, f := range fs {
|
||||
delete(behind, f.path)
|
||||
delete(glances, f.path)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// glanceAll glances at each of fs, a few at a time.
|
||||
func glanceAll(fs []file) []*state {
|
||||
out := make([]*state, len(fs))
|
||||
ch := make(chan int)
|
||||
var wg sync.WaitGroup
|
||||
for range min(max(runtime.NumCPU()/2, 1), len(fs)) {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := range ch {
|
||||
out[i] = glance(fs[i])
|
||||
}
|
||||
}()
|
||||
}
|
||||
for i := range fs {
|
||||
ch <- i
|
||||
}
|
||||
close(ch)
|
||||
wg.Wait()
|
||||
return out
|
||||
}
|
||||
|
||||
// glance is what f's first lines say of its session: its id, folder,
|
||||
// title and start, read with its agent's own parser, and none of what it
|
||||
// spent, which only a whole read can count. Its last activity is the
|
||||
// file's time.
|
||||
func glance(f file) *state {
|
||||
p := parserFor(f.agent)
|
||||
s := &state{}
|
||||
var head func([]byte) bool
|
||||
var thin func([]byte) (thinner, bool)
|
||||
switch {
|
||||
case p.claude:
|
||||
thin = thinClaude
|
||||
case f.agent == "codex":
|
||||
head = func(b []byte) bool { return codexHead(s, b, f.main) }
|
||||
thin = thinCodex
|
||||
}
|
||||
idIn := idInFile(f.agent)
|
||||
_, err := scanThin(f.path, 0, head, thin, func(b []byte, _, end int64) bool {
|
||||
p.line(s, b, f.main)
|
||||
if s.Cwd != "" && s.Title != "" && (!idIn || s.ID != "") {
|
||||
return false
|
||||
}
|
||||
return end < glanceBytes
|
||||
})
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
if p.claude && f.main {
|
||||
claudeTail(s, f)
|
||||
}
|
||||
if isBuddy(f.agent) && s.Cwd == "" {
|
||||
workbuddyMeta(s, f.path)
|
||||
}
|
||||
g := &state{Size: f.size, Mod: f.mod.UnixNano(), ID: s.ID, Cwd: s.Cwd, Title: s.Title, Named: s.Named,
|
||||
Custom: s.Custom, First: s.First, Start: s.Start, Last: f.mod, CodexIdentity: s.CodexIdentity,
|
||||
CodexNickname: s.CodexNickname, Provider: s.Provider}
|
||||
if g.Start.IsZero() || g.Start.After(g.Last) {
|
||||
g.Start = g.Last
|
||||
}
|
||||
return g
|
||||
}
|
||||
|
||||
// parsed is the parse kept of path: none for a glance put in the cache,
|
||||
// which a refresh reads whole as though nothing were kept.
|
||||
func parsed(path string) *state {
|
||||
s := cache[path]
|
||||
if s != nil && overlaid[path] == s {
|
||||
return nil
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// tailBytes is how much of a Claude Code file's end a glance reads for its
|
||||
// titles.
|
||||
const tailBytes = 64 << 10
|
||||
|
||||
// claudeTail reads the titles at the end of a Claude Code file into s: the
|
||||
// one Claude Code gives a session, and one the user gave it, are lines it
|
||||
// adds as the session goes on, the last of each the one that stands.
|
||||
func claudeTail(s *state, f file) {
|
||||
from := max(f.size-tailBytes, 0)
|
||||
p := parserFor(f.agent)
|
||||
scanThin(f.path, from, nil, nil, func(b []byte, start, _ int64) bool {
|
||||
if start == from && from > 0 {
|
||||
return true // the end of a line begun before
|
||||
}
|
||||
if bytes.Contains(b, ccTitle) || bytes.Contains(b, ccCustom) {
|
||||
p.line(s, b, true)
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
// savable is the cache as it is saved: without the glances put in it.
|
||||
func savable() map[string]*state {
|
||||
c := maps.Clone(cache)
|
||||
for p, g := range overlaid {
|
||||
if c[p] == g {
|
||||
delete(c, p)
|
||||
}
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// forgetBehind waits for the reads behind answers, and forgets the glances
|
||||
// (Reset).
|
||||
func forgetBehind() {
|
||||
behindRuns.Wait()
|
||||
mu.Lock()
|
||||
glances, overlaid, behind = map[string]*state{}, map[string]*state{}, map[string]bool{}
|
||||
mu.Unlock()
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package sessions
|
||||
|
||||
import (
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The Sessions page answers before a first read of its files (hey_boyce on
|
||||
// X: its placeholder rows stood for a long time on a first open). Its rows
|
||||
// come from a glance at each file's first lines, say they are pending, and
|
||||
// the whole read runs behind the answer; the next ask has their counts.
|
||||
func TestManageAnswersBeforeFirstReads(t *testing.T) {
|
||||
setup(t)
|
||||
old := quickBytes
|
||||
quickBytes = 0 // as a long history: every file over the bar
|
||||
release := make(chan struct{})
|
||||
var parses atomic.Int64
|
||||
parseHook = func() { parses.Add(1); <-release }
|
||||
opened := false
|
||||
open := func() {
|
||||
if !opened {
|
||||
opened = true
|
||||
close(release)
|
||||
}
|
||||
}
|
||||
t.Cleanup(func() { open(); behindRuns.Wait(); parseHook, quickBytes = nil, old })
|
||||
|
||||
claude := func([]AgentCount, map[string]map[string]bool) string { return "claude" }
|
||||
got := make(chan ManageView, 1)
|
||||
go func() { got <- Manage(map[string]bool{"codex": true, "claude": true}, claude) }()
|
||||
var v ManageView
|
||||
select {
|
||||
case v = <-got:
|
||||
case <-time.After(30 * time.Second): // a fail-safe: the old code never answers
|
||||
n := parses.Load()
|
||||
open()
|
||||
<-got // ended before the test's folder goes
|
||||
t.Fatalf("Manage waited for the whole read (%d files being read)", n)
|
||||
}
|
||||
if len(v.Sessions) < 2 {
|
||||
t.Fatalf("listed %d sessions before the read", len(v.Sessions))
|
||||
}
|
||||
for _, m := range v.Sessions {
|
||||
if !m.Pending {
|
||||
t.Fatalf("%s not pending, read whole before the answer", m.ID)
|
||||
}
|
||||
if m.Last.IsZero() {
|
||||
t.Fatalf("glanced row %+v has no time", m.Session)
|
||||
}
|
||||
if m.Input+m.Output != 0 {
|
||||
t.Fatalf("a glance counted tokens: %+v", m.Tokens)
|
||||
}
|
||||
}
|
||||
glanced := map[string]Managed{}
|
||||
for _, m := range v.Sessions {
|
||||
glanced[m.ID] = m
|
||||
}
|
||||
named := 0
|
||||
for _, m := range glanced {
|
||||
if m.Cwd != "" && m.Title != "" {
|
||||
named++
|
||||
}
|
||||
}
|
||||
if named == 0 {
|
||||
t.Fatalf("no glanced row has a folder and title: %+v", v.Sessions)
|
||||
}
|
||||
if !v.Native["codex"]["01a0bdc9-b5fd-7e63-9658-68bc8dce5ecd"] {
|
||||
t.Fatalf("codex ids from the glance: %v", v.Native["codex"])
|
||||
}
|
||||
// no glance stays in the cache, nor goes into a save
|
||||
mu.Lock()
|
||||
for _, m := range v.Sessions {
|
||||
if s := cache[m.Path]; s != nil {
|
||||
mu.Unlock()
|
||||
t.Fatalf("%s: a glance left in the cache", m.Path)
|
||||
}
|
||||
}
|
||||
if len(savable()) != 0 {
|
||||
mu.Unlock()
|
||||
t.Fatal("a glance would be saved")
|
||||
}
|
||||
mu.Unlock()
|
||||
|
||||
// asked again while the read is under way: still answered, still pending
|
||||
go func() { got <- Manage(map[string]bool{"codex": true}, claude) }()
|
||||
select {
|
||||
case v = <-got:
|
||||
case <-time.After(30 * time.Second):
|
||||
open()
|
||||
<-got
|
||||
t.Fatal("a second ask waited for the read under way")
|
||||
}
|
||||
if len(v.Sessions) == 0 || !v.Sessions[0].Pending {
|
||||
t.Fatalf("second ask: %+v", v.Sessions)
|
||||
}
|
||||
|
||||
open()
|
||||
behindRuns.Wait()
|
||||
v = Manage(map[string]bool{"codex": true}, claude)
|
||||
spent := false
|
||||
for _, m := range v.Sessions {
|
||||
if m.Pending {
|
||||
t.Fatalf("%s still pending after the read", m.ID)
|
||||
}
|
||||
spent = spent || m.Input+m.Output > 0 && m.Messages > 0
|
||||
// the glance showed what the whole read shows
|
||||
g, ok := glanced[m.ID]
|
||||
if !ok || g.Cwd != m.Cwd || g.Title != m.Title || g.Path != m.Path {
|
||||
t.Fatalf("glanced %q %q %q, read %q %q %q", g.ID, g.Cwd, g.Title, m.ID, m.Cwd, m.Title)
|
||||
}
|
||||
}
|
||||
if len(v.Sessions) != len(glanced) {
|
||||
t.Fatalf("%d glanced, %d read", len(glanced), len(v.Sessions))
|
||||
}
|
||||
if !spent {
|
||||
t.Fatalf("read whole and nothing counted: %+v", v.Sessions)
|
||||
}
|
||||
if !v.Native["codex"]["01a0bdc9-b5fd-7e63-9658-68bc8dce5ecd"] {
|
||||
t.Fatalf("codex ids after the read: %v", v.Native["codex"])
|
||||
}
|
||||
}
|
||||
@@ -978,7 +978,7 @@ func loadCache() {
|
||||
// row are folded into the latest, and one is written saveGap after the
|
||||
// last at the soonest.
|
||||
func saveCache() {
|
||||
snap := save{cacheFile{Version: cacheVersion, Zone: zone(), Files: maps.Clone(cache)}, CachePath()}
|
||||
snap := save{cacheFile{Version: cacheVersion, Zone: zone(), Files: savable()}, CachePath()}
|
||||
saving.Lock()
|
||||
defer saving.Unlock()
|
||||
saving.next = &snap
|
||||
@@ -1107,7 +1107,7 @@ func refresh(want, all []file) {
|
||||
if f.cold {
|
||||
continue // in a stopped WSL distro: what was read of it stands
|
||||
}
|
||||
if s := cache[f.path]; s == nil || s.Size != f.size || s.Mod != f.mod.UnixNano() || (f.agent == "hermes" && (f.m().hermes == nil || f.m().rev == "" || s.DBRevision != f.m().rev)) || ((f.agent == "alma" || f.agent == "cursor" || f.agent == "agy") && s.DBRevision != f.m().rev) {
|
||||
if s := parsed(f.path); s == nil || s.Size != f.size || s.Mod != f.mod.UnixNano() || (f.agent == "hermes" && (f.m().hermes == nil || f.m().rev == "" || s.DBRevision != f.m().rev)) || ((f.agent == "alma" || f.agent == "cursor" || f.agent == "agy") && s.DBRevision != f.m().rev) {
|
||||
if parsing[f.path] != nil {
|
||||
// a refresh is reading it, another or this one (a path
|
||||
// listed twice): its last parse stands until that one is
|
||||
@@ -1168,7 +1168,7 @@ func refresh(want, all []file) {
|
||||
}
|
||||
jobs := make([]job, len(todo))
|
||||
for i, f := range todo {
|
||||
jobs[i] = job{f: f, old: cache[f.path]}
|
||||
jobs[i] = job{f: f, old: parsed(f.path)}
|
||||
}
|
||||
generation := cacheGeneration
|
||||
mu.Unlock()
|
||||
@@ -1209,7 +1209,7 @@ func refresh(want, all []file) {
|
||||
publish := func(i int) {
|
||||
j := &jobs[i]
|
||||
// A concurrent read may already have published a newer parse.
|
||||
if generation == cacheGeneration && cache[j.f.path] == j.old {
|
||||
if generation == cacheGeneration && parsed(j.f.path) == j.old {
|
||||
cache[j.f.path] = j.parsed
|
||||
}
|
||||
close(parsing[j.f.path])
|
||||
@@ -1383,6 +1383,7 @@ func Reset() {
|
||||
wslReset()
|
||||
forgetHermesPrints()
|
||||
forgetAgySummaries()
|
||||
forgetBehind()
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
saved()
|
||||
|
||||
Reference in New Issue
Block a user