From 3eba174fd90eca4fe1622fa8e16bfa076281ac32 Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 20 Nov 2026 03:53:58 +0800 Subject: [PATCH] sessions: a restart no longer opens each Claude Code subagent's file again (shangyuan0818 on X) Every list built each session's subagents, and ccTask and ccMeta keep what they read in memory only. After a start, each of a few thousand subagent files was opened for its first user line (or its meta file), under Defender's per-open scan. The parse already read that file; its task and meta now stay in its state (StateMore Task, TaskRead, SubMeta) and the list uses them, falling back to ccTask/ccMeta when a parse has none. A subagent's parse made before this (no TaskRead) is read again once (ccStale), then not. Windows (xiaomi-gpu, Defender on, sandbox HOME, Claude-only reads), fixture of 12k files / 9.3 GB with 9k subagent files, three requests together: - warm restart: 2.2 s -> 1.0 s - restart after one session grew: 2.4 s -> 1.1 s - restart after one new session: 2.3 s -> 1.1 s - grow or new session while running: 0.55 s -> 0.4 s on the next list - cold, no cache: 21 s -> 15.8 s (the subagent read is no longer done twice) The plain 100-session fixture (6.6 GB) was 0.3 to 0.8 s warm before and stays there: it has no subagent files to open, and I did not reproduce "15 s after an agent used". The 5 s cold figure the reporter gives matches. Run: go test ./internal/sessions at this head (mote), gofmt, go vet for linux, windows and darwin. TestSubagentTaskAndMetaComeBackFromTheSavedParse is red on the old code (the list read the subagent's file once with its meta gone); TestSubagentParseWithoutItsTaskIsReadOnce guards the one-time reread. Not tried: a real Claude Code subagent's meta.json on Windows (the fixture has none, the meta path is covered by the test); the full suite and the GUI files are run after the push. A task past a subagent's 16th line is now found where ccTask gave none. --- internal/sessions/claude.go | 13 +++++- internal/sessions/sessions.go | 18 ++++++++- internal/sessions/subagent_task_test.go | 53 +++++++++++++++++++++++++ internal/sessions/subagents.go | 31 +++++++++++---- 4 files changed, 106 insertions(+), 9 deletions(-) diff --git a/internal/sessions/claude.go b/internal/sessions/claude.go index 35602ad34..2da976558 100644 --- a/internal/sessions/claude.go +++ b/internal/sessions/claude.go @@ -108,7 +108,7 @@ func claudeLine(s *state, b []byte, main bool) { ccLink(s, h, b, main) ccReply(s, at, msg, b, main) case bytes.HasPrefix(msg, ccRole) && typeAfter(msg, ccRole) == "user": - if main && !ccToolResult(msg) { + if (main || !s.more().TaskRead) && !ccToolResult(msg) { // a prompt, or something Claude Code put in: read whole claudeFull(s, b, main) return @@ -209,7 +209,13 @@ func ccRelocated(s *state, b []byte, main bool) { // magpie that didn't read /cd's relocated lines, and the folder it names is // not the project the file is in: the session was moved with /cd, and its // parse names the folder it left. Read again once, the parse is current. +// The same for a subagent's parse made before its task was kept. func ccStale(f file, s *state) bool { + if f.agent == "claude" && !f.main && s != nil && !s.more().TaskRead && SubagentOf(f.path) != "" { + // a subagent's parse from before its task and meta were kept with + // it: read again once, so a start no longer opens each of them + return true + } if f.agent != "claude" || !f.main || s == nil || s.CdRead || s.Cwd == "" { return false } @@ -366,6 +372,7 @@ func claudeFull(s *state, b []byte, main bool) { s.saw(at, main) want := bytes.Contains(b, ccAssistant) || main && bytes.Contains(b, ccUser) || + !main && !s.more().TaskRead && bytes.Contains(b, ccUser) || main && (bytes.Contains(b, ccTitle) || bytes.Contains(b, ccCustom) || bytes.Contains(b, ccSummary)) || s.Cwd == "" && bytes.Contains(b, ccCwd) if !want { @@ -408,6 +415,10 @@ func claudeFull(s *state, b []byte, main bool) { s.own().Named = title(l.Summary) } case "user": + if !main && !l.IsMeta && !s.more().TaskRead { + // the subagent's task, as ccTask reads it + s.own().Task, s.own().TaskRead = untagged(ccText(l.Message.Content)), true + } if main && !l.IsMeta && !l.IsSidechain { p := ccPrompt(l.Message.Content) if p != "" { diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go index 4d6ce8b1b..cac0162a8 100644 --- a/internal/sessions/sessions.go +++ b/internal/sessions/sessions.go @@ -275,6 +275,13 @@ type StateMore struct { Custom string `json:"custom,omitempty"` // the name the user gave it First string `json:"first,omitempty"` // the first message, when no prompt looked typed Convs []string `json:"convs,omitempty"` // the gateway's ids for its requests (dshConvs) + // Claude Code subagent: what it was asked (its first user line, as + // ccTask reads it), and the agent-.meta.json beside it. Kept with + // the file's state, so a restart opens neither again for each of + // thousands of subagent files (shangyuan0818 on X). + Task string `json:"task,omitempty"` + TaskRead bool `json:"task_read,omitempty"` + SubMeta *ccSubMeta `json:"sub_meta,omitempty"` // ResponseIDs are the ids of the replies its own requests got, as the // gateway wrote them on its routes and the agent kept them with the // reply (dsh's replay state): they name a request after the fact, where @@ -349,7 +356,7 @@ func moreOf(m StateMore) *StateMore { func (m *StateMore) zero() bool { return m == nil || m.DBRevision == "" && !m.CodexIdentityConflict && m.CodexNickname == "" && len(m.CodexSpawnNames) == 0 && len(m.CodexSpawnConflicts) == 0 && len(m.CodexAgentIDs) == 0 && - len(m.CodexAgentConflicts) == 0 && m.Named == "" && m.Custom == "" && m.First == "" && + len(m.CodexAgentConflicts) == 0 && m.Named == "" && m.Custom == "" && m.First == "" && m.Task == "" && !m.TaskRead && m.SubMeta == nil && len(m.Convs) == 0 && len(m.ResponseIDs) == 0 && len(m.SeedConvs) == 0 && len(m.TurnConvs) == 0 && m.Root == "" && m.Leaf == "" && len(m.Compacts) == 0 && m.Since.IsZero() && m.Grok == nil && m.Droid == nil && m.Kimi == nil && m.Agy == nil && m.Dsh == nil && m.Cline == nil @@ -2431,6 +2438,15 @@ func parseRead(f file, old *state, calls *callsRide) *state { if calls != nil { calls.finish(off, err) } + if parser.claude && !f.main && err == nil && SubagentOf(f.path) != "" { + // read: found or not, so the parse is not read again for it + s.own().TaskRead = true + if s.more().SubMeta == nil { + if m, ok := readCCMeta(f.path); ok { + s.own().SubMeta = &m + } + } + } if isBuddy(f.agent) && s.Cwd == "" { workbuddyMeta(s, f.path) } diff --git a/internal/sessions/subagent_task_test.go b/internal/sessions/subagent_task_test.go index 6b57e6a7d..60f3ec470 100644 --- a/internal/sessions/subagent_task_test.go +++ b/internal/sessions/subagent_task_test.go @@ -153,3 +153,56 @@ func TestSubagentWithMetaTaskIsNotReadForIt(t *testing.T) { t.Fatalf("subagents %+v", s.Subagents) } } + +// A restart does not open each Claude Code subagent's file or meta file +// again: its task and its meta come back from the saved parse, as the +// listing of a few thousand subagents did at every start (shangyuan0818 on X). +func TestSubagentTaskAndMetaComeBackFromTheSavedParse(t *testing.T) { + inZone(t, 0) + claude, _ := setup(t) + const sid = "11111111-2222-3333-4444-555555555555" + subs := filepath.Join(claude, "projects", "-work-app", sid, "subagents") + meta := filepath.Join(subs, "agent-a1.meta.json") + writeFile(t, meta, `{"agentType":"Explore","toolUseId":"toolu_01BZaaaaaaaaaaaaaaaaaaaa"}`) + sub := filepath.Join(subs, "agent-a1.jsonl") + writeFile(t, sub, ccHookLine(0)+ccTaskLine("Map the parser callers")) + List(0) + Saved() + // a restart: the parses come back from the disk, nothing else kept + Reset() + ccTasks.Clear() + ccMetas.Clear() + // and the meta file is not there to be read again + if err := os.Remove(meta); err != nil { + t.Fatal(err) + } + scans := scansOf(t, sub) + s := find(t, List(0), "claude", sid) + if n := scans(); n != 0 { + t.Fatalf("the list read a subagent's file %d times for a task the saved parse holds", n) + } + if len(s.Subagents) == 0 || s.Subagents[0].Kind != "Explore" || s.Subagents[0].Title != "Map the parser callers" { + t.Fatalf("subagents %+v", s.Subagents) + } +} + +// A subagent's parse made before its task was kept is read again once, and +// is not after that, whether or not its file names a task. +func TestSubagentParseWithoutItsTaskIsReadOnce(t *testing.T) { + inZone(t, 0) + claude, _ := setup(t) + const sid = "11111111-2222-3333-4444-555555555555" + sub := filepath.Join(claude, "projects", "-work-app", sid, "subagents", "agent-a1.jsonl") + writeFile(t, sub, ccHookLine(0)) + List(0) + f := file{agent: "claude", path: sub} + st := parsed(sub) + if st == nil || !st.more().TaskRead || ccStale(f, st) { + t.Fatalf("a parse of a subagent with no task is read again at each start: %+v", st) + } + old := *st + old.StateMore = nil // as a magpie before this kept it + if !ccStale(f, &old) { + t.Fatal("a subagent's parse made before its task was kept is not read again") + } +} diff --git a/internal/sessions/subagents.go b/internal/sessions/subagents.go index 56a6feabe..badbed54c 100644 --- a/internal/sessions/subagents.go +++ b/internal/sessions/subagents.go @@ -54,12 +54,19 @@ func subagentsOf(s Session, fs []file) []Subagent { if sa.ID == "" || strings.HasPrefix(sa.ID, "acompact-") { continue } - m := ccMeta(f.path) + var m ccSubMeta + if st.more().SubMeta != nil { + m = *st.more().SubMeta + } else { + m = ccMeta(f.path) + } sa.Kind, sa.Parent = m.AgentType, m.ParentAgentID // the file only when the meta names no task: cmp.Or read // every Claude Code subagent's file for a title it threw away if sa.Title = m.Description; sa.Title == "" { - sa.Title = ccTask(f.path) + if sa.Title = st.more().Task; sa.Title == "" { + sa.Title = ccTask(f.path) + } } case "opencode": sa.ID = f.m().sid @@ -122,19 +129,29 @@ func ccMeta(p string) ccSubMeta { if v, ok := ccMetas.Load(meta); ok { return v.(ccSubMeta) } - b, err := os.ReadFile(meta) - if err != nil { + m, ok := readCCMeta(p) + if !ok { return ccSubMeta{} } + ccMetas.Store(meta, m) + return m +} + +// readCCMeta reads the meta file beside the subagent file p; false when +// it isn't there or isn't JSON. +func readCCMeta(p string) (ccSubMeta, bool) { + b, err := os.ReadFile(strings.TrimSuffix(p, ".jsonl") + ".meta.json") + if err != nil { + return ccSubMeta{}, false + } var m ccSubMeta if json.Unmarshal(b, &m) != nil { - return ccSubMeta{} + return ccSubMeta{}, false } m.AgentType = m.AgentType[:min(len(m.AgentType), 128)] m.ParentAgentID = m.ParentAgentID[:min(len(m.ParentAgentID), 128)] m.Description = title(m.Description) - ccMetas.Store(meta, m) - return m + return m, true } var ccMetas sync.Map