sessions: a kept parse's rarely set fields live in a StateMore made only when one is set (#2278)

Each of the ~18k files the Sessions cache keeps had a 760-byte state, and
~330 bytes of it were fields almost no file sets: the Codex spawn and agent
maps, Named/Custom/First, the dsh and Claude conversation lists, Root/Leaf,
Compacts, and the six per-agent tails (Grok, Droid, Kimi, Agy, Dsh, Cline).
On the owner's real cache (18,331 files) Root and Leaf are set in 150,
Named in 117, Compacts in 78, First in 35. They move to an embedded
*StateMore, nil unless something is in it: reads go through more() (a
shared empty one when nil), writes through own(). The JSON is the same
(embedded fields are inlined), so the cache version stays.

- parseWith drops an extra that only had empty values written to it, and
  share() drops one the decode made empty.
- clone() deep-copies the extra, so growing a clone leaves the kept state
  alone. Copies that never write (withoutRevisions, the Agent rename)
  share it, as they shared the maps before.

Run on mote at this tree:
- gofmt -l internal/sessions: clean. go vet ./internal/sessions/ on
  darwin, GOOS=linux and GOOS=windows: ok.
- go test -count=1 ./internal/sessions/: ok (26s).
- Every selector was checked by renaming the embedding to a named field
  and compiling with -gcflags=-e until only the struct literals were left,
  so no field is reached through a nil *StateMore.
- New tests in state_more_test.go: zero() knows every field (reflect), a
  read makes no extra and a write never reaches the shared empty one, a
  clone owns its extra, and a cache round trip keeps no empty extra.
  Broken by hand: dropping Cline from zero() and sharing the extra in
  clone() each turn their test red; restored.
- Real-account idle heap (copy of the owner's config and 24.6MB sessions
  cache, gateway idle 180s, heap after GC): decodeCache's retained heap
  35.0MB -> 22.5MB, reflect.unsafe_New 20.0MB -> 10.5MB. The total
  (128.7MB -> 133.6MB) moves by more than that between runs of one binary
  (118-140MB), from late passes that happened to be live.

