// The usage screen draws answers that look plausible when they are wrong, so // E2E cannot catch these: a day's name, off by one when it is read on the // terminal's own zone instead of the offset the daemon counted on; a share, // over 100% when a provider reports more cached input than input; today's total // beside today's models from a different read, which reads as one snapshot on // screen even when a call landed between the two requests; a provider named by // the endpoint it dialled; a count so large its cell drops the label saying // what it counts; and a scale that differs between two rows of one screen. package tui import ( "errors" "fmt" "net" "net/http" "net/http/httptest" "net/url" "strings" "testing" "time" "albedo/cli/internal/daemon" tea "charm.land/bubbletea/v2" "github.com/charmbracelet/x/ansi" ) // usageAnswer is one answer of GET /usage: the days it was asked for, read at // at on a clock offset minutes ahead of UTC. func usageAnswer(at time.Time, offset int, days []daemon.UsageDay, lines []daemon.UsageLine) daemon.UsageSummary { return daemon.UsageSummary{GeneratedAt: at, UTCOffsetMinutes: offset, Days: days, Lines: lines} } // usageScreen is a screen that has drawn these answers. func usageScreen(t *testing.T, today, week daemon.UsageSummary) UsageModel { t.Helper() m := NewUsageModel(nil) m.SetSize(100, 30) m, _ = m.Update(usageLoadedMsg{Gen: m.Generation, Today: today, Week: week}) return m } // usageFrom is the day d of October 2026 in UTC, with what it used. func usageFrom(d int, calls, in, out int64) daemon.UsageDay { return daemon.UsageDay{ Start: time.Date(2026, 10, d, 0, 0, 0, 0, time.UTC), UsageTotals: daemon.UsageTotals{Calls: calls, InputTokens: in, OutputTokens: out}, } } // usageBars is how many of a row's slots are filled. func usageBars(row listEntry) int { return strings.Count(ansi.Strip(row.tag), "▰") } func TestUsageDayNamesFollowTheOffsetTheDaemonAnsweredWith(t *testing.T) { // A clock nine hours ahead of UTC: its 25 October began at 15:00 UTC on the // 24th, so a day labelled by its UTC date reads a day early. at := time.Date(2026, 10, 25, 2, 0, 0, 0, time.UTC) week := []daemon.UsageDay{ {Start: time.Date(2026, 10, 22, 15, 0, 0, 0, time.UTC)}, {Start: time.Date(2026, 10, 23, 15, 0, 0, 0, time.UTC)}, {Start: time.Date(2026, 10, 24, 15, 0, 0, 0, time.UTC)}, } m := usageScreen(t, usageAnswer(at, 9*60, week[2:], nil), usageAnswer(at, 9*60, week, nil)) var names []string for _, row := range m.rows() { names = append(names, row.name) } if got := strings.Join(names, "|"); got != "today|yesterday|Fri 23 Oct" { t.Fatalf("day names = %q, want the client's own days, newest first", got) } } // usageCapabilities is what the fake daemon says it can serve, so the client // attaches: a read of usage needs usage_summary. const usageCapabilities = `{"instance_id":"instance-a","protocol":3,"state":"ready","capabilities":{"durable_inputs":1,"session_replay":2,"collection_invalidation":1,"tool_progress":1,"context":1,"catalog":1,"workspace_browsing":1,"host_probes":1,"provider_auth":1,"history_rewind":1,"storage_report":1,"usage_summary":1},"build":null,"digest":null,"extensions":[],"quota":null,"notices":[]}` // TestUsageReadsTheWeekBeforeTheDay drives the screen's own command against a // daemon whose two answers disagree, the way two reads a moment apart do: the // week's answer was read while today still had one call. func TestUsageReadsTheWeekBeforeTheDay(t *testing.T) { var asked []string totals := func(calls int) string { return fmt.Sprintf(`"calls":%d,"errors":0,"input_tokens":%d,"cached_input_tokens":0,"cache_creation_tokens":0,"output_tokens":%d,"reasoning_tokens":0`, calls, calls*100, calls*10) } server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/server" { fmt.Fprint(w, usageCapabilities) return } asked = append(asked, r.URL.Query().Get("days")+"/"+r.URL.Query().Get("utc_offset_minutes")) calls := 1 if r.URL.Query().Get("days") == "1" { calls = 2 } fmt.Fprintf(w, `{"generated_at":"2026-10-25T18:00:00Z","utc_offset_minutes":0,"days":[{"start":"2026-10-25T00:00:00Z",%s}],"lines":[{"profile":"work","provider":"claude","account":null,"model":"example-large",%s}],"scopes":[],"lines_truncated":false,"scopes_truncated":false}`, totals(calls), totals(calls)) })) defer server.Close() conn, err := daemon.Attach(t.Context(), daemon.ConnectionSnapshot{Port: server.Listener.Addr().(*net.TCPAddr).Port, Token: "t", Version: daemon.ProtocolVersion}, nil) if err != nil { t.Fatal(err) } defer conn.HTTPClient().CloseIdleConnections() m := NewUsageModel(conn) msg, ok := m.Init()().(usageLoadedMsg) if !ok || msg.Err != nil { t.Fatalf("the read failed: %v", msg.Err) } m, _ = m.Update(msg) if len(asked) != 2 || !strings.HasPrefix(asked[0], "7/") || !strings.HasPrefix(asked[1], "1/") { t.Fatalf("asked %v, want the week first and then the day", asked) } if offset := strings.Split(asked[0], "/")[1]; offset != strings.Split(asked[1], "/")[1] { t.Fatalf("the two reads were counted on different clocks: %v", asked) } rows := m.rows() if len(rows) != 2 { t.Fatalf("rows = %d, want the model and today", len(rows)) } if rows[1].name != "today" { t.Fatalf("second row = %q, want today", rows[1].name) } if detail := strings.Join(rows[1].detail(80), " "); !strings.Contains(detail, "2 calls") { t.Fatalf("today's total = %q, want the calls its own answer counted", detail) } if detail := strings.Join(rows[0].detail(80), " "); !strings.Contains(detail, "2 calls") { t.Fatalf("the model = %q, want the calls of the answer it came from", detail) } } func TestUsageTodayIsOneAnswerWithItsModels(t *testing.T) { at := time.Date(2026, 10, 25, 18, 0, 0, 0, time.UTC) // The week was read while today still had one call; a second call landed // before the day's own answer, which lists the model that made both. week := usageAnswer(at, 0, []daemon.UsageDay{usageFrom(19, 4, 40, 4), usageFrom(20, 5, 50, 5), usageFrom(25, 1, 10, 1)}, nil) today := usageAnswer(at, 0, []daemon.UsageDay{usageFrom(25, 2, 20, 2)}, []daemon.UsageLine{ {Profile: "work", Provider: "claude", Model: "example-large", UsageTotals: daemon.UsageTotals{Calls: 2, InputTokens: 20, OutputTokens: 2}}, }) m := usageScreen(t, today, week) rows := m.rows() if len(rows) != 4 { t.Fatalf("rows = %d, want the model and the three days it was read over", len(rows)) } if detail := strings.Join(rows[0].detail(80), " "); !strings.Contains(detail, "2 calls") { t.Fatalf("the model's answer = %q, want the 2 calls it was read with", detail) } if rows[1].name != "today" { t.Fatalf("second row = %q, want today", rows[1].name) } if detail := strings.Join(rows[1].detail(80), " "); !strings.Contains(detail, "2 calls") { t.Fatalf("today's total = %q, want the call its own answer counted, not the week's older one", detail) } if rows[2].name == "today" || rows[3].name == "today" { t.Fatalf("days = %q, %q, want the closed days behind today", rows[2].name, rows[3].name) } } func TestUsageDaysStayAWeekWhenMidnightFallsBetweenTheReads(t *testing.T) { at := time.Date(2026, 10, 25, 0, 0, 30, 0, time.UTC) var week []daemon.UsageDay for d := 18; d <= 24; d++ { week = append(week, usageFrom(d, 1, 10, 1)) } // The week was read just before midnight, when the 24th was today, and the // day just after it: the week's own last day is then yesterday. m := usageScreen(t, usageAnswer(at, 0, []daemon.UsageDay{usageFrom(25, 1, 10, 1)}, nil), usageAnswer(at, 0, week, nil)) days := m.days() if len(days) != usageDays { t.Fatalf("days = %d, want the %d a week holds", len(days), usageDays) } if got := m.dayName(days[0].start); got != "today" { t.Fatalf("newest day = %q, want today", got) } if got := m.dayName(days[1].start); got != "yesterday" { t.Fatalf("second day = %q, want yesterday", got) } if want := time.Date(2026, 10, 19, 0, 0, 0, 0, time.UTC); !days[len(days)-1].start.Equal(want) { t.Fatalf("oldest day = %s, want %s: the week ends today, whatever clock each answer was read on", days[len(days)-1].start, want) } } func TestUsageBarsShareOneScale(t *testing.T) { // A model is small beside the week's busiest day, and a bar is read against // the bars around it, so both sections share that day's scale. at := time.Date(2026, 10, 25, 18, 0, 0, 0, time.UTC) week := usageAnswer(at, 0, []daemon.UsageDay{usageFrom(23, 40, 1_000_000, 0), usageFrom(24, 4, 4_000, 0), usageFrom(25, 3, 10_000, 0)}, nil) today := usageAnswer(at, 0, []daemon.UsageDay{usageFrom(25, 3, 10_000, 0)}, []daemon.UsageLine{ {Profile: "work", Provider: "claude", Model: "example-large", UsageTotals: daemon.UsageTotals{Calls: 3, InputTokens: 10_000}}, }) rows := usageScreen(t, today, week).rows() if got := usageBars(rows[0]); got != 1 { t.Fatalf("the week's busiest model filled %d of %d slots, want one of the week's scale", got, usageBarSlots) } if got := usageBars(rows[len(rows)-1]); got != usageBarSlots { t.Fatalf("the week's busiest day filled %d of %d slots, want all of them", got, usageBarSlots) } } // The ledger records a pooled account as the uuid the provider minted, and // ollama as the name of its own profile, so a row that shows the account entire // names nobody, or says what the row already said. The web client names these // rows the same way (`lineWho` in web/src/lib/usage.ts), and the cases here are // its cases. func TestUsageWhoNamesAnAccountOnlyWhenItSaysSomething(t *testing.T) { const ( uuid = "df3eba1d-874a-4762-8d64-7e2feb475634" other = "0a1b2c3d-0000-4000-8000-000000000000" hash = "1ba6a50e45eecfdf" email = "me@example.com" codex = "responses:https://chatgpt.com/backend-api" ollama = "chat_completions:https://ollama.com/v1" ) line := func(profile, provider, account string) daemon.UsageLine { return daemon.UsageLine{Profile: profile, Provider: provider, Account: account, Model: "example-large"} } none, named := line("ollama", ollama, ""), line("ollama", ollama, "ollama") pool := []daemon.UsageLine{ line("codex", codex, uuid), line("codex", codex, other), line("codex", codex, email), none, named, } cases := []struct { name string line daemon.UsageLine lines []daemon.UsageLine want string }{ // An id alone under its profile is left off, not cut: it tells a reader nothing. {"a lone uuid", line("codex", codex, uuid), []daemon.UsageLine{line("codex", codex, uuid)}, "codex"}, {"a lone hash", line("codex", codex, hash), []daemon.UsageLine{line("codex", codex, hash)}, "codex"}, // Another profile's accounts never make this one's several. {"a lone uuid beside a pooled profile", line("home", codex, uuid), append(pool, line("home", codex, uuid)), "home"}, // Two accounts of one profile cannot be told apart without the account, // so an id says as much of itself as tells them apart. {"a uuid of several", pool[0], pool, "codex · df3eba"}, {"the other uuid of several", pool[1], pool, "codex · 0a1b2c"}, // An email names someone, so it is never cut and never left off. {"an email", line("work", codex, email), []daemon.UsageLine{line("work", codex, email)}, "work · me@example.com"}, {"an email beside a uuid", pool[2], pool, "codex · me@example.com"}, // An account named after its own profile says nothing new, which leaves // the row recorded with no account saying that much instead. {"an account named after its profile", named, []daemon.UsageLine{none, named}, "ollama"}, {"no account beside it", none, []daemon.UsageLine{none, named}, "ollama · no account"}, // A profile's single row has nothing to be told apart from. {"the only account is no account", line("home", codex, ""), []daemon.UsageLine{line("home", codex, "")}, "home"}, } for _, c := range cases { if got := usageWho(c.line, c.lines); got != c.want { t.Errorf("%s: usageWho = %q, want %q", c.name, got, c.want) } } } // The rule reaches the screen it is for: the rows say who, and so does the pane, // which is where a whole account was shown. func TestUsageRowsAndPaneNameTheAccountTheSameWay(t *testing.T) { const ( uuid = "df3eba1d-874a-4762-8d64-7e2feb475634" other = "0a1b2c3d-0000-4000-8000-000000000000" codex = "responses:https://chatgpt.com/backend-api" ollama = "chat_completions:https://ollama.com/v1" ) at := time.Date(2026, 10, 25, 18, 0, 0, 0, time.UTC) lines := []daemon.UsageLine{ {Profile: "codex", Provider: codex, Account: uuid, Model: "example-large", UsageTotals: daemon.UsageTotals{Calls: 2, InputTokens: 20, OutputTokens: 2}}, {Profile: "codex", Provider: codex, Account: other, Model: "example-large", UsageTotals: daemon.UsageTotals{Calls: 1, InputTokens: 10, OutputTokens: 1}}, {Profile: "ollama", Provider: ollama, Model: "example-mini", UsageTotals: daemon.UsageTotals{Calls: 1, InputTokens: 10, OutputTokens: 1}}, {Profile: "ollama", Provider: ollama, Account: "ollama", Model: "example-mini", UsageTotals: daemon.UsageTotals{Calls: 1, InputTokens: 10, OutputTokens: 1}}, } m := usageScreen(t, usageAnswer(at, 0, []daemon.UsageDay{usageFrom(25, 5, 50, 5)}, lines), usageAnswer(at, 0, []daemon.UsageDay{usageFrom(25, 5, 50, 5)}, nil)) want := []string{"codex · df3eba", "codex · 0a1b2c", "ollama · no account", "ollama"} rows := m.rows() if len(rows) < len(want) { t.Fatalf("rows = %d, want the four models and then the days", len(rows)) } for i, who := range want { if rows[i].desc != who { t.Errorf("row %d says %q, want %q", i, rows[i].desc, who) } provider := "ChatGPT" if i > 1 { provider = "Ollama" } if detail := ansi.Strip(strings.Join(rows[i].detail(80), " ")); !strings.Contains(detail, who+" · "+provider) { t.Errorf("row %d's pane = %q, want it to say %q", i, detail, who+" · "+provider) } } } func TestUsageShareIsWithheldWhenThePartExceedsTheWhole(t *testing.T) { // A provider that counts cache reads outside its input reports more cached // tokens than input tokens; the count is still worth saying, the share is // not, because the providers disagree about what the whole is. if got := usageShare(240, 200, "cached"); got != " · 240 cached" { t.Fatalf("a part larger than its whole should have no share, got %q", got) } if got := usageShare(240, 960, "cached"); !strings.HasSuffix(got, "(25%)") { t.Fatalf("a part inside its whole should have its share, got %q", got) } } func TestUsageFailedRefreshKeepsTheRowsAndSaysHowOldTheyAre(t *testing.T) { at := time.Date(2026, 10, 25, 18, 0, 0, 0, time.UTC) m := usageScreen(t, usageAnswer(at, 0, []daemon.UsageDay{usageFrom(25, 2, 20, 2)}, nil), usageAnswer(at, 0, []daemon.UsageDay{usageFrom(24, 1, 10, 1), usageFrom(25, 2, 20, 2)}, nil)) dial := &url.Error{Op: "Get", URL: "http://127.0.0.1:4318/usage?days=1", Err: errors.New("dial tcp 127.0.0.1:4318: connect: connection refused")} m, _ = m.Update(usageLoadedMsg{Gen: m.Generation, Err: usageError{dial}}) view := ansi.Strip(m.View()) // The header says how old the rows are and the footer why they could not be // refreshed, which leaves the footer its row for every hint. if !strings.Contains(strings.SplitN(view, "\n", 2)[0], "as of 18:00") { t.Fatalf("the header does not say how old the rows are:\n%s", view) } for _, want := range []string{usageUnreachable, "retry"} { if !strings.Contains(view, want) { t.Fatalf("the failed refresh's screen lacks %q:\n%s", want, view) } } // A refresh that cannot reach the daemon reads like a load that could not, // and the transport's sentence names a socket, which tells a reader nothing. for _, unwanted := range []string{"dial tcp", "127.0.0.1"} { if strings.Contains(view, unwanted) { t.Fatalf("the failed refresh's screen shows %q:\n%s", unwanted, view) } } if len(m.rows()) == 0 { t.Fatal("a failed refresh blanked the rows it had drawn") } } func TestUsageBreakdownStandsInWithoutThePane(t *testing.T) { // A terminal narrower than the pane and too short to stack it: the // highlighted row's counts are the breakdown, and losing them leaves the // screen saying only that something was used. at := time.Date(2026, 10, 25, 18, 0, 0, 0, time.UTC) answers := usageAnswer(at, 0, []daemon.UsageDay{usageFrom(24, 0, 0, 0), usageFrom(25, 12, 96_000, 4_000)}, []daemon.UsageLine{ {Profile: "work", Provider: "claude", Model: "example-large", UsageTotals: daemon.UsageTotals{Calls: 12, InputTokens: 96_000, OutputTokens: 4_000}}, }) m := NewUsageModel(nil) m.SetSize(80, 17) m, _ = m.Update(usageLoadedMsg{Gen: m.Generation, Today: answers, Week: answers}) if view := ansi.Strip(m.View()); !strings.Contains(view, "12 calls · 96k in · 4k out") { t.Fatalf("a terminal with no room for the pane lost the highlighted row's counts:\n%s", view) } // The idle day below it has nothing to add to its row, and an empty summary // would still take a line. for range 2 { m, _ = m.Update(tea.KeyPressMsg{Code: tea.KeyDown}) } if got := m.summary(); got != "" { t.Fatalf("an idle day's summary = %q, want none", got) } }