Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
sessions: a parse's models, days and tools are sorted slices, not maps
yetonebbb4fd478aa9
diff --git a/internal/sessions/agy_test.go b/internal/sessions/agy_test.goindex 8690b879f..7e0471de2 100644--- a/internal/sessions/agy_test.go+++ b/internal/sessions/agy_test.go@@ -94,8 +94,8 @@ func TestAgyCounts(t *testing.T) {t.Fatal("no transcript")}s := parseAgy(f, nil)- d := s.Days["2026-10-25"]- if d == nil || d.Prompts != 1 || d.Replies != 1 || d.Tools["read_file"] != 1 {+ d := s.Days.of("2026-10-25")+ if d == nil || d.Prompts != 1 || d.Replies != 1 || d.Tools.of("read_file") != 1 {t.Fatalf("day: %+v", d)}if s.Title != "read a.txt" {@@ -145,17 +145,17 @@ func TestAgyGrows(t *testing.T) {whole := parseAgy(f, nil)want := Tokens{Input: 3010, CacheRead: 1000, Output: 112}for name, s := range map[string]*state{"read on": on, "read whole": whole} {- if got := s.Models["agy"]; got != want {+ if got := s.Models.of("agy"); got != want {t.Errorf("%s: %+v, want %+v", name, got, want)}- if d := s.Days["2026-10-25"]; d == nil || d.Prompts != 2 || d.Replies != 2 {+ if d := s.Days.of("2026-10-25"); d == nil || d.Prompts != 2 || d.Replies != 2 {t.Errorf("%s: day %+v", name, d)}if !s.Last.Equal(at("2026-10-25T10:00:01Z")) {t.Errorf("%s: last %s", name, s.Last)}}- if first.Models["agy"] != (Tokens{Input: 3000, CacheRead: 1000, Output: 100}) {+ if first.Models.of("agy") != (Tokens{Input: 3000, CacheRead: 1000, Output: 100}) {t.Errorf("the read before was changed: %+v", first.Models)}}diff --git a/internal/sessions/cache_decode.go b/internal/sessions/cache_decode.goindex 5846ef26b..aabaa6413 100644--- a/internal/sessions/cache_decode.go+++ b/internal/sessions/cache_decode.go@@ -149,10 +149,8 @@ func (st *state) share() {// models as its own: held once, they were ~10 of the 28MB kept. A kept// state is never written: a parse writes a clone, which holds them apart.if len(st.Days) == 1 {- for _, d := range st.Days {- if len(d.Models) == len(st.Models) && maps.Equal(d.Models, st.Models) {- d.Models = st.Models- }+ if d := st.Days[0].v; d != nil && slices.Equal(d.Models, st.Models) {+ d.Models = st.Models}}}diff --git a/internal/sessions/cache_decode_test.go b/internal/sessions/cache_decode_test.goindex 99495cd06..34c37b52f 100644--- a/internal/sessions/cache_decode_test.go+++ b/internal/sessions/cache_decode_test.go@@ -103,26 +103,26 @@ func TestDecodeCacheSharesOneDaysModels(t *testing.T) {if !ok || len(files) != 3 {t.Fatalf("decoded %d files, %v", len(files), ok)}- same := func(a, b map[string]Tokens) bool {- return reflect.ValueOf(a).UnsafePointer() == reflect.ValueOf(b).UnsafePointer()+ same := func(a, b named[Tokens]) bool {+ return unsafe.SliceData(a) == unsafe.SliceData(b)}one, other, two := files["/one"], files["/other"], files["/two"]- if !same(one.Models, one.Days["2026-10-24"].Models) {+ if !same(one.Models, one.Days.of("2026-10-24").Models) {t.Errorf("a file of one day holds its models twice")}- if same(other.Models, other.Days["2026-10-24"].Models) || same(two.Models, two.Days["2026-10-23"].Models) {+ if same(other.Models, other.Days.of("2026-10-24").Models) || same(two.Models, two.Days.of("2026-10-23").Models) {t.Errorf("models held once that aren't the same, or of a file of two days")}c := one.clone()c.use("2026-10-24", "gpt-5.5", Tokens{Input: 1})- if c.Models["gpt-5.5"].Input != 11 || c.Days["2026-10-24"].Models["gpt-5.5"].Input != 11 {- t.Fatalf("a parse counted %d and %d, want 11 in each", c.Models["gpt-5.5"].Input, c.Days["2026-10-24"].Models["gpt-5.5"].Input)+ if c.Models.of("gpt-5.5").Input != 11 || c.Days.of("2026-10-24").Models.of("gpt-5.5").Input != 11 {+ t.Fatalf("a parse counted %d and %d, want 11 in each", c.Models.of("gpt-5.5").Input, c.Days.of("2026-10-24").Models.of("gpt-5.5").Input)}c.dropUse("2026-10-24", "gpt-5.5", Tokens{Input: 11, Output: 2})- if len(c.Models) != 0 || c.Days["2026-10-24"] == nil || len(c.Days["2026-10-24"].Models) != 0 {- t.Fatalf("a parse took back to %v and %+v", c.Models, c.Days["2026-10-24"])+ if len(c.Models) != 0 || c.Days.of("2026-10-24") == nil || len(c.Days.of("2026-10-24").Models) != 0 {+ t.Fatalf("a parse took back to %v and %+v", c.Models, c.Days.of("2026-10-24"))}- if one.Models["gpt-5.5"].Input != 10 || one.Days["2026-10-24"].Models["gpt-5.5"].Input != 10 {+ if one.Models.of("gpt-5.5").Input != 10 || one.Days.of("2026-10-24").Models.of("gpt-5.5").Input != 10 {t.Fatalf("the kept state was written: %v", one.Models)}}@@ -132,7 +132,7 @@ func TestDecodeCacheSharesOneDaysModels(t *testing.T) {// no parse, an empty index and none at all.func TestEncodeCacheIsMarshal(t *testing.T) {at := time.Date(2026, 10, 25, 7, 0, 0, 0, time.UTC)- files := map[string]*state{"/b/<a&b>.jsonl": {Size: 3, Mod: 9, Title: "a <b> & \"c\" ", Start: at, Last: at, Models: map[string]Tokens{"m": {Input: 1}}}, "/a/x.jsonl": nil}+ files := map[string]*state{"/b/<a&b>.jsonl": {Size: 3, Mod: 9, Title: "a <b> & \"c\" ", Start: at, Last: at, Models: named[Tokens]{{"m", Tokens{Input: 1}}}}, "/a/x.jsonl": nil}for i := range 3000 {files[fmt.Sprintf("/s/%04d.jsonl", i)] = &state{Size: int64(i), Cwd: strings.Repeat("d", i%300), Start: at, Last: at.Add(time.Duration(i) * time.Second)}}diff --git a/internal/sessions/claude_cache_ttl_test.go b/internal/sessions/claude_cache_ttl_test.goindex 2d1f9c828..26c397467 100644--- a/internal/sessions/claude_cache_ttl_test.go+++ b/internal/sessions/claude_cache_ttl_test.go@@ -22,8 +22,8 @@ func TestClaudeCacheWriteSplit(t *testing.T) {claudeLine(s, []byte(fmt.Sprintf(`{"type":"assistant","timestamp":%q,"requestId":"req-a","message":{%s,"role":"assistant","content":[],"usage":{"input_tokens":10,"output_tokens":2,"cache_read_input_tokens":30,"cache_creation_input_tokens":3000,"cache_creation":{"ephemeral_5m_input_tokens":1000,"ephemeral_1h_input_tokens":2000}}}}`,at.Format(time.RFC3339Nano), id)), true)claudeLine(s, claudeUsageLine(at.Add(time.Second), "b", "req-b", "m", Tokens{Input: 1, CacheWrite: 500}, "", fast), true)- if want := (Tokens{Input: 11, Output: 2, CacheRead: 30, CacheWrite: 3500, CacheWrite1h: 2000}); s.Models["m"] != want {- t.Fatalf("tokens = %+v, want %+v", s.Models["m"], want)+ if want := (Tokens{Input: 11, Output: 2, CacheRead: 30, CacheWrite: 3500, CacheWrite1h: 2000}); s.Models.of("m") != want {+ t.Fatalf("tokens = %+v, want %+v", s.Models.of("m"), want)}})}diff --git a/internal/sessions/claude_historical_test.go b/internal/sessions/claude_historical_test.goindex db183eb54..bb868ef87 100644--- a/internal/sessions/claude_historical_test.go+++ b/internal/sessions/claude_historical_test.go@@ -44,7 +44,7 @@ func TestHistoricalClaudeFilesDoNotDisplaceActiveWindows(t *testing.T) {v.add(c.Tokens)totals[c.File] = v}- if totals[claude] != cache[claude].Models["m"] || totals[codex] != cache[codex].Models["gpt-6-astra"] {+ if totals[claude] != cache[claude].Models.of("m") || totals[codex] != cache[codex].Models.of("gpt-6-astra") {t.Fatal("calls and summaries disagree", totals[claude], totals[codex])}}@@ -77,10 +77,10 @@ func TestHistoricalClaudeFilesDoNotDisplaceActiveWindows(t *testing.T) {t.Fatal("rebuilt active call shard", path)}}- if got := cache[claude].Models["m"]; got != (Tokens{Input: 100, Output: i + 2}) {+ if got := cache[claude].Models.of("m"); got != (Tokens{Input: 100, Output: i + 2}) {t.Fatal(got)}- if got := cache[codex].Models["gpt-6-astra"]; got != (Tokens{Input: 100 * (i + 2), Output: i + 2}) {+ if got := cache[codex].Models.of("gpt-6-astra"); got != (Tokens{Input: 100 * (i + 2), Output: i + 2}) {t.Fatal(got)}}diff --git a/internal/sessions/claude_native_review_test.go b/internal/sessions/claude_native_review_test.goindex 820aeee98..5df405e8d 100644--- a/internal/sessions/claude_native_review_test.go+++ b/internal/sessions/claude_native_review_test.go@@ -119,7 +119,7 @@ func TestEvictedClaudeRevisionsReleasedAndRebuilt(t *testing.T) {want := Tokens{10338, 37363, 281066, 63398, 0}List(0)var got Tokens- for _, v := range cache[path].Models {+ for _, v := range cache[path].Models.all() {got.add(v)}if got != want {diff --git a/internal/sessions/claude_object_end_test.go b/internal/sessions/claude_object_end_test.goindex b20969f76..c9b66d72e 100644--- a/internal/sessions/claude_object_end_test.go+++ b/internal/sessions/claude_object_end_test.go@@ -39,8 +39,8 @@ func TestClaudeReplyDecodesWithoutCopyingTheLine(t *testing.T) {line := claudeUsageLine(at, "a", "req-a", "m", Tokens{Input: 10, Output: 2}, content, true)s := &state{}claudeLine(s, line, true)- if s.Models["m"] != (Tokens{Input: 10, Output: 2}) {- t.Fatalf("tokens %+v", s.Models["m"])+ if s.Models.of("m") != (Tokens{Input: 10, Output: 2}) {+ t.Fatalf("tokens %+v", s.Models.of("m"))}const n = 20var before, after runtime.MemStatsdiff --git a/internal/sessions/claude_retention_test.go b/internal/sessions/claude_retention_test.goindex 69da601bf..b5135ebcb 100644--- a/internal/sessions/claude_retention_test.go+++ b/internal/sessions/claude_retention_test.go@@ -52,7 +52,7 @@ func TestQoderUsageAfterWindowLoss(t *testing.T) {}appendText(t, path, string(claudeUsageLine(at.Add(time.Second), "a", "r", "m", Tokens{Input: 100, Output: 50}, "", true))+"\n")List(0)- if got := cache[path].Models["m"]; got != (Tokens{Input: 100, Output: 50}) {+ if got := cache[path].Models.of("m"); got != (Tokens{Input: 100, Output: 50}) {t.Fatalf("after window loss: %+v, want input=100 output=50", got)}})@@ -121,7 +121,7 @@ func TestClaudeLargeWindowSurvivesIdleAndSmallFiles(t *testing.T) {if cache[path].Named != "must resume this summary" {t.Fatal("summary reparsed the large prefix")}- if got := cache[path].Models["m"]; got != (Tokens{Input: 4001, Output: 8002}) {+ if got := cache[path].Models.of("m"); got != (Tokens{Input: 4001, Output: 8002}) {t.Fatal(got)}after, err := os.Stat(callCachePath(path))diff --git a/internal/sessions/claude_usage.go b/internal/sessions/claude_usage.goindex fcd85f536..f130827b7 100644--- a/internal/sessions/claude_usage.go+++ b/internal/sessions/claude_usage.go@@ -311,10 +311,10 @@ func ccTool(s *state, m *claudeContribution, at time.Time, id, name, skill strinprevious = append(append([]claudeToolVersion(nil), old.Previous...), claudeToolVersion{old.Name, old.Skill})d := s.day(dateOf(old.At))if old.Name != "" {- d.Tools[old.Name]--+ *d.Tools.at(old.Name)--}if old.Skill != "" {- d.Skills[old.Skill]--+ *d.Skills.at(old.Skill)--}}m.Tools[id] = claudeToolUsage{At: at, Updated: at, Name: name, Skill: skill, Previous: previous}diff --git a/internal/sessions/claude_usage_test.go b/internal/sessions/claude_usage_test.goindex a8e24812c..ffa7902d0 100644--- a/internal/sessions/claude_usage_test.go+++ b/internal/sessions/claude_usage_test.go@@ -23,7 +23,7 @@ func claudeUsageLine(at time.Time, id, request, model string, tokens Tokens, confunc claudeUsageReplies(s *state) int {n := 0- for _, d := range s.Days {+ for _, d := range s.Days.all() {n += d.Replies}return n@@ -40,10 +40,10 @@ func TestClaudeUsageNonAdjacentReplay(t *testing.T) {claudeLine(s, claudeUsageLine(at.Add(48*time.Hour), "a", "req-a", "m", a, "", fast), true)want := awant.add(b)- if s.Models["m"] != want || claudeUsageReplies(s) != 2 {+ if s.Models.of("m") != want || claudeUsageReplies(s) != 2 {t.Fatalf("tokens=%+v replies=%d, want %+v / 2", s.Models, claudeUsageReplies(s), want)}- if s.Days[dateOf(at)].Models["m"] != want {+ if s.Days.of(dateOf(at)).Models.of("m") != want {t.Fatal("replay moved the original contribution to its observation date")}})@@ -65,24 +65,24 @@ func TestClaudeUsageRevisionAndTools(t *testing.T) {claudeLine(s, line(time.Second, "m", updated, newTool), true)claudeLine(s, line(2*time.Second, "m", old, tool), true)claudeLine(s, line(time.Millisecond, "m", Tokens{10, 99, 30, 4, 0}, tool), true)- if s.Models["m"] != updated || claudeUsageReplies(s) != 1 {+ if s.Models.of("m") != updated || claudeUsageReplies(s) != 1 {t.Fatalf("old replay undid newer usage: %+v", s)}- d := s.Days[dateOf(at)]- if d.Tools["Read"] != 1 || d.Tools["Skill"] != 1 || d.Skills["review"] != 1 {+ d := s.Days.of(dateOf(at))+ if d.Tools.of("Read") != 1 || d.Tools.of("Skill") != 1 || d.Skills.of("review") != 1 {t.Fatalf("tools=%v skills=%v", d.Tools, d.Skills)}// A genuinely newer correction can reduce tokens and change model.correction := Tokens{8, 5, 20, 0, 0}claudeLine(s, line(48*time.Hour, "m2", correction, ""), true)- if !s.Models["m"].zero() || s.Models["m2"] != correction || d.Replies != 1 {+ if !s.Models.of("m").zero() || s.Models.of("m2") != correction || d.Replies != 1 {t.Fatalf("correction failed: %+v", s)}- if !d.Models["m"].zero() || s.Days[dateOf(at.Add(48*time.Hour))].Models["m2"] != correction {+ if !d.Models.of("m").zero() || s.Days.of(dateOf(at.Add(48*time.Hour))).Models.of("m2") != correction {t.Fatal("correction did not replace both date/model buckets")}claudeLine(s, line(49*time.Hour, "m", updated, newTool), true)- if s.Models["m2"] != correction || !s.Models["m"].zero() {+ if s.Models.of("m2") != correction || !s.Models.of("m").zero() {t.Fatal("known old snapshot with new observation time replaced correction")}})@@ -117,7 +117,7 @@ func TestClaudeUsageIdentity(t *testing.T) {for range tc.calls {want.add(tok)}- if s.Models["m"] != want || claudeUsageReplies(s) != tc.calls || len(st.Calls) != tc.calls {+ if s.Models.of("m") != want || claudeUsageReplies(s) != tc.calls || len(st.Calls) != tc.calls {t.Fatalf("tokens=%+v replies=%d calls=%d, want %+v / %d", s.Models, claudeUsageReplies(s), len(st.Calls), want, tc.calls)}if tc.name == "missing request upgrade" && st.Calls[0].RequestID != "r1" {@@ -135,7 +135,7 @@ func TestClaudeUsageMissingToolIdentityAndSubagent(t *testing.T) {for i := range 2 {claudeLine(s, claudeUsageLine(at.Add(time.Duration(i)*time.Second), "a", "r", "m", tok, content, true), false)}- if s.Models["m"] != tok || claudeUsageReplies(s) != 0 || s.Days[dateOf(at)].Tools["Read"] != 2 {+ if s.Models.of("m") != tok || claudeUsageReplies(s) != 0 || s.Days.of(dateOf(at)).Tools.of("Read") != 2 {t.Fatalf("subagent/missing tool ID behavior changed: %+v", s)}}@@ -147,8 +147,8 @@ func TestClaudeToolRevisionRejectsReplayedName(t *testing.T) {content := fmt.Sprintf(`[{"type":"tool_use","id":"tool-1","name":%q,"input":{}}]`, name)claudeLine(s, claudeUsageLine(at.Add(time.Duration(i)*time.Second), "a", "r", "m", Tokens{Input: 3}, content, true), true)}- d := s.Days[dateOf(at)]- if d.Tools["Read"] != 0 || d.Tools["Write"] != 1 {+ d := s.Days.of(dateOf(at))+ if d.Tools.of("Read") != 0 || d.Tools.of("Write") != 1 {t.Fatalf("old tool snapshot undid newer name: %v", d.Tools)}}@@ -179,7 +179,7 @@ func TestClaudeRepeatedBlockRejectsZeroedHistoricalSnapshot(t *testing.T) {claudeLine(s, b, true)claudeCallLine(calls, b)}- if s.Models["m"] != tokens || len(calls.Calls) != 1 || calls.Calls[0].Tokens != tokens {+ if s.Models.of("m") != tokens || len(calls.Calls) != 1 || calls.Calls[0].Tokens != tokens {t.Fatalf("zeroed historical blocks removed original usage: summary=%v calls=%+v", s.Models, calls.Calls)}})diff --git a/internal/sessions/claude_window_test.go b/internal/sessions/claude_window_test.goindex 0c55d2a5c..3f88d5311 100644--- a/internal/sessions/claude_window_test.go+++ b/internal/sessions/claude_window_test.go@@ -99,7 +99,7 @@ func TestClaudeWindowBoundsOneLongMessage(t *testing.T) {}}want := Tokens{Output: claudeRevisionEntries * 2}- if s.Models["m"] != want || claudeUsageReplies(s) != 1 {+ if s.Models.of("m") != want || claudeUsageReplies(s) != 1 {t.Fatal("window reset lost the current contribution")}copy := s.clone()diff --git a/internal/sessions/cursor_test.go b/internal/sessions/cursor_test.goindex f8dc07bb5..476c79f91 100644--- a/internal/sessions/cursor_test.go+++ b/internal/sessions/cursor_test.go@@ -283,10 +283,10 @@ func TestCursor(t *testing.T) {tools := map[string]int{}for _, f := range cursorFiles() {if st := cache[f.path]; st != nil && f.key == "cursor:"+curMain {- if st.Days[date] == nil {+ if st.Days.of(date) == nil {t.Fatalf("%s counts no day %s: %v", f.path, date, st.Days)}- for name, n := range st.Days[date].Tools {+ for name, n := range st.Days.of(date).Tools.all() {tools[name] += n}}diff --git a/internal/sessions/grow_test.go b/internal/sessions/grow_test.goindex a67233d66..ecefb6a9e 100644--- a/internal/sessions/grow_test.go+++ b/internal/sessions/grow_test.go@@ -204,11 +204,11 @@ func TestDroidReadsOnlyWhatWasAppended(t *testing.T) {if at := g.read(); at != was {t.Fatalf("read from %d, not %d", at, was)}- if d := g.old.Days["2026-09-27"]; d == nil || len(d.Models) != 0 {+ if d := g.old.Days.of("2026-09-27"); d == nil || len(d.Models) != 0 {t.Fatalf("the total is still on the day before: %+v", d)}- if m := g.old.Days["2026-09-28"].Models["claude-opus-4-5"]; m.Input != 300 {- t.Fatalf("the total on its day: %+v", g.old.Days["2026-09-28"])+ if m := g.old.Days.of("2026-09-28").Models.of("claude-opus-4-5"); m.Input != 300 {+ t.Fatalf("the total on its day: %+v", g.old.Days.of("2026-09-28"))}// only the settings changed: nothing of the transcript reados.WriteFile(filepath.Join(dir, droidMain+".settings.json"), []byte(`{"model":"claude-opus-4-5","tokenUsage":{"inputTokens":400,"outputTokens":90}}`), 0o644)@@ -286,7 +286,7 @@ func TestKimiForkMarkerAcrossReads(t *testing.T) {g.read()g.append(`{"type":"usage.record","model":"kimi-code/k3","usage":{"inputOther":7,"output":3,"inputCacheRead":0,"inputCacheCreation":0},"usageScope":"turn","time":1791700005000}` + "\n")g.read()- if g.old.Models["kimi-code/k3"] != (Tokens{Input: 7, Output: 3}) || len(g.old.Models) != 1 {+ if g.old.Models.of("kimi-code/k3") != (Tokens{Input: 7, Output: 3}) || len(g.old.Models) != 1 {t.Fatalf("the fork's own: %+v", g.old.Models)}}@@ -357,7 +357,7 @@ func TestDshPackedReadsOnlyWhatWasAppended(t *testing.T) {if at := g.read(); at != was {t.Fatalf("the line finished in the next frame, read from %d, not its frame's %d", at, was)}- if m := g.old.Models["deepseek-v4-flash"]; m.Input != 10+6+7+8+9 {+ if m := g.old.Models.of("deepseek-v4-flash"); m.Input != 10+6+7+8+9 {t.Fatalf("flash, each reply once: %+v", m)}// cut short: read whole again@@ -397,7 +397,7 @@ func TestDshEndSeedAcrossReads(t *testing.T) {g.read()g.append(string(b[rest:]))g.read()- if m := g.old.Models["deepseek-v4-pro"]; m.Input != 50 || len(g.old.Models) != 1 || g.old.Title != "Tidy the build script" {+ if m := g.old.Models.of("deepseek-v4-pro"); m.Input != 50 || len(g.old.Models) != 1 || g.old.Title != "Tidy the build script" {t.Fatalf("the fork's own: %+v, title %q", g.old.Models, g.old.Title)}}@@ -492,7 +492,7 @@ func TestClineReadsMessagesOnlyWhenTheyChange(t *testing.T) {}// made a fork after its first reply: what came before is its source'sedit(manifest, `"metadata": {`, `"metadata": {"fork": {"forkedAt": "2026-09-27T10:01:00.000Z"},`)- if !read() || old.Models["claude-opus-5-5"] != (Tokens{}) {+ if !read() || old.Models.of("claude-opus-5-5") != (Tokens{}) {t.Fatalf("forked: %+v", old.Models)}// started at another time: read againdiff --git a/internal/sessions/kimi_test.go b/internal/sessions/kimi_test.goindex 53255462e..ef45e64dc 100644--- a/internal/sessions/kimi_test.go+++ b/internal/sessions/kimi_test.go@@ -188,10 +188,10 @@ func TestKimiCodeSessionCounts(t *testing.T) {sum := func(id string) (prompts, replies, tools int, custom, named string) {for _, f := range byKey["kimi:"+id] {s := parseKimi(f, nil)- for _, d := range s.Days {+ for _, d := range s.Days.all() {prompts += d.Promptsreplies += d.Replies- for _, n := range d.Tools {+ for _, n := range d.Tools.all() {tools += n}}diff --git a/internal/sessions/manage.go b/internal/sessions/manage.goindex c6da1faf6..56daf168f 100644--- a/internal/sessions/manage.go+++ b/internal/sessions/manage.go@@ -230,7 +230,7 @@ func listAgent(agent string, all []file) []Managed {for _, f := range fs {m.Size += f.sizeif st := cache[f.path]; st != nil && f.main {- for _, d := range st.Days {+ for _, d := range st.Days.all() {m.Messages += d.Prompts + d.Replies}}diff --git a/internal/sessions/named.go b/internal/sessions/named.gonew file mode 100644index 000000000..16d1bf960--- /dev/null+++ b/internal/sessions/named.go@@ -0,0 +1,208 @@+package sessions++import (+ "bytes"+ "encoding/json"+ "errors"+ "iter"+ "slices"+ "strings"+ "unique"+ "unsafe"++ "github.com/tidwall/gjson"+)++// named holds a few values by name, in the names' order, and is written as+// the JSON object a map is. A file's parse has a model or two, a day or two+// and a few tools, and Go's map of one is a group of eight: ~500 bytes for+// one model's Tokens, where this holds 56. A long history's 15.9k kept+// parses held ~18MB of such maps.+type named[V any] []entry[V]++type entry[V any] struct {+ name string+ v V+}++func (n named[V]) find(name string) (int, bool) {+ return slices.BinarySearchFunc(n, name, func(e entry[V], name string) int { return strings.Compare(e.name, name) })+}++// get is name's value, and whether there is one.+func (n named[V]) get(name string) (V, bool) {+ if i, ok := n.find(name); ok {+ return n[i].v, true+ }+ var zero V+ return zero, false+}++// of is name's value, or the zero value when there is none.+func (n named[V]) of(name string) V {+ v, _ := n.get(name)+ return v+}++// at is where name's value is held, a zero one put in when there is none.+// It holds until the next name is put in.+func (n *named[V]) at(name string) *V {+ i, ok := n.find(name)+ if !ok {+ *n = slices.Insert(*n, i, entry[V]{name: name})+ }+ return &(*n)[i].v+}++// del takes name out, leaving nil when nothing is left, as a map's delete+// and the nil the code set after it did.+func (n *named[V]) del(name string) {+ if i, ok := n.find(name); ok {+ *n = slices.Delete(*n, i, i+1)+ }+ if len(*n) == 0 {+ *n = nil+ }+}++// all is each name and its value, in the names' order.+func (n named[V]) all() iter.Seq2[string, V] {+ return func(yield func(string, V) bool) {+ for _, e := range n {+ if !yield(e.name, e.v) {+ return+ }+ }+ }+}++// MarshalJSON writes n as json.Marshal writes a map: keys in order.+func (n named[V]) MarshalJSON() ([]byte, error) {+ if n == nil {+ return []byte("null"), nil+ }+ var b bytes.Buffer+ b.WriteByte('{')+ for i, e := range n {+ if i > 0 {+ b.WriteByte(',')+ }+ k, err := json.Marshal(e.name)+ if err != nil {+ return nil, err+ }+ b.Write(k)+ b.WriteByte(':')+ v, err := json.Marshal(e.v)+ if err != nil {+ return nil, err+ }+ b.Write(v)+ }+ b.WriteByte('}')+ return b.Bytes(), nil+}++var errNotObject = errors.New("sessions: not a JSON object")++// UnmarshalJSON reads an object as json.Unmarshal reads it into a map: a+// name given twice is its last. b is the cache file's own bytes, which are+// not kept: names are held once (unique) for all the parses that use them.+func (n *named[V]) UnmarshalJSON(b []byte) error {+ r := gjson.ParseBytes(b)+ if r.Type == gjson.Null {+ *n = nil+ return nil+ }+ if !r.IsObject() {+ return errNotObject+ }+ size := 0+ r.ForEach(func(_, _ gjson.Result) bool {+ size+++ return true+ })+ out := make(named[V], 0, size)+ var err error+ r.ForEach(func(k, v gjson.Result) bool {+ var val V+ if !quick(&val, v) {+ if err = json.Unmarshal(unsafe.Slice(unsafe.StringData(v.Raw), len(v.Raw)), &val); err != nil {+ return false+ }+ }+ *out.at(unique.Make(k.String()).Value()) = val+ return true+ })+ if err != nil {+ return err+ }+ *n = out+ return nil+}++// quick reads v into an int or Tokens without reflection when every number+// in it is a plain integer, as a cache magpie wrote has them; anything else+// is left to json.Unmarshal, and its errors.+func quick(val any, v gjson.Result) bool {+ switch p := val.(type) {+ case *int:+ n, ok := integer(v.Raw)+ *p = n+ return ok+ case *Tokens:+ if !v.IsObject() {+ return false+ }+ ok := true+ v.ForEach(func(k, f gjson.Result) bool {+ var at *int+ switch k.Raw {+ case `"input"`:+ at = &p.Input+ case `"output"`:+ at = &p.Output+ case `"cache_read"`:+ at = &p.CacheRead+ case `"cache_write"`:+ at = &p.CacheWrite+ case `"cache_write_1h"`:+ at = &p.CacheWrite1h+ default:+ ok = false+ return false+ }+ *at, ok = integer(f.Raw)+ return ok+ })+ if !ok {+ *p = Tokens{}+ }+ return ok+ }+ return false+}++// integer is s as an int when it is one written plainly: an optional minus+// and up to 18 digits, no leading zero.+func integer(s string) (int, bool) {+ neg := strings.HasPrefix(s, "-")+ if neg {+ s = s[1:]+ }+ if s == "" || len(s) > 18 || len(s) > 1 && s[0] == '0' {+ return 0, false+ }+ n := 0+ for i := range len(s) {+ c := s[i]+ if c < '0' || c > '9' {+ return 0, false+ }+ n = n*10 + int(c-'0')+ }+ if neg {+ n = -n+ }+ return n, true+}diff --git a/internal/sessions/named_test.go b/internal/sessions/named_test.gonew file mode 100644index 000000000..3848eaf77--- /dev/null+++ b/internal/sessions/named_test.go@@ -0,0 +1,65 @@+package sessions++import (+ "encoding/json"+ "testing"+)++// A parse's models, days and tools are written as the maps they were, byte+// for byte, so a cache saved before reads the same, and read back as they+// were written: a name given twice is its last, and a number that isn't an+// int fails the read as it failed into a map.+func TestNamedIsAMapInJSON(t *testing.T) {+ m := map[string]Tokens{"z<&>": {Input: 1, CacheWrite1h: 2}, "a": {Output: -3}, "mé": {}}+ var n named[Tokens]+ for k, v := range m {+ *n.at(k) = v+ }+ want, _ := json.Marshal(m)+ got, err := json.Marshal(n)+ if err != nil || string(got) != string(want) {+ t.Fatalf("named wrote %s, %v; a map writes %s", got, err, want)+ }+ var back named[Tokens]+ if err := json.Unmarshal(got, &back); err != nil || len(back) != len(m) {+ t.Fatalf("read back %v, %v", back, err)+ }+ for k, v := range m {+ if back.of(k) != v {+ t.Errorf("%q read back %+v, want %+v", k, back.of(k), v)+ }+ }++ var d struct {+ T named[int] `json:"t,omitempty"`+ M named[Tokens] `json:"m,omitempty"`+ }+ if err := json.Unmarshal([]byte(`{"t":{"b":1,"a":2,"b":3},"m":{"x":{"input":5,"extra":1}}}`), &d); err != nil {+ t.Fatal(err)+ }+ if len(d.T) != 2 || d.T.of("a") != 2 || d.T.of("b") != 3 || d.T[0].name != "a" {+ t.Errorf("tools read as %v, want a=2 b=3 in order", d.T)+ }+ if d.M.of("x") != (Tokens{Input: 5}) {+ t.Errorf("a field Tokens doesn't have read as %+v", d.M.of("x"))+ }+ if b, _ := json.Marshal(struct {+ T named[int] `json:"t,omitempty"`+ }{}); string(b) != `{}` {+ t.Errorf("none written as %s, want it left out", b)+ }++ for _, bad := range []string{`{"t":{"a":1.5}}`, `{"t":{"a":"1"}}`, `{"t":[1]}`, `{"m":{"x":{"input":1e3}}}`, `{"m":{"x":{"input":99999999999999999999}}}`} {+ var into struct {+ T named[int] `json:"t"`+ M named[Tokens] `json:"m"`+ }+ var asMap struct {+ T map[string]int `json:"t"`+ M map[string]Tokens `json:"m"`+ }+ if (json.Unmarshal([]byte(bad), &into) == nil) != (json.Unmarshal([]byte(bad), &asMap) == nil) {+ t.Errorf("%s: named and a map disagree on whether it reads", bad)+ }+ }+}diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.goindex cbe5719aa..7f41c5a8e 100644--- a/internal/sessions/sessions.go+++ b/internal/sessions/sessions.go@@ -198,10 +198,10 @@ type state struct {Convs []string `json:"convs,omitempty"` // the gateway's ids for its requests (dshConvs)Start time.Time `json:"start"`Last time.Time `json:"last"`- Models map[string]Tokens `json:"models,omitempty"`+ 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 map[string]*day `json:"days,omitempty"`+ Days named[*day] `json:"days,omitempty"`// Claude Code: the message last counted, whose later lines repeat it,// and the day it was counted onMsg string `json:"msg,omitempty"`@@ -237,7 +237,7 @@ type state struct {// 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 {- Models map[string]Tokens `json:"m,omitempty"`+ Models named[Tokens] `json:"m,omitempty"`// Active is milliseconds of work: the gaps between one line and the// next, each counted when shorter than idleGap and put on the later// line's day. A longer pause (lunch, the night, a session picked up@@ -253,8 +253,8 @@ type day struct {Replies int `json:"r,omitempty"`// Tools are the tool calls made, by the tool's name, and Skills the// skills called up, by the skill's (subagents' files included)- Tools map[string]int `json:"t,omitempty"`- Skills map[string]int `json:"k,omitempty"`+ Tools named[int] `json:"t,omitempty"`+ Skills named[int] `json:"k,omitempty"`}// tool counts a call of a tool, and of a skill when it calls one up; a@@ -265,16 +265,10 @@ func (s *state) tool(at time.Time, name, skill string) {}d := s.day(dateOf(at))if name != "" {- if d.Tools == nil {- d.Tools = map[string]int{}- }- d.Tools[name]+++ *d.Tools.at(name)++}if skill != "" {- if d.Skills == nil {- d.Skills = map[string]int{}- }- d.Skills[skill]+++ *d.Skills.at(skill)++}}@@ -290,15 +284,11 @@ func dateOf(t time.Time) string {}func (s *state) day(date string) *day {- if s.Days == nil {- s.Days = map[string]*day{}- }- d := s.Days[date]- if d == nil {- d = &day{}- s.Days[date] = d+ d := s.Days.at(date)+ if *d == nil {+ *d = &day{}}- return d+ return *d}// use counts a model's tokens, spent on a date.@@ -306,31 +296,18 @@ func (s *state) use(date, model string, t Tokens) {if t.zero() {return}- if s.Models == nil {- s.Models = map[string]Tokens{}- }- m := s.Models[model]- m.add(t)- s.Models[model] = m- d := s.day(date)- if d.Models == nil {- d.Models = map[string]Tokens{}- }- m = d.Models[model]- m.add(t)- d.Models[model] = m+ s.Models.at(model).add(t)+ s.day(date).Models.at(model).add(t)}// unuse takes back what use counted.func (s *state) unuse(date, model string, t Tokens) {- if m, ok := s.Models[model]; ok {- m.sub(t)- s.Models[model] = m+ if i, ok := s.Models.find(model); ok {+ s.Models[i].v.sub(t)}- if d := s.Days[date]; d != nil {- if m, ok := d.Models[model]; ok {- m.sub(t)- d.Models[model] = m+ if d := s.Days.of(date); d != nil {+ if i, ok := d.Models.find(model); ok {+ d.Models[i].v.sub(t)}}}@@ -361,10 +338,7 @@ func (s *state) clone() *state {c := *sc.Codex = s.Codex.clone()c.Claude = s.Claude.clone()- c.Models = make(map[string]Tokens, len(s.Models))- for k, v := range s.Models {- c.Models[k] = v- }+ c.Models = slices.Clone(s.Models)if s.Total != nil {t := *s.Totalc.Total = &t@@ -374,22 +348,15 @@ func (s *state) clone() *state {c.CodexSpawnConflicts = maps.Clone(s.CodexSpawnConflicts)c.CodexAgentIDs = maps.Clone(s.CodexAgentIDs)c.CodexAgentConflicts = maps.Clone(s.CodexAgentConflicts)- c.Days = make(map[string]*day, len(s.Days))- for k, v := range s.Days {- d := &day{Active: v.Active, Models: make(map[string]Tokens, len(v.Models)), Prompts: v.Prompts, Replies: v.Replies}+ c.Days = slices.Clone(s.Days)+ for i, e := range c.Days {+ v := e.v+ d := &day{Active: v.Active, Models: slices.Clone(v.Models), Prompts: v.Prompts, Replies: v.Replies}if v.Hours != nil {d.Hours = append([]int64(nil), v.Hours...)}- if v.Tools != nil {- d.Tools = maps.Clone(v.Tools)- }- if v.Skills != nil {- d.Skills = maps.Clone(v.Skills)- }- for m, t := range v.Models {- d.Models[m] = t- }- c.Days[k] = d+ d.Tools, d.Skills = slices.Clone(v.Tools), slices.Clone(v.Skills)+ c.Days[i].v = d}return &c}@@ -1350,7 +1317,7 @@ func assembleListed(fs []file, price func(string) *catalog.Price, codexTitle funif st.Last.After(s.Last) {s.Last = st.Last}- for name, t := range st.Models {+ for name, t := range st.Models.all() {m := models[name]if m == nil {m = &Model{Model: name}diff --git a/internal/sessions/stats.go b/internal/sessions/stats.goindex f944e8fd0..e417d85d3 100644--- a/internal/sessions/stats.go+++ b/internal/sessions/stats.go@@ -248,11 +248,11 @@ func statsRead(days int, now time.Time, native map[string]bool) Stats {if cwd == "" {cwd = st.Cwd}- for date, d := range st.Days {+ for date, d := range st.Days.all() {if date == "" || date < from || date > out.To {continue}- for model, t := range d.Models {+ for model, t := range d.Models.all() {if t.zero() {continue}@@ -291,7 +291,7 @@ func statsRead(days int, now time.Time, native map[string]bool) Stats {pd = &dayShare{tools: map[string]int{}}sh.perDate[date] = pd}- for model, t := range d.Models {+ for model, t := range d.Models.all() {if !t.zero() {u := sh.models[model]u.add(t)@@ -307,11 +307,11 @@ func statsRead(days int, now time.Time, native map[string]bool) Stats {dates[date] = true}pd.messages += d.Prompts + d.Replies- for name, n := range d.Tools {+ for name, n := range d.Tools.all() {sh.tools[name] += npd.tools[ToolCategory(name)] += n}- for name, n := range d.Skills {+ for name, n := range d.Skills.all() {sh.skills[name] += nif date > sh.skillLast[name] {sh.skillLast[name] = datediff --git a/internal/sessions/stats_test.go b/internal/sessions/stats_test.goindex 337dbdb3d..f7ea04149 100644--- a/internal/sessions/stats_test.go+++ b/internal/sessions/stats_test.go@@ -143,7 +143,7 @@ func TestStatsMidnight(t *testing.T) {// the same from the start, and from the parse kept on diskfull := parse(file{agent: "claude", path: path, main: true, size: int64(len(first + rest)), mod: time.Now()}, nil)- if got := full.Days["2026-09-21"].Models["claude-opus-5-5"]; got != after21 {+ if got := full.Days.of("2026-09-21").Models.of("claude-opus-5-5"); got != after21 {t.Fatalf("read whole: %+v", got)}Reset()diff --git a/internal/sessions/tail.go b/internal/sessions/tail.goindex 3ceb8553c..e8c9735dc 100644--- a/internal/sessions/tail.go+++ b/internal/sessions/tail.go@@ -57,21 +57,15 @@ func (s *state) dropUse(date, model string, t Tokens) {return}s.unuse(date, model, t)- if m, ok := s.Models[model]; ok && m.zero() {- delete(s.Models, model)- if len(s.Models) == 0 {- s.Models = nil- }+ if m, ok := s.Models.get(model); ok && m.zero() {+ s.Models.del(model)}- if d := s.Days[date]; d != nil {- if m, ok := d.Models[model]; ok && m.zero() {- delete(d.Models, model)- if len(d.Models) == 0 {- d.Models = nil- }+ if d := s.Days.of(date); d != nil {+ if m, ok := d.Models.get(model); ok && m.zero() {+ d.Models.del(model)}if len(d.Models) == 0 && d.Active == 0 && d.Hours == nil && d.Prompts == 0 && d.Replies == 0 && d.Tools == nil && d.Skills == nil {- delete(s.Days, date)+ s.Days.del(date)}}}