Not tried: the full ./... suite (state is unexported; only internal/sessions
uses it, and the whole binary builds).
This commit is contained in:
yetone
2026-11-09 18:08:28 +08:00
parent ff7d84b9b2
commit b8270850df
32 changed files with 413 additions and 238 deletions
+8 -8
View File
@@ -295,9 +295,9 @@ const agyModel = "agy"
// the file has only grown (agy appends a step at a time).
func parseAgy(f file, old *state) *state {
if agyRowOnly(f.path) {
s := &state{Size: f.size, Mod: f.mod.UnixNano(), DBRevision: f.m().rev}
s := &state{Size: f.size, Mod: f.mod.UnixNano(), StateMore: moreOf(StateMore{DBRevision: f.m().rev})}
if f.m().agy != nil {
s.Named, s.Cwd = title(f.m().agy.Title), f.m().agy.Cwd
s.own().Named, s.Cwd = title(f.m().agy.Title), f.m().agy.Cwd
// no transcript to read the prompt from: what the row lists
// it as until it has a title
s.Title = title(f.m().agy.Preview)
@@ -310,8 +310,8 @@ func parseAgy(f file, old *state) *state {
var s *state
c := agyCarry{Last: -1}
var off int64
if old != nil && old.Agy != nil && old.Agy.Tail.holds(f.path) {
s, c, off = old.clone(), *old.Agy, old.Agy.Tail.Off
if old != nil && old.more().Agy != nil && old.more().Agy.Tail.holds(f.path) {
s, c, off = old.clone(), *old.more().Agy, old.more().Agy.Tail.Off
steps := make(map[int]agyCounted, len(c.Steps))
for k, v := range c.Steps {
steps[k] = v
@@ -328,12 +328,12 @@ func parseAgy(f file, old *state) *state {
if err == nil {
c.Tail = markTail(f.path, end, 0, end)
}
s.Size, s.Mod, s.DBRevision = f.size, f.mod.UnixNano(), f.m().rev
s.Named, s.Cwd = "", ""
s.Size, s.Mod, s.own().DBRevision = f.size, f.mod.UnixNano(), f.m().rev
s.own().Named, s.Cwd = "", ""
if f.m().agy != nil {
s.Named, s.Cwd = title(f.m().agy.Title), f.m().agy.Cwd
s.own().Named, s.Cwd = title(f.m().agy.Title), f.m().agy.Cwd
}
s.Agy = &c
s.own().Agy = &c
return s
}
+2 -2
View File
@@ -232,7 +232,7 @@ func almaModel(model, providerID string) string {
// parseAlma reads one chat in a read transaction, a snapshot while Alma
// writes on.
func parseAlma(f file) *state {
s := &state{Size: f.size, Mod: f.mod.UnixNano(), DBRevision: f.m().rev}
s := &state{Size: f.size, Mod: f.mod.UnixNano(), StateMore: moreOf(StateMore{DBRevision: f.m().rev})}
st := f.m().alma
if st == nil {
return s
@@ -343,7 +343,7 @@ func parseAlma(f file) *state {
if s.Title == "" {
s.Title = first
}
s.First = first
s.own().First = first
for _, table := range []struct {
name string
+2 -2
View File
@@ -367,9 +367,9 @@ func parseAntigravity(f file) *state {
if err != nil {
return &state{}
}
s := &state{Size: f.size, Mod: f.mod.UnixNano(), DBRevision: f.m().rev}
s := &state{Size: f.size, Mod: f.mod.UnixNano(), StateMore: moreOf(StateMore{DBRevision: f.m().rev})}
if r := f.m().agy; r != nil {
s.Named, s.Title, s.Cwd = title(r.Title), title(r.Preview), r.Cwd
s.own().Named, s.Title, s.Cwd = title(r.Title), title(r.Preview), r.Cwd
}
for _, c := range calls {
s.saw(c.at, true)
+11 -1
View File
@@ -153,11 +153,21 @@ func encodeCache(w io.Writer, c cacheFile) error {
// history's 23.7k copies of one ~420-byte title, with its cwds and model
// names, were 11 of the 54 MB its kept parses held.
func (st *state) share() {
for _, s := range []*string{&st.Title, &st.Cwd, &st.First, &st.Named, &st.Model, &st.Provider, &st.MsgModel, &st.MsgDay, &st.CodexNickname} {
if st.StateMore.zero() {
st.StateMore = nil // an old cache's, or one Unmarshal made for an empty value
}
for _, s := range []*string{&st.Title, &st.Cwd, &st.Model, &st.Provider, &st.MsgModel, &st.MsgDay} {
if *s != "" {
*s = unique.Make(*s).Value()
}
}
if m := st.StateMore; m != nil {
for _, s := range []*string{&m.First, &m.Named, &m.CodexNickname} {
if *s != "" {
*s = unique.Make(*s).Value()
}
}
}
if id := st.CodexIdentity; id != nil {
for _, s := range []*string{&id.Role, &id.ParentSession, &id.RootSession} {
if *s != "" {
+8 -8
View File
@@ -73,14 +73,14 @@ func ccFamily(files []file) (copies, branches map[string]string) {
continue
}
st := cache[f.path]
if st == nil || st.Root == "" || st.Leaf == "" {
if st == nil || st.more().Root == "" || st.more().Leaf == "" {
continue
}
i := len(all)
all = append(all, ccOne{f, st})
up = append(up, i)
in := f.agent + "\x00" + f.m().wsl + "\x00"
for _, u := range append([]string{st.Root}, st.Compacts...) {
for _, u := range append([]string{st.more().Root}, st.more().Compacts...) {
if j, ok := at[in+u]; ok {
up[find(i)] = find(j)
} else {
@@ -109,7 +109,7 @@ func ccFamily(files []file) (copies, branches map[string]string) {
}
holds := func(b ccOne, uuid string) bool {
used[b.f.path] = true
return b.st.Leaf == uuid || ccUUIDsOf(*b.f)[uuid]
return b.st.more().Leaf == uuid || ccUUIDsOf(*b.f)[uuid]
}
// before reports whether b is kept over a: the one that holds
// the other's first message too (a copy made after a compaction
@@ -117,7 +117,7 @@ func ccFamily(files []file) (copies, branches map[string]string) {
// before), then the newer file, then the later key, so of two
// files that hold each other one stays
before := func(b, a ccOne) bool {
if ab, ba := holds(a, b.st.Root), holds(b, a.st.Root); ab != ba {
if ab, ba := holds(a, b.st.more().Root), holds(b, a.st.more().Root); ab != ba {
return ba
}
if c := b.f.mod.Compare(a.f.mod); c != 0 {
@@ -131,10 +131,10 @@ func ccFamily(files []file) (copies, branches map[string]string) {
// a file that holds what came before the other's start (a
// compaction the fork started after) is not that one's
// copy: the conversation's file a fork went on from
if i == j || a.f.key == b.f.key || !holds(b, a.st.Leaf) || !holds(b, a.st.Root) {
if i == j || a.f.key == b.f.key || !holds(b, a.st.more().Leaf) || !holds(b, a.st.more().Root) {
continue
}
if !holds(a, b.st.Leaf) || before(b, a) {
if !holds(a, b.st.more().Leaf) || before(b, a) {
hidden[i] = true
break
}
@@ -147,7 +147,7 @@ func ccFamily(files []file) (copies, branches map[string]string) {
// the file it is kept in: one that is not a copy itself and
// holds its last message, as the longest of them does
for j, b := range g {
if !hidden[j] && i != j && holds(b, a.st.Leaf) {
if !hidden[j] && i != j && holds(b, a.st.more().Leaf) {
if out == nil {
out = map[string]string{}
}
@@ -196,7 +196,7 @@ type ccOne struct {
// headFirst reports whether a, not b, is the conversation two files that
// went on apart are of (ccFamily).
func headFirst(a, b ccOne, holds func(ccOne, string) bool) bool {
if ab, ba := holds(a, b.st.Root), holds(b, a.st.Root); ab != ba {
if ab, ba := holds(a, b.st.more().Root), holds(b, a.st.more().Root); ab != ba {
return ab
}
ida, idb := strings.TrimPrefix(a.f.key, a.f.agent+":"), strings.TrimPrefix(b.f.key, b.f.agent+":")
+1 -1
View File
@@ -235,7 +235,7 @@ func TestClaudeCopyAfterCompactIsOneRow(t *testing.T) {
var compacts []string
for p, st := range cache {
if strings.HasSuffix(p, ccCompacted+".jsonl") {
compacts = st.Compacts
compacts = st.more().Compacts
}
}
mu.Unlock()
+11 -11
View File
@@ -144,10 +144,10 @@ func (s *state) link(uuid string) {
if !ccRandomUUID(uuid) {
return
}
if s.Root == "" {
s.Root = uuid
if s.more().Root == "" {
s.own().Root = uuid
}
s.Leaf = uuid
s.own().Leaf = uuid
}
// ccRandomUUID reports whether u is a version 4 uuid, as Claude Code's
@@ -388,23 +388,23 @@ func claudeFull(s *state, b []byte, main bool) {
}
if main && !l.IsSidechain && (l.Type == "user" || l.Type == "assistant") {
s.link(l.UUID)
if l.IsCompactSummary && l.Type == "user" && ccRandomUUID(l.UUID) && !slices.Contains(s.Compacts, l.UUID) {
s.Compacts = append(s.Compacts, l.UUID)
if l.IsCompactSummary && l.Type == "user" && ccRandomUUID(l.UUID) && !slices.Contains(s.more().Compacts, l.UUID) {
s.own().Compacts = append(s.more().Compacts, l.UUID)
}
}
switch l.Type {
case "ai-title":
if l.AITitle != "" {
s.Named = title(l.AITitle)
s.own().Named = title(l.AITitle)
}
case "custom-title":
// named by the user (/rename): before the one Claude Code made
if main && l.CustomTitle != "" {
s.Custom = title(l.CustomTitle)
s.own().Custom = title(l.CustomTitle)
}
case "summary":
if l.Summary != "" && s.Named == "" {
s.Named = title(l.Summary)
if l.Summary != "" && s.more().Named == "" {
s.own().Named = title(l.Summary)
}
case "user":
if main && !l.IsMeta && !l.IsSidechain {
@@ -414,8 +414,8 @@ func claudeFull(s *state, b []byte, main bool) {
}
if s.Title == "" {
s.Title = p
if s.Title == "" && s.First == "" {
s.First = untagged(ccText(l.Message.Content))
if s.Title == "" && s.more().First == "" {
s.own().First = untagged(ccText(l.Message.Content))
}
}
}
+2 -2
View File
@@ -55,7 +55,7 @@ func TestHistoricalClaudeFilesDoNotDisplaceActiveWindows(t *testing.T) {
if cache[path].revisionWeight() == 0 {
t.Fatal("history displaced active summary", path)
}
cache[path].Named = "incremental marker"
cache[path].own().Named = "incremental marker"
st, err := os.Stat(callCachePath(path))
if err != nil {
t.Fatal(err)
@@ -67,7 +67,7 @@ func TestHistoricalClaudeFilesDoNotDisplaceActiveWindows(t *testing.T) {
appendText(t, codex, tokenCountLine(i+2, cxUse(100*(i+2), 0, 0, i+2, 0), cxUse(100, 0, 0, 1, 0))+"\n")
read()
for _, path := range []string{claude, codex} {
if cache[path].Named != "incremental marker" {
if cache[path].more().Named != "incremental marker" {
t.Fatal("reparsed active summary", path)
}
st, err := os.Stat(callCachePath(path))
+2 -2
View File
@@ -87,7 +87,7 @@ func TestClaudeLargeWindowSurvivesIdleAndSmallFiles(t *testing.T) {
t.Fatal(err)
}
snapshot := cache[path]
snapshot.Named = "must resume this summary"
snapshot.own().Named = "must resume this summary"
// Cross the old hard cutoff without sleeping. The cutoff used source
// mtime, so advancing only the eviction clock reproduces idle expiry.
later := time.Now().Add(2 * revisionIdle)
@@ -118,7 +118,7 @@ func TestClaudeLargeWindowSurvivesIdleAndSmallFiles(t *testing.T) {
}
appendText(t, path, string(claudeUsageLine(at.Add(time.Hour), "new", "", "m", Tokens{Input: 1, Output: 2}, "", true))+"\n")
read()
if cache[path].Named != "must resume this summary" {
if cache[path].more().Named != "must resume this summary" {
t.Fatal("summary reparsed the large prefix")
}
if got := cache[path].Models.of("m"); got != (Tokens{Input: 4001, Output: 8002}) {
+4 -4
View File
@@ -59,13 +59,13 @@ func TestLargeClaudeFileKeepsAppendContinuation(t *testing.T) {
}
// A cold reparse cannot preserve this in-memory marker. This proves List
// clones its old summary and resumes at Off instead of replaying the prefix.
cache[path].Named = "append continuation marker"
cache[path].own().Named = "append continuation marker"
old := cache[path].Claude.clone()
for i := 0; i < 3; i++ {
line := string(claudeUsageLine(at.Add(time.Duration(count+i)*time.Second), fmt.Sprint(count+i), "", "m", Tokens{Input: 1, Output: 2}, "", true))
appendText(t, path, line+"\n")
check(count + i + 1)
if cache[path].Named != "append continuation marker" {
if cache[path].more().Named != "append continuation marker" {
t.Fatal("summary reparsed the prefix")
}
after, err := os.Stat(callCachePath(path))
@@ -279,7 +279,7 @@ func TestClaudeSummaryReadOnAfterRestart(t *testing.T) {
// after the restart went on from the kept parse
mu.Lock()
marked := *cache[path]
marked.Named = "read on marker"
marked.own().Named = "read on marker"
cache[path] = &marked
saveCache()
mu.Unlock()
@@ -287,7 +287,7 @@ func TestClaudeSummaryReadOnAfterRestart(t *testing.T) {
appendText(t, path, line(count, "2990", 9)+"\n"+lines[count-1]+"\n"+line(count+1, "new", 2)+"\n")
got := List(0)
mu.Lock()
named := cache[path].Named
named := cache[path].more().Named
mu.Unlock()
if named != "read on marker" {
t.Fatal("the grown file was parsed again from its start")
+8 -8
View File
@@ -133,10 +133,10 @@ func parseCline(f file, old *state) *state {
}
name := func(s *state, prompt string) *state {
s.Size, s.Mod = f.size, f.mod.UnixNano()
s.ID, s.Cwd, s.Named, s.Title, s.First = "", "", "", "", ""
s.ID, s.Cwd, s.own().Named, s.Title, s.own().First = "", "", "", "", ""
if hasM {
s.ID, s.Cwd = m.SessionID, m.Cwd
s.Named = title(m.Metadata.Title)
s.own().Named = title(m.Metadata.Title)
clineTitle(s, m.Prompt)
}
if f.main {
@@ -148,9 +148,9 @@ func parseCline(f file, old *state) *state {
if err != nil {
return name(&state{}, "")
}
if o := old; o != nil && o.Cline != nil && o.Cline.Size == fi.Size() && o.Cline.Mod == fi.ModTime().UnixNano() && o.Cline.Since.Equal(since) && o.Cline.Start.Equal(start) {
if o := old; o != nil && o.more().Cline != nil && o.more().Cline.Size == fi.Size() && o.more().Cline.Mod == fi.ModTime().UnixNano() && o.more().Cline.Since.Equal(since) && o.more().Cline.Start.Equal(start) {
s := o.clone()
return name(s, o.Cline.Prompt) // the title its messages gave, when the manifest gives none
return name(s, o.more().Cline.Prompt) // the title its messages gave, when the manifest gives none
}
s := &state{}
@@ -176,7 +176,7 @@ func parseCline(f file, old *state) *state {
// the first prompt that names the session by itself
var t state
text := ccText(m.Content)
if clineTitle(&t, text); t.Title != "" || t.First != "" {
if clineTitle(&t, text); t.Title != "" || t.more().First != "" {
c.Prompt, named = text, true
}
}
@@ -194,7 +194,7 @@ func parseCline(f file, old *state) *state {
s.use(dateOf(at), m.ModelInfo.ID, Tokens{Input: max(0, u.Input-u.CacheRead-u.CacheWrite), Output: u.Output, CacheRead: u.CacheRead, CacheWrite: u.CacheWrite})
}
}
s.Cline = c
s.own().Cline = c
return name(s, c.Prompt)
}
@@ -241,12 +241,12 @@ var (
// clineTitle takes a session's title from a prompt: the words typed, out of
// the tags Cline wraps them in (<user_input mode="act">) and its notices.
func clineTitle(s *state, prompt string) {
if s.Title != "" || s.First != "" {
if s.Title != "" || s.more().First != "" {
return
}
t := strings.TrimSpace(clineInput.ReplaceAllString(clineNotice.ReplaceAllString(prompt, " "), " "))
if strings.HasPrefix(t, "<") {
s.First = untagged(t)
s.own().First = untagged(t)
} else {
s.Title = title(t)
}
+28 -28
View File
@@ -335,17 +335,17 @@ func mergeCodexIdentity(old, next CodexIdentity) (CodexIdentity, bool) {
func noteCodexIdentity(s *state, identity CodexIdentity, conflict bool) {
if s.CodexIdentity == nil {
copy := identity
s.CodexIdentity, s.CodexIdentityConflict = &copy, conflict
s.CodexIdentity, s.own().CodexIdentityConflict = &copy, conflict
return
}
if s.CodexIdentityConflict {
if s.more().CodexIdentityConflict {
return
}
old := *s.CodexIdentity
merged, conflictFound := mergeCodexIdentity(old, identity)
if conflict || conflictFound {
s.CodexIdentity = &CodexIdentity{ID: old.ID, Role: codexRoleUnknown}
s.CodexIdentityConflict = true
s.own().CodexIdentityConflict = true
return
}
s.CodexIdentity = &merged
@@ -401,7 +401,7 @@ func codexSubagentTaskTitles(files []file) map[codexTaskTitle]string {
st := cache[f.path]
// most threads spawn no agent: four maps for each of them on every
// poll were ~140 MB in 80s of polls over ~34k sessions (#2278)
if len(st.CodexSpawnConflicts) == 0 && len(st.CodexAgentConflicts) == 0 && len(st.CodexSpawnNames) == 0 && len(st.CodexAgentIDs) == 0 {
if len(st.more().CodexSpawnConflicts) == 0 && len(st.more().CodexAgentConflicts) == 0 && len(st.more().CodexSpawnNames) == 0 && len(st.more().CodexAgentIDs) == 0 {
continue
}
calls := parents[f.key]
@@ -409,19 +409,19 @@ func codexSubagentTaskTitles(files []file) map[codexTaskTitle]string {
calls = &parentCalls{names: map[string]string{}, children: map[string]string{}, badNames: map[string]bool{}, badChildren: map[string]bool{}}
parents[f.key] = calls
}
for id := range st.CodexSpawnConflicts {
for id := range st.more().CodexSpawnConflicts {
calls.badNames[id] = true
}
for id := range st.CodexAgentConflicts {
for id := range st.more().CodexAgentConflicts {
calls.badChildren[id] = true
}
for id, name := range st.CodexSpawnNames {
for id, name := range st.more().CodexSpawnNames {
if old := calls.names[id]; old != "" && old != name {
calls.badNames[id] = true
}
calls.names[id] = name
}
for id, child := range st.CodexAgentIDs {
for id, child := range st.more().CodexAgentIDs {
if old := calls.children[id]; old != "" && old != child {
calls.badChildren[id] = true
}
@@ -457,7 +457,7 @@ func codexTaskParentFiles(children, all []file) []file {
continue
}
st := cache[f.path]
if st != nil && !st.CodexIdentityConflict && st.CodexIdentity != nil && st.CodexIdentity.Role == codexRoleSubagent && st.CodexIdentity.ParentSession != "" {
if st != nil && !st.more().CodexIdentityConflict && st.CodexIdentity != nil && st.CodexIdentity.Role == codexRoleSubagent && st.CodexIdentity.ParentSession != "" {
parents[st.CodexIdentity.ParentSession] = true
}
}
@@ -475,16 +475,16 @@ func (s *state) codexAgentStarted(id, thread string) {
if id == "" || thread == "" {
return
}
if s.CodexAgentIDs == nil {
s.CodexAgentIDs = map[string]string{}
if s.more().CodexAgentIDs == nil {
s.own().CodexAgentIDs = map[string]string{}
}
if old, ok := s.CodexAgentIDs[id]; ok && old != thread {
if s.CodexAgentConflicts == nil {
s.CodexAgentConflicts = map[string]bool{}
if old, ok := s.more().CodexAgentIDs[id]; ok && old != thread {
if s.more().CodexAgentConflicts == nil {
s.own().CodexAgentConflicts = map[string]bool{}
}
s.CodexAgentConflicts[id] = true
s.own().CodexAgentConflicts[id] = true
} else {
s.CodexAgentIDs[id] = thread
s.own().CodexAgentIDs[id] = thread
}
}
@@ -528,7 +528,7 @@ type codexIdentityFrom struct {
func codexIdentityFromOf(f file) codexIdentityFrom {
from := codexIdentityFrom{key: f.key}
if s := cache[f.path]; s != nil && s.CodexIdentity != nil {
from.identity, from.known, from.conflict = *s.CodexIdentity, true, s.CodexIdentityConflict
from.identity, from.known, from.conflict = *s.CodexIdentity, true, s.more().CodexIdentityConflict
}
return from
}
@@ -588,7 +588,7 @@ func codexIdentitiesBuilt(files []file) map[string]CodexIdentity {
conflict := false
if s := cache[f.path]; s != nil && s.CodexIdentity != nil {
identity = *s.CodexIdentity
conflict = s.CodexIdentityConflict
conflict = s.more().CodexIdentityConflict
if identity.ID == "" {
identity.ID = id
}
@@ -737,21 +737,21 @@ func codexBody(s *state, b []byte, main bool) {
s.Cwd = p.Cwd
}
if p.AgentNickname != "" {
s.CodexNickname = p.AgentNickname
s.own().CodexNickname = p.AgentNickname
}
case l.Type == "response_item" && p.Type == "function_call" && p.Name == "spawn_agent":
if p.CallID != "" {
if name := title(gjson.Get(p.Arguments, "task_name").String()); name != "" {
if s.CodexSpawnNames == nil {
s.CodexSpawnNames = map[string]string{}
if s.more().CodexSpawnNames == nil {
s.own().CodexSpawnNames = map[string]string{}
}
if old, ok := s.CodexSpawnNames[p.CallID]; ok && old != name {
if s.CodexSpawnConflicts == nil {
s.CodexSpawnConflicts = map[string]bool{}
if old, ok := s.more().CodexSpawnNames[p.CallID]; ok && old != name {
if s.more().CodexSpawnConflicts == nil {
s.own().CodexSpawnConflicts = map[string]bool{}
}
s.CodexSpawnConflicts[p.CallID] = true
s.own().CodexSpawnConflicts[p.CallID] = true
} else {
s.CodexSpawnNames[p.CallID] = name
s.own().CodexSpawnNames[p.CallID] = name
}
}
}
@@ -781,8 +781,8 @@ func codexBody(s *state, b []byte, main bool) {
if s.Title == "" {
s.Title = cxPrompt(p.Message)
}
if s.Title == "" && s.First == "" {
s.First = untagged(p.Message)
if s.Title == "" && s.more().First == "" {
s.own().First = untagged(p.Message)
}
case l.Type == "response_item" && p.Type == "message" && p.Role == "user":
typed := false
@@ -228,7 +228,7 @@ func TestCodexSubagentNicknameInvalidatesOldParseCache(t *testing.T) {
codexDetailsUsage(t, "child", 1),
)
writeCache(&save{cacheFile: cacheFile{Version: cacheVersion - 1, Zone: zone(), Files: map[string]*state{path: {
ID: "child", CodexNickname: "stale nickname", Size: 1, Mod: 1,
ID: "child", StateMore: &StateMore{CodexNickname: "stale nickname"}, Size: 1, Mod: 1,
}}}, path: CachePath()})
Reset()
if got := codexDetailsSession(t, "child"); got.Nickname != "Fresh nickname" {
+5 -5
View File
@@ -441,7 +441,7 @@ func parseCursor(f file) *state {
if m, ok := readCursorMetaFile(dir); ok {
s.Cwd = m.Cwd
if f.main {
s.Named = cursorTitle(m.Title)
s.own().Named = cursorTitle(m.Title)
}
s.saw(ms(m.Created), f.main)
if u := ms(m.Updated); !u.IsZero() {
@@ -460,8 +460,8 @@ func parseCursor(f file) *state {
return s
}
s.ID = filepath.Base(dir)
if s.Named == "" && f.main {
s.Named = cursorTitle(meta.Name)
if s.more().Named == "" && f.main {
s.own().Named = cursorTitle(meta.Name)
}
s.saw(ms(meta.CreatedAt), f.main)
s.saw(cursorStarted(db, meta.Root), f.main)
@@ -475,8 +475,8 @@ func parseCursor(f file) *state {
case "user":
typed, other := cursorTyped(parts)
if typed == "" {
if f.main && s.Title == "" && s.First == "" && other != "" {
s.First = untagged(other)
if f.main && s.Title == "" && s.more().First == "" && other != "" {
s.own().First = untagged(other)
}
continue
}
+3 -3
View File
@@ -170,9 +170,9 @@ func cursorEditorHasMessages(path string) bool {
}
func parseCursorEditor(f file) *state {
s := &state{ID: f.m().sid, Size: f.size, Mod: f.mod.UnixNano(), DBRevision: f.m().rev}
s := &state{ID: f.m().sid, Size: f.size, Mod: f.mod.UnixNano(), StateMore: moreOf(StateMore{DBRevision: f.m().rev})}
if m := f.m().editor; m != nil {
s.Named = cursorTitle(m.Name)
s.own().Named = cursorTitle(m.Name)
s.Cwd = m.Workspace.URI.Path
s.saw(ms(m.Created), false)
s.saw(ms(m.Updated), false)
@@ -206,7 +206,7 @@ func parseCursorEditor(f file) *state {
if len(s.Days) == 0 {
// A failed transcript export may contain only an error record,
// while the editor metadata still has a name for the empty chat.
s.Named = ""
s.own().Named = ""
}
return s
}
+8 -8
View File
@@ -244,8 +244,8 @@ func parseDroid(f file, old *state) *state {
var s *state
var c droidCarry
var off int64
if old != nil && old.Droid != nil && old.Droid.Tail.holds(f.path) {
s, c, off = old.clone(), *old.Droid, old.Droid.Tail.Off
if old != nil && old.more().Droid != nil && old.more().Droid.Tail.holds(f.path) {
s, c, off = old.clone(), *old.more().Droid, old.more().Droid.Tail.Off
s.dropUse(c.Date, c.Model, c.Tokens)
} else {
s = &state{}
@@ -273,7 +273,7 @@ func parseDroid(f file, old *state) *state {
s.use(c.Date, c.Model, c.Tokens)
}
}
s.Droid = &c
s.own().Droid = &c
return s
}
@@ -287,9 +287,9 @@ func droidLineOf(s *state, c *droidCarry, b []byte, main bool) {
c.Started = true
var st droidStart
if l.Type == "session_start" && json.Unmarshal(b, &st) == nil {
s.ID, s.Cwd, s.Named = st.ID, st.Cwd, title(st.Title)
if s.Named == "New Session" {
s.Named = "" // Droid's until it names one
s.ID, s.Cwd, s.own().Named = st.ID, st.Cwd, title(st.Title)
if s.more().Named == "New Session" {
s.own().Named = "" // Droid's until it names one
}
if st.LastCwd != "" {
s.Cwd = st.LastCwd
@@ -320,8 +320,8 @@ func droidLineOf(s *state, c *droidCarry, b []byte, main bool) {
return
}
if strings.HasPrefix(strings.TrimSpace(text), "<") {
if s.First == "" {
s.First = untagged(text)
if s.more().First == "" {
s.own().First = untagged(text)
}
return
}
+16 -15
View File
@@ -286,8 +286,8 @@ func parseDsh(f file, old *state) *state {
var s *state
var c dshCarry
var off, skip int64
if old != nil && old.Dsh != nil && old.Dsh.Tail.holds(f.path) {
s, c = old.clone(), *old.Dsh
if old != nil && old.more().Dsh != nil && old.more().Dsh.Tail.holds(f.path) {
s, c = old.clone(), *old.more().Dsh
off, skip = c.Tail.Off, c.Tail.Skip
} else {
s = &state{}
@@ -329,7 +329,7 @@ func parseDsh(f file, old *state) *state {
if err == nil {
c.Tail = markTail(f.path, next, nextSkip, end)
}
s.Dsh = &c
s.own().Dsh = &c
return s
}
@@ -351,10 +351,10 @@ func dshCount(s *state, h *dshHead, b []byte, main bool) {
}
switch e.Type {
case "user/message":
if main && s.Title == "" && s.First == "" && e.Data.Source.Kind == "user" {
s.Convs = append(s.Convs, dshConvs(e.Data.Content)...)
if main && s.Title == "" && s.more().First == "" && e.Data.Source.Kind == "user" {
s.own().Convs = append(s.more().Convs, dshConvs(e.Data.Content)...)
if t := ccText(e.Data.Content); strings.HasPrefix(t, "<") {
s.First = untagged(t)
s.own().First = untagged(t)
} else {
s.Title = title(t)
}
@@ -367,25 +367,25 @@ func dshCount(s *state, h *dshHead, b []byte, main bool) {
// way (dshLastConvs); a file with no turn/start keeps its
// newest few
if c := dshConvs(e.Data.Content); len(c) > 0 {
s.TurnConvs = append(s.TurnConvs, c[0])
if n := len(s.TurnConvs); n > dshTurnKept {
s.TurnConvs = slices.Clone(s.TurnConvs[n-dshTurnKept:])
s.own().TurnConvs = append(s.more().TurnConvs, c[0])
if n := len(s.more().TurnConvs); n > dshTurnKept {
s.own().TurnConvs = slices.Clone(s.more().TurnConvs[n-dshTurnKept:])
}
}
}
case "turn/start":
if main {
s.TurnConvs = nil
s.own().TurnConvs = nil
}
case "session/title":
if t := title(e.Data.Title); t != "" {
s.Named = t
s.own().Named = t
}
case "session/title-llm-request":
if main {
for _, m := range e.Data.Messages {
if m.Role == "user" {
s.Convs = append(s.Convs, dshConvs(m.Content)...)
s.own().Convs = append(s.more().Convs, dshConvs(m.Content)...)
break
}
}
@@ -397,8 +397,9 @@ func dshCount(s *state, h *dshHead, b []byte, main bool) {
// kept: dsh writes no parentSession for a fork, so the
// openings its seed carried are all that says the fork
// came from them (SeedConvs)
n := &state{ID: s.ID, Cwd: s.Cwd, Title: s.Title, First: s.First, Named: s.Named, Size: s.Size, Mod: s.Mod,
SeedConvs: append(append([]string(nil), s.SeedConvs...), s.Convs...)}
n := &state{ID: s.ID, Cwd: s.Cwd, Title: s.Title, Size: s.Size, Mod: s.Mod,
StateMore: moreOf(StateMore{First: s.more().First, Named: s.more().Named,
SeedConvs: append(append([]string(nil), s.more().SeedConvs...), s.more().Convs...)})}
n.saw(ms(h.CreatedAt), main)
*s = *n
return
@@ -410,7 +411,7 @@ func dshCount(s *state, h *dshHead, b []byte, main bool) {
if e.Type == "assistant/message" && main {
if src := e.Data.Message.Source; dshGatewayProvider(src) {
if id := src.ReplayState.Response.ResponseID; id != "" {
s.ResponseIDs = append(s.ResponseIDs, id)
s.own().ResponseIDs = append(s.more().ResponseIDs, id)
}
}
}
+18 -18
View File
@@ -44,8 +44,8 @@ func TestDshResponseIDsSkipTheSeed(t *testing.T) {
dshReplyWithID(4, "own-1"),
dshReplyWithID(5, "own-2"),
})
if want := []string{"own-1", "own-2"}; !slices.Equal(s.ResponseIDs, want) {
t.Fatalf("fork's own replies: %v, want %v", s.ResponseIDs, want)
if want := []string{"own-1", "own-2"}; !slices.Equal(s.more().ResponseIDs, want) {
t.Fatalf("fork's own replies: %v, want %v", s.more().ResponseIDs, want)
}
}
@@ -59,8 +59,8 @@ func TestDshResponseIDsSkipTheSeedLength(t *testing.T) {
dshReplyWithID(1, "inherited-2"),
dshReplyWithID(2, "own"),
})
if want := []string{"own"}; !slices.Equal(s.ResponseIDs, want) {
t.Fatalf("fork's own replies: %v, want %v", s.ResponseIDs, want)
if want := []string{"own"}; !slices.Equal(s.more().ResponseIDs, want) {
t.Fatalf("fork's own replies: %v, want %v", s.more().ResponseIDs, want)
}
}
@@ -72,8 +72,8 @@ func TestDshResponseIDsOfASession(t *testing.T) {
dshReplyWithID(1, "a"),
dshReplyWithID(2, "b"),
})
if want := []string{"a", "b"}; !slices.Equal(s.ResponseIDs, want) {
t.Fatalf("replies: %v, want %v", s.ResponseIDs, want)
if want := []string{"a", "b"}; !slices.Equal(s.more().ResponseIDs, want) {
t.Fatalf("replies: %v, want %v", s.more().ResponseIDs, want)
}
}
@@ -86,8 +86,8 @@ func TestDshResponseIDsOnlyFromTheGateway(t *testing.T) {
`{"type":"assistant/message","seq":1,"time":1000,"data":{"message":{"source":{"provider":"deepseek","model":"deepseek-v4","replayState":{"response":{"provider":"deepseek","responseId":"vendor-1"}}}}}}`,
dshReplyWithID(2, "gw-1"),
})
if want := []string{"gw-1"}; !slices.Equal(s.ResponseIDs, want) {
t.Fatalf("replies: %v, want %v", s.ResponseIDs, want)
if want := []string{"gw-1"}; !slices.Equal(s.more().ResponseIDs, want) {
t.Fatalf("replies: %v, want %v", s.more().ResponseIDs, want)
}
}
@@ -119,13 +119,13 @@ func TestDshResponseIDsEndSeedAcrossReads(t *testing.T) {
}
write(head, dshReplyWithID(1, "inherited"))
first := parseDsh(f(), nil)
if len(first.ResponseIDs) != 1 {
t.Fatalf("before the marker: %v", first.ResponseIDs)
if len(first.more().ResponseIDs) != 1 {
t.Fatalf("before the marker: %v", first.more().ResponseIDs)
}
write(`{"type":"session/end-seed","seq":2,"time":1000,"data":{"inherited":true}}`, dshReplyWithID(3, "own"))
next := parseDsh(f(), first)
if want := []string{"own"}; !slices.Equal(next.ResponseIDs, want) {
t.Fatalf("after the marker: %v, want %v", next.ResponseIDs, want)
if want := []string{"own"}; !slices.Equal(next.more().ResponseIDs, want) {
t.Fatalf("after the marker: %v, want %v", next.more().ResponseIDs, want)
}
}
@@ -204,13 +204,13 @@ func TestDshForkWithoutAParentKeepsItsSeedOpenings(t *testing.T) {
if len(want) == 0 {
t.Fatal("the fixture opens no conversation")
}
if !slices.Equal(s.SeedConvs, want) {
t.Fatalf("seed openings %v, want %v", s.SeedConvs, want)
if !slices.Equal(s.more().SeedConvs, want) {
t.Fatalf("seed openings %v, want %v", s.more().SeedConvs, want)
}
if len(s.Convs) != 0 {
t.Fatalf("the fork keeps its source's opening as its own: %v", s.Convs)
if len(s.more().Convs) != 0 {
t.Fatalf("the fork keeps its source's opening as its own: %v", s.more().Convs)
}
if !slices.Equal(s.ResponseIDs, []string{"own"}) {
t.Fatalf("replies %v, want [own]", s.ResponseIDs)
if !slices.Equal(s.more().ResponseIDs, []string{"own"}) {
t.Fatalf("replies %v, want [own]", s.more().ResponseIDs)
}
}
+6 -6
View File
@@ -33,8 +33,8 @@ func TestDshTurnConvsAreTheNewestTurns(t *testing.T) {
dshUserTurn(4, "second"),
dshUserTurn(5, "context"),
})
if want := []string{dshTurnID("second"), dshTurnID("context")}; !slices.Equal(s.TurnConvs, want) {
t.Fatalf("newest turn's messages %v, want %v", s.TurnConvs, want)
if want := []string{dshTurnID("second"), dshTurnID("context")}; !slices.Equal(s.more().TurnConvs, want) {
t.Fatalf("newest turn's messages %v, want %v", s.more().TurnConvs, want)
}
}
@@ -50,8 +50,8 @@ func TestDshTurnConvsSkipTheSeed(t *testing.T) {
dshTurnStart(4, 2),
dshUserTurn(5, "own"),
})
if want := []string{dshTurnID("own")}; !slices.Equal(s.TurnConvs, want) {
t.Fatalf("fork's newest turn %v, want %v", s.TurnConvs, want)
if want := []string{dshTurnID("own")}; !slices.Equal(s.more().TurnConvs, want) {
t.Fatalf("fork's newest turn %v, want %v", s.more().TurnConvs, want)
}
}
@@ -66,7 +66,7 @@ func TestDshTurnConvsKeepTheNewestFew(t *testing.T) {
want = append(want, dshTurnID(text))
}
s := dshSessionFile(t, lines)
if want = want[len(want)-dshTurnKept:]; !slices.Equal(s.TurnConvs, want) {
t.Fatalf("turn messages %v, want the newest %d %v", s.TurnConvs, dshTurnKept, want)
if want = want[len(want)-dshTurnKept:]; !slices.Equal(s.more().TurnConvs, want) {
t.Fatalf("turn messages %v, want the newest %d %v", s.more().TurnConvs, dshTurnKept, want)
}
}
+8 -8
View File
@@ -214,8 +214,8 @@ func parseGrok(f file, old *state) *state {
}
var s *state
var off int64
if o := old; o != nil && o.Grok != nil && o.Grok.Model == c.Model && o.Grok.Created.Equal(c.Created) && o.Grok.Since.Equal(c.Since) && o.Grok.Tail.holds(f.path) {
s, c, off = o.clone(), *o.Grok, o.Grok.Tail.Off
if o := old; o != nil && o.more().Grok != nil && o.more().Grok.Model == c.Model && o.more().Grok.Created.Equal(c.Created) && o.more().Grok.Since.Equal(c.Since) && o.more().Grok.Tail.holds(f.path) {
s, c, off = o.clone(), *o.more().Grok, o.more().Grok.Tail.Off
} else {
s = &state{}
if hasM {
@@ -223,9 +223,9 @@ func parseGrok(f file, old *state) *state {
}
}
s.Size, s.Mod = f.size, f.mod.UnixNano()
s.ID, s.Cwd, s.Named = m.Info.ID, m.Info.Cwd, title(m.GeneratedTitle)
if s.Named == "" {
s.Named = title(m.SessionSummary)
s.ID, s.Cwd, s.own().Named = m.Info.ID, m.Info.Cwd, title(m.GeneratedTitle)
if s.more().Named == "" {
s.own().Named = title(m.SessionSummary)
}
end, err := scanAt(f.path, off, nil, func(b []byte, _, _ int64) bool {
grokUpdate(s, &c, b, f.main)
@@ -239,11 +239,11 @@ func parseGrok(f file, old *state) *state {
if c.InPrompt {
t = title(c.Prompt)
}
s.Title, s.First = t, ""
s.Title, s.own().First = t, ""
if strings.HasPrefix(t, "<") {
s.Title, s.First = "", untagged(t)
s.Title, s.own().First = "", untagged(t)
}
s.Grok = &c
s.own().Grok = &c
return s
}
+6 -6
View File
@@ -148,8 +148,8 @@ func TestGrokReadsOnlyWhatWasAppended(t *testing.T) {
summary := filepath.Join(dir, "summary.json")
b, _ := os.ReadFile(summary)
os.WriteFile(summary, bytes.Replace(b, []byte(`"generated_title": "Parser port"`), []byte(`"generated_title": "Port of the parser"`), 1), 0o644)
if at, end := g.read(), g.size(); at != end || g.old.Named != "Port of the parser" {
t.Fatalf("summary changed: read from %d of %d, named %q", at, end, g.old.Named)
if at, end := g.read(), g.size(); at != end || g.old.more().Named != "Port of the parser" {
t.Fatalf("summary changed: read from %d of %d, named %q", at, end, g.old.more().Named)
}
// the model its turns are counted under changed: read whole
b, _ = os.ReadFile(summary)
@@ -252,8 +252,8 @@ func TestKimiReadsOnlyWhatWasAppended(t *testing.T) {
g.read()
kimiSetState(t, sessions, slug, kimiCancel, map[string]any{"title": "Cancelled twice", "isCustomTitle": true})
if at, end := g.read(), g.size(); at != end || g.old.Custom != "Cancelled twice" {
t.Fatalf("state.json changed: read from %d of %d, custom %q", at, end, g.old.Custom)
if at, end := g.read(), g.size(); at != end || g.old.more().Custom != "Cancelled twice" {
t.Fatalf("state.json changed: read from %d of %d, custom %q", at, end, g.old.more().Custom)
}
// the session now says it was forked: what it counted is read again
kimiSetState(t, sessions, slug, kimiCancel, map[string]any{"forkedFrom": kimiJune})
@@ -477,8 +477,8 @@ func TestClineReadsMessagesOnlyWhenTheyChange(t *testing.T) {
t.Fatal("manifest touched: messages read again")
}
edit(manifest, `"status": "x"`, `"title": "Faster importer"`)
if read() || old.Named != "Faster importer" || old.Title != "Speed up the importer" {
t.Fatalf("manifest titled: named %q, title %q", old.Named, old.Title)
if read() || old.more().Named != "Faster importer" || old.Title != "Speed up the importer" {
t.Fatalf("manifest titled: named %q, title %q", old.more().Named, old.Title)
}
// a message more: read again
edit(path, `"content": "done",`, `"content": "done, all of it",`)
+1 -1
View File
@@ -629,7 +629,7 @@ func parseHermes(f file) *state {
s.Last = at
}
}
s.DBRevision = f.m().rev
s.own().DBRevision = f.m().rev
return s
}
+1 -1
View File
@@ -84,7 +84,7 @@ func TestHermesUnreadFingerprintsParseAgain(t *testing.T) {
// the same size and time as what was parsed: only the fingerprint can
// tell it changed, and it is unknown
f := file{agent: "hermes", path: path + "#s", more: &fileMore{hermes: h}, mod: time.Unix(1790000000, 0)}
s := state{Mod: f.mod.UnixNano(), DBRevision: ""}
s := state{Mod: f.mod.UnixNano()}
cache = map[string]*state{f.path: &s}
t.Cleanup(func() { cache = nil })
parsed := 0
+5 -5
View File
@@ -235,8 +235,8 @@ func parseKimi(f file, old *state) *state {
}
var s *state
var off int64
if o := old; o != nil && o.Kimi != nil && o.Kimi.Created.Equal(c.Created) && o.Kimi.Forked == c.Forked && o.Kimi.Tail.holds(f.path) {
s, c, off = o.clone(), *o.Kimi, o.Kimi.Tail.Off
if o := old; o != nil && o.more().Kimi != nil && o.more().Kimi.Created.Equal(c.Created) && o.more().Kimi.Forked == c.Forked && o.more().Kimi.Tail.holds(f.path) {
s, c, off = o.clone(), *o.more().Kimi, o.more().Kimi.Tail.Off
} else {
s = fresh()
}
@@ -260,10 +260,10 @@ func parseKimi(f file, old *state) *state {
s.Size, s.Mod = f.size, f.mod.UnixNano()
if hasSt && f.main {
s.Cwd = cmp.Or(st.Cwd, st.WorkDir, kimiIndexedWorkDir(f.path))
s.Custom, s.Named = st.names()
s.Custom, s.Named = title(s.Custom), title(s.Named)
s.own().Custom, s.own().Named = st.names()
s.own().Custom, s.own().Named = title(s.more().Custom), title(s.more().Named)
}
s.Kimi = &c
s.own().Kimi = &c
return s
}
+1 -1
View File
@@ -196,7 +196,7 @@ func TestKimiCodeSessionCounts(t *testing.T) {
}
}
if f.main {
custom, named = s.Custom, s.Named
custom, named = s.more().Custom, s.more().Named
}
}
return
+4 -3
View File
@@ -214,9 +214,10 @@ func glance(f file) *state {
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}
g := &state{Size: f.size, Mod: f.mod.UnixNano(), ID: s.ID, Cwd: s.Cwd, Title: s.Title,
Start: s.Start, Last: f.mod, CodexIdentity: s.CodexIdentity, Provider: s.Provider,
StateMore: moreOf(StateMore{Named: s.more().Named, Custom: s.more().Custom, First: s.more().First,
CodexNickname: s.more().CodexNickname})}
if g.Start.IsZero() || g.Start.After(g.Last) {
g.Start = g.Last
}
+5 -5
View File
@@ -560,7 +560,7 @@ func parseOpenCode(f file) *state {
}
s.ID, s.Cwd = info.ID, info.Directory
if t := title(info.Title); t != "" && !ocDefaultTitle(t) {
s.Named = t
s.own().Named = t
}
var msgs []ocMessage
for _, b := range f.m().oc.messages(f.m().sid) {
@@ -584,7 +584,7 @@ func parseOpenCode(f file) *state {
}
switch m.Role {
case "user":
if typed := m.Semantics == nil || m.Semantics.Origin == "" || m.Semantics.Origin == "real_user"; typed && f.main && s.Title == "" && s.First == "" {
if typed := m.Semantics == nil || m.Semantics.Origin == "" || m.Semantics.Origin == "real_user"; typed && f.main && s.Title == "" && s.more().First == "" {
ocTitle(s, f.m().oc.parts(m.ID))
}
case "assistant":
@@ -627,12 +627,12 @@ func ocTitle(s *state, parts [][]byte) {
}
}
if t := strings.Join(typed, " "); strings.HasPrefix(strings.TrimSpace(t), "<") {
s.First = untagged(t)
s.own().First = untagged(t)
} else {
s.Title = title(t)
}
if s.Title == "" && s.First == "" {
s.First = untagged(strings.Join(other, " "))
if s.Title == "" && s.more().First == "" {
s.own().First = untagged(strings.Join(other, " "))
}
}
+7 -7
View File
@@ -168,7 +168,7 @@ func piParse(s *state, b []byte, main bool) {
at := tsAt(b, false)
header := s.ID == "" && bytes.Contains(b, piHeader)
// a forked session's copy of the entries it was forked from
copied := !s.Since.IsZero() && !at.IsZero() && at.Before(s.Since)
copied := !s.more().Since.IsZero() && !at.IsZero() && at.Before(s.more().Since)
if !copied {
s.saw(at, main)
}
@@ -187,18 +187,18 @@ func piParse(s *state, b []byte, main bool) {
if s.ID == "" {
s.ID, s.Cwd = l.ID, l.Cwd
if l.ParentSession != "" {
s.Since = at
s.own().Since = at
}
if l.Title != "" {
s.Named = title(l.Title)
s.own().Named = title(l.Title)
}
}
case "session_info":
s.Named = title(l.Name)
s.own().Named = title(l.Name)
case "title_change":
// omp's, one with each new title
if l.Title != "" {
s.Named = title(l.Title)
s.own().Named = title(l.Title)
}
case "model_change":
if l.ModelID != "" {
@@ -230,8 +230,8 @@ func piParse(s *state, b []byte, main bool) {
s.tool(at, "", skill)
}
if main && s.Title == "" {
if s.Title = piPrompt(text); s.Title == "" && s.First == "" {
s.First = untagged(text)
if s.Title = piPrompt(text); s.Title == "" && s.more().First == "" {
s.own().First = untagged(text)
}
}
case "assistant":
+121 -61
View File
@@ -214,27 +214,60 @@ const All = 5000
// state is what one file's parse has come to, enough to read on from Off.
type state struct {
// the agent whose file it is, for its parseVersions
Agent string `json:"agent,omitempty"`
Codex *codexUsageState `json:"-"`
codexPath string // the rollout read, for its fork's parent
Claude *claudeUsageState `json:"claude,omitempty"`
Agent string `json:"agent,omitempty"`
Codex *codexUsageState `json:"-"`
codexPath string // the rollout read, for its fork's parent
Claude *claudeUsageState `json:"claude,omitempty"`
Head string `json:"head,omitempty"`
HeadSize int `json:"head_size,omitempty"`
ContentHash string `json:"content_hash,omitempty"`
Size int64 `json:"size"`
Mod int64 `json:"mod"` // unix nanoseconds
Off int64 `json:"off"` // after the last whole line read
ID string `json:"id,omitempty"`
CodexIdentity *CodexIdentity `json:"codex_identity,omitempty"`
Cwd string `json:"cwd,omitempty"`
Title string `json:"title,omitempty"`
Start time.Time `json:"start"`
Last time.Time `json:"last"`
Models named[Tokens] `json:"models,omitempty"`
// 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: parsed by a magpie that reads /cd's relocated lines
// (ccRelocated), so Cwd is the folder the session was last moved to
CdRead bool `json:"cd_read,omitempty"`
// Claude Code: the message last counted, whose later lines repeat it,
// and the day it was counted on
Msg string `json:"msg,omitempty"`
MsgModel string `json:"msg_model,omitempty"`
MsgUse Tokens `json:"msg_use"`
MsgDay string `json:"msg_day,omitempty"`
// Codex: the model in use, and its running total (input with cache) last seen
Model string `json:"model,omitempty"`
Total *Tokens `json:"total,omitempty"`
// Codex: the model_provider its session_meta names (codex_provider.go)
Provider string `json:"provider,omitempty"`
// what few files have, nil for a file with none of it (StateMore)
*StateMore
}
// StateMore is what only some files' state has. A history's every file is
// kept parsed, and these fields were ~330 of each state's 760 bytes, held
// empty by nearly all of them: ~6 MB of 18k files' states (#2278). It is
// embedded so the cache's JSON keeps its keys; a read through a state goes
// through more() and a write through own(), as a nil one has no fields.
type StateMore struct {
DBRevision string `json:"db_revision,omitempty"`
Head string `json:"head,omitempty"`
HeadSize int `json:"head_size,omitempty"`
ContentHash string `json:"content_hash,omitempty"`
Size int64 `json:"size"`
Mod int64 `json:"mod"` // unix nanoseconds
Off int64 `json:"off"` // after the last whole line read
ID string `json:"id,omitempty"`
CodexIdentity *CodexIdentity `json:"codex_identity,omitempty"`
CodexIdentityConflict bool `json:"codex_identity_conflict,omitempty"`
CodexNickname string `json:"codex_nickname,omitempty"`
CodexSpawnNames map[string]string `json:"codex_spawn_names,omitempty"`
CodexSpawnConflicts map[string]bool `json:"codex_spawn_conflicts,omitempty"`
CodexAgentIDs map[string]string `json:"codex_agent_ids,omitempty"`
CodexAgentConflicts map[string]bool `json:"codex_agent_conflicts,omitempty"`
Cwd string `json:"cwd,omitempty"`
Title string `json:"title,omitempty"`
Named string `json:"named,omitempty"` // the agent's own title for it
Custom string `json:"custom,omitempty"` // the name the user gave it
First string `json:"first,omitempty"` // the first message, when no prompt looked typed
@@ -252,25 +285,7 @@ type state struct {
// TurnConvs are the ids of its newest turn's user messages (the first
// of dshConvs each, the newest dshTurnKept), reset at the turn's start
// and not kept from a fork's seed (gui's ownerLast)
TurnConvs []string `json:"turn_convs,omitempty"`
Start time.Time `json:"start"`
Last time.Time `json:"last"`
Models named[Tokens] `json:"models,omitempty"`
// 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: parsed by a magpie that reads /cd's relocated lines
// (ccRelocated), so Cwd is the folder the session was last moved to
CdRead bool `json:"cd_read,omitempty"`
// Claude Code: the message last counted, whose later lines repeat it,
// and the day it was counted on
Msg string `json:"msg,omitempty"`
MsgModel string `json:"msg_model,omitempty"`
MsgUse Tokens `json:"msg_use"`
MsgDay string `json:"msg_day,omitempty"`
TurnConvs []string `json:"turn_convs,omitempty"`
// Claude Code: the uuids of the first and the last message of the
// file's own conversation (ccLink)
Root string `json:"root,omitempty"`
@@ -279,11 +294,6 @@ type state struct {
// /rewind's summarize) left in the file. A copy made after one starts
// with that summary, so its Root is one of these (ccCopies).
Compacts []string `json:"compacts,omitempty"`
// Codex: the model in use, and its running total (input with cache) last seen
Model string `json:"model,omitempty"`
Total *Tokens `json:"total,omitempty"`
// Codex: the model_provider its session_meta names (codex_provider.go)
Provider string `json:"provider,omitempty"`
// Pi: in a forked session, the time it was forked; the lines before
// it are the copy of the session it was forked from
Since time.Time `json:"since,omitzero"`
@@ -305,6 +315,43 @@ type state struct {
Cline *clineCarry `json:"cline,omitempty"`
}
// noMore is what more gives for a state with none: read, never written.
var noMore StateMore
// more is s's StateMore to read: an empty one when s has none.
func (s *state) more() *StateMore {
if s.StateMore != nil {
return s.StateMore
}
return &noMore
}
// own is s's StateMore to write, made when s has none.
func (s *state) own() *StateMore {
if s.StateMore == nil {
s.StateMore = &StateMore{}
}
return s.StateMore
}
// moreOf is m to embed in a state: nil when it holds nothing.
func moreOf(m StateMore) *StateMore {
if m.zero() {
return nil
}
return &m
}
// zero: m holds nothing a state would keep (TestStateMoreZeroKnowsEveryField).
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.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
}
// day is one local date's share of a file: tokens by model, and the time
// the session was at work on it.
type day struct {
@@ -436,19 +483,24 @@ func (s *state) clone() *state {
c.Codex = s.Codex.clone()
c.Claude = s.Claude.clone()
c.Models = slices.Clone(s.Models)
c.Compacts = slices.Clone(s.Compacts)
if s.Total != nil {
t := *s.Total
c.Total = &t
}
c.Convs = slices.Clone(s.Convs)
c.ResponseIDs = slices.Clone(s.ResponseIDs)
c.SeedConvs = slices.Clone(s.SeedConvs)
c.TurnConvs = slices.Clone(s.TurnConvs)
c.CodexSpawnNames = maps.Clone(s.CodexSpawnNames)
c.CodexSpawnConflicts = maps.Clone(s.CodexSpawnConflicts)
c.CodexAgentIDs = maps.Clone(s.CodexAgentIDs)
c.CodexAgentConflicts = maps.Clone(s.CodexAgentConflicts)
// its own StateMore: c := *s shares s's
if m := s.StateMore; m != nil {
cm := *m
cm.Compacts = slices.Clone(m.Compacts)
cm.Convs = slices.Clone(m.Convs)
cm.ResponseIDs = slices.Clone(m.ResponseIDs)
cm.SeedConvs = slices.Clone(m.SeedConvs)
cm.TurnConvs = slices.Clone(m.TurnConvs)
cm.CodexSpawnNames = maps.Clone(m.CodexSpawnNames)
cm.CodexSpawnConflicts = maps.Clone(m.CodexSpawnConflicts)
cm.CodexAgentIDs = maps.Clone(m.CodexAgentIDs)
cm.CodexAgentConflicts = maps.Clone(m.CodexAgentConflicts)
c.StateMore = &cm
}
c.Days = slices.Clone(s.Days)
for i, e := range c.Days {
v := e.v
@@ -1425,7 +1477,7 @@ func refresh(want, all []file) {
if f.cold {
continue // in a stopped WSL distro: what was read of it stands
}
if s := parsed(f.path); s == nil || s.Size != f.size || s.Mod != f.mod.UnixNano() || ccStale(f, s) || (f.agent == "hermes" && (f.m().hermes == nil || f.m().rev == "" || s.DBRevision != f.m().rev)) || ((f.agent == "alma" || f.agent == "cursor" || f.agent == "agy" || f.agent == "antigravity") && s.DBRevision != f.m().rev) {
if s := parsed(f.path); s == nil || s.Size != f.size || s.Mod != f.mod.UnixNano() || ccStale(f, s) || (f.agent == "hermes" && (f.m().hermes == nil || f.m().rev == "" || s.more().DBRevision != f.m().rev)) || ((f.agent == "alma" || f.agent == "cursor" || f.agent == "agy" || f.agent == "antigravity") && s.more().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
@@ -1923,28 +1975,28 @@ func assembleListed(fs []file, price func(string) *catalog.Price, codexTitle fun
if s.Title == "" {
s.Title = st.Title
}
if st.Named != "" {
named = st.Named
if st.more().Named != "" {
named = st.more().Named
}
if st.Custom != "" {
custom = st.Custom
if st.more().Custom != "" {
custom = st.more().Custom
}
if first == "" {
first = st.First
first = st.more().First
}
if s.Agent == "claude" && s.App == "" && desktopEntrypoint(st.Entry) {
s.App = "claude-desktop"
}
s.Convs = append(s.Convs, st.Convs...)
s.ResponseIDs = append(s.ResponseIDs, st.ResponseIDs...)
s.SeedConvs = append(s.SeedConvs, st.SeedConvs...)
s.TurnConvs = append(s.TurnConvs, st.TurnConvs...)
if d := st.Dsh; d != nil && d.Head.IsSeeded && d.Head.DelegationDepth == 0 {
s.Convs = append(s.Convs, st.more().Convs...)
s.ResponseIDs = append(s.ResponseIDs, st.more().ResponseIDs...)
s.SeedConvs = append(s.SeedConvs, st.more().SeedConvs...)
s.TurnConvs = append(s.TurnConvs, st.more().TurnConvs...)
if d := st.more().Dsh; d != nil && d.Head.IsSeeded && d.Head.DelegationDepth == 0 {
s.ForkOf = d.Head.ParentSession
}
}
if s.Agent == "codex" && st.CodexNickname != "" {
s.Nickname = st.CodexNickname
if s.Agent == "codex" && st.more().CodexNickname != "" {
s.Nickname = st.more().CodexNickname
}
if !st.Start.IsZero() && (s.Start.IsZero() || st.Start.Before(s.Start)) {
s.Start = st.Start
@@ -2054,6 +2106,14 @@ func parse(f file, old *state) *state { return parseWith(f, old, nil) }
// parseWith is parse with calls, when not nil, reading the file's calls on
// the same pass.
func parseWith(f file, old *state, calls *callsRide) *state {
s := parseRead(f, old, calls)
if s != nil && s.StateMore.zero() {
s.StateMore = nil // only empty values were written through own()
}
return s
}
func parseRead(f file, old *state, calls *callsRide) *state {
defer func() {
if calls != nil {
calls.release()
@@ -2917,7 +2977,7 @@ func Titles(keys []string) map[string]string {
continue
}
if st := cache[path]; st != nil {
if name := cmp.Or(st.Named, st.Title, st.First); name != "" {
if name := cmp.Or(st.more().Named, st.Title, st.more().First); name != "" {
out[k] = name
}
}
+103
View File
@@ -0,0 +1,103 @@
package sessions
import (
"bytes"
"reflect"
"testing"
"time"
)
// TestStateMoreZeroKnowsEveryField: a StateMore with any one field set is
// not zero, so a parse or a decode never drops what it holds; a field
// added to StateMore and not to zero() fails here.
func TestStateMoreZeroKnowsEveryField(t *testing.T) {
if !(*StateMore)(nil).zero() || !(&StateMore{}).zero() {
t.Fatal("an empty StateMore isn't zero")
}
typ := reflect.TypeFor[StateMore]()
for i := range typ.NumField() {
var m StateMore
f := reflect.ValueOf(&m).Elem().Field(i)
switch f.Kind() {
case reflect.String:
f.SetString("x")
case reflect.Bool:
f.SetBool(true)
case reflect.Slice:
f.Set(reflect.MakeSlice(f.Type(), 1, 1))
case reflect.Map:
f.Set(reflect.MakeMap(f.Type()))
f.SetMapIndex(reflect.New(f.Type().Key()).Elem(), reflect.New(f.Type().Elem()).Elem())
case reflect.Pointer:
f.Set(reflect.New(f.Type().Elem()))
case reflect.Struct:
if f.Type() != reflect.TypeFor[time.Time]() {
t.Fatalf("%s: a struct field zero() can't be checked for", typ.Field(i).Name)
}
f.Set(reflect.ValueOf(time.Unix(1, 0)))
default:
t.Fatalf("%s: kind %s not set by this test", typ.Field(i).Name, f.Kind())
}
if m.zero() || moreOf(m) == nil {
t.Errorf("%s set, and zero() says the StateMore is empty", typ.Field(i).Name)
}
}
}
// TestStateMoreReadsLeaveTheSharedEmptyOne: reading a state with no extra
// makes none and finds every field empty, and a write makes its own.
func TestStateMoreReadsLeaveTheSharedEmptyOne(t *testing.T) {
s := &state{}
if s.more().Named != "" || s.more().Agy != nil || s.StateMore != nil {
t.Fatal("a read of an empty state made or found an extra")
}
s.own().Named = "n"
if s.StateMore == nil || s.more().Named != "n" || !noMore.zero() || (&state{}).more().Named != "" {
t.Fatal("a write through own() reached the shared empty StateMore")
}
}
// TestStateCloneOwnsItsMore: a clone's extra is its own, so growing the
// clone (as every parse after the first does) leaves the kept state alone.
func TestStateCloneOwnsItsMore(t *testing.T) {
s := &state{StateMore: &StateMore{Named: "a", Convs: []string{"c1"}, CodexSpawnNames: map[string]string{"k": "v"}, Compacts: []string{"u"}}}
c := s.clone()
if c.StateMore == s.StateMore {
t.Fatal("the clone shares the kept state's StateMore")
}
c.own().Named = "b"
c.own().Convs[0] = "c2"
c.own().CodexSpawnNames["k"] = "w"
c.own().Compacts = append(c.more().Compacts, "u2")
if s.Named != "a" || s.Convs[0] != "c1" || s.CodexSpawnNames["k"] != "v" || len(s.Compacts) != 1 {
t.Fatalf("a change to the clone reached the kept state: %+v", *s.StateMore)
}
if (&state{}).clone().StateMore != nil {
t.Fatal("a clone of a state with no extra made one")
}
}
// TestCacheKeepsNoEmptyMore: a cache written with states that have no
// extra, or an empty one, reads back with none, and one with an extra
// reads back with it.
func TestCacheKeepsNoEmptyMore(t *testing.T) {
c := cacheFile{Version: cacheVersion, Zone: "UTC", Parsers: parseVersions, Files: map[string]*state{
"/a": {Agent: "claude", Size: 1, Title: "t"},
"/b": {Agent: "claude", Size: 2, StateMore: &StateMore{}},
"/c": {Agent: "claude", Size: 3, StateMore: &StateMore{Named: "named", Root: "r"}},
}}
var b bytes.Buffer
if err := encodeCache(&b, c); err != nil {
t.Fatal(err)
}
files, ok := decodeCache(b.Bytes(), "UTC")
if !ok || len(files) != 3 {
t.Fatalf("decode: %v %d", ok, len(files))
}
if files["/a"].StateMore != nil || files["/b"].StateMore != nil {
t.Fatal("an empty extra was kept by the decode")
}
if m := files["/c"].StateMore; m == nil || m.Named != "named" || m.Root != "r" {
t.Fatalf("an extra was lost: %+v", m)
}
}
+2 -2
View File
@@ -66,8 +66,8 @@ func subagentsOf(s Session, fs []file) []Subagent {
if f.m().parent != s.ID {
sa.Parent = f.m().parent
}
sa.Title, sa.Kind = ocSubagentTitle(st.Named)
sa.Title = cmp.Or(sa.Title, st.Title, st.First)
sa.Title, sa.Kind = ocSubagentTitle(st.more().Named)
sa.Title = cmp.Or(sa.Title, st.Title, st.more().First)
// OpenCode 2 names the agent in the session's row, and its
// titles no longer do (#2290)
if v2, ok := f.m().oc.(ocV2DB); ok {
+5 -5
View File
@@ -181,7 +181,7 @@ func workbuddyLine(s *state, b []byte, main bool) {
at := numTS(b)
s.saw(at, main)
want := bytes.Contains(b, wbUsage) ||
main && (bytes.Contains(b, wbTitle) || s.First == "" && bytes.Contains(b, wbUser)) ||
main && (bytes.Contains(b, wbTitle) || s.more().First == "" && bytes.Contains(b, wbUser)) ||
s.Cwd == "" && bytes.Contains(b, wbCwd)
if !want {
return
@@ -204,15 +204,15 @@ func workbuddyLine(s *state, b []byte, main bool) {
case "custom-title":
// named by the user: before the one WorkBuddy made
if main && l.CustomTitle != "" {
s.Custom = title(l.CustomTitle)
s.own().Custom = title(l.CustomTitle)
}
case "ai-title":
if main && l.AITitle != "" {
s.Named = title(l.AITitle)
s.own().Named = title(l.AITitle)
}
case "message":
if main && l.Role == "user" && s.First == "" {
s.First = wbPrompt(l.Content)
if main && l.Role == "user" && s.more().First == "" {
s.own().First = wbPrompt(l.Content)
}
}
u := p.Usage