From e7ff3be6fdd882e166459ad1e123b90e43a0e5df Mon Sep 17 00:00:00 2001 From: Riley Crane Date: Fri, 13 Nov 2026 11:37:15 -0800 Subject: [PATCH 1/6] feat(bestie): show the last 7 days of cost in the Bestie tab Add a Cost row to the Bestie tab: a daily sparkline, the week's total and Open Usage, which opens Settings -> Usage. The numbers are estimates from the agent type's own `usage` read, priced as the Usage plugin prices them, and are computed when the tab opens. Nothing is stored or synced. An agent whose type reports no usage, or that runs elsewhere, shows the row as not available. A read that fails shows a quiet message with Retry. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Riley Crane --- docs/buzz-help.md | 5 +- src/bundled/bestie/BestieTab.test.tsx | 105 +++++++++++------- src/bundled/bestie/BestieTab.tsx | 27 ++++- src/bundled/bestie/CostRow.test.tsx | 148 ++++++++++++++++++++++++++ src/bundled/bestie/CostRow.tsx | 132 +++++++++++++++++++++++ src/bundled/bestie/README.md | 12 +++ src/bundled/bestie/cost.ts | 49 +++++++++ src/bundled/bestie/index.tsx | 6 +- 8 files changed, 441 insertions(+), 43 deletions(-) create mode 100644 src/bundled/bestie/CostRow.test.tsx create mode 100644 src/bundled/bestie/CostRow.tsx create mode 100644 src/bundled/bestie/cost.ts diff --git a/docs/buzz-help.md b/docs/buzz-help.md index bfda636962..0fbb1eb607 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -1286,7 +1286,10 @@ available rather than silently discarding it. the confirmation offers another attempt. A Bestie on another device has no Bestie tab on this one. A hosted Bestie whose provider holds its instructions (Builderlab does) has the tab and can use **Remembers you**; hosted agents - cannot use Bestie's Attention check-ins. + cannot use Bestie's Attention check-ins. The tab's **Cost** row shows an + estimate of what a local Bestie's sessions on this computer cost over the + last 7 days, with **Open Usage**. It is not a bill, and it says when the + agent's type reports no usage or the agent runs elsewhere. - An agent running on this device can also show, change or remove your Bestie when you ask it to. It saves to this device and your account, as the menu does, and accepts only your agents you can tag in this community. It also diff --git a/src/bundled/bestie/BestieTab.test.tsx b/src/bundled/bestie/BestieTab.test.tsx index db5c9bc33b..011ef52bb0 100644 --- a/src/bundled/bestie/BestieTab.test.tsx +++ b/src/bundled/bestie/BestieTab.test.tsx @@ -45,6 +45,7 @@ const member = (name: string, digit: string): Agent => }) as unknown as Agent; const ada = member("Ada", "a"); const bea = member("Bea", "b"); +const navigation = { open: vi.fn(async () => ({ status: "opened" })) } as never; /** Agents that save as a synced editor would: the agent's next config. * `listed` are the agents it finds, Ada and Bea, both on this device. */ @@ -124,7 +125,7 @@ function community(saved: string | null | undefined, agents = [ada, bea]) { it("shows on the saved Bestie only, and moves when Change picks another", async () => { const user = userEvent.setup(); const { relay, mainAgent } = community(ada.pubkey); - const tab = bestieTab(relay, host([]).agents); + const tab = bestieTab(relay, host([]).agents, navigation); const changed = vi.fn(); const stop = tab.subscribe?.(changed); // Nothing shows before the account's choice is read. @@ -159,6 +160,28 @@ it("shows on the saved Bestie only, and moves when Change picks another", async stop?.(); }); +it("shows the Bestie's cost for the week, without a failed read stopping the tab", async () => { + const { relay } = community(ada.pubkey); + const usage = vi.fn().mockRejectedValue(new Error("unreadable")); + const agents = { + ...host().agents, + types: () => [{ key: "test/echo", adopt: () => ({}), usage }], + } as unknown as Parameters[1]; + const tab = bestieTab(relay, agents, navigation); + const stop = tab.subscribe?.(() => {}); + await vi.waitFor(() => expect(tab.when?.(ada)).toBe(true)); + const Tab = tab.component; + render(); + expect(await screen.findByText("Cost, last 7 days")).toBeVisible(); + expect( + await screen.findByText("Couldn't read this agent's sessions."), + ).toBeVisible(); + // The rest of the tab is where it was. + expect(screen.getByText("This is your Bestie")).toBeVisible(); + expect(usage).toHaveBeenCalledTimes(1); + stop?.(); +}); + const deviceChoice = () => readView(SCOPE, "solo:default-agent", null); /** Opens Change and confirms Bea in place of Ada. */ @@ -178,7 +201,7 @@ it("puts this device back on the account's Bestie when a failed Change is closed const user = userEvent.setup(); const { relay, mainAgent } = community(ada.pubkey); mainAgent.write.mockRejectedValueOnce(new Error("offline")); - const tab = bestieTab(relay, host([]).agents); + const tab = bestieTab(relay, host([]).agents, navigation); const stop = tab.subscribe?.(() => {}); await vi.waitFor(() => expect(tab.when?.(ada)).toBe(true)); const Tab = tab.component; @@ -196,7 +219,7 @@ it("keeps the Bestie an agent saved when its tab closes over a failed Change", a const user = userEvent.setup(); const { relay, mainAgent } = community(ada.pubkey); mainAgent.write.mockRejectedValueOnce(new Error("offline")); - const tab = bestieTab(relay, host([]).agents); + const tab = bestieTab(relay, host([]).agents, navigation); const subscribe = tab.subscribe ?? (() => () => {}); const stop = subscribe(() => {}); await vi.waitFor(() => expect(tab.when?.(ada)).toBe(true)); @@ -228,7 +251,7 @@ it("puts this device back when a Change still saving fails after the panel close fail = reject; }), ); - const tab = bestieTab(relay, host([]).agents); + const tab = bestieTab(relay, host([]).agents, navigation); const stop = tab.subscribe?.(() => {}); await vi.waitFor(() => expect(tab.when?.(ada)).toBe(true)); const Tab = tab.component; @@ -245,7 +268,11 @@ it("offers a remote agent in Change, and says what it can't do before switching" const user = userEvent.setup(); const cara = { ...member("Cara", "c"), place: "hosted" } as Agent; const { relay, mainAgent } = community(ada.pubkey, [ada, bea, cara]); - const Tab = bestieTab(relay, host([], [ada, bea, cara]).agents).component; + const Tab = bestieTab( + relay, + host([], [ada, bea, cara]).agents, + navigation, + ).component; await act(async () => { render(); }); @@ -269,7 +296,7 @@ it("offers a remote agent in Change, and says what it can't do before switching" it("says nothing of remote agents when switching to one on this device", async () => { const user = userEvent.setup(); const { relay } = community(ada.pubkey); - const Tab = bestieTab(relay, host([]).agents).component; + const Tab = bestieTab(relay, host([]).agents, navigation).component; await act(async () => { render(); }); @@ -289,7 +316,7 @@ it("shows a hosted Bestie's switches as unavailable when its provider has no ins } as Agent; const { relay } = community(ada.pubkey); const { agents, save } = host(["block.builderlab/builderlab"], [remote, bea]); - const Tab = bestieTab(relay, agents).component; + const Tab = bestieTab(relay, agents, navigation).component; await act(async () => { render(); }); @@ -339,7 +366,7 @@ function hostedBestie(text: string) { it("shows a hosted Bestie's tab, not one on another device's", async () => { const { relay } = community(ada.pubkey); - const tab = bestieTab(relay, host().agents); + const tab = bestieTab(relay, host().agents, navigation); const stop = tab.subscribe?.(() => {}); await vi.waitFor(() => expect(tab.when?.(ada)).toBe(true)); stop?.(); @@ -351,7 +378,7 @@ it("turns a hosted Bestie's memory on and off through its provider, and never to const user = userEvent.setup(); const { relay } = community(ada.pubkey); const { remote, agents, save, get, set } = hostedBestie("Be brief."); - const Tab = bestieTab(relay, agents).component; + const Tab = bestieTab(relay, agents, navigation).component; await act(async () => { render(); }); @@ -384,7 +411,7 @@ it("never replaces a hosted Bestie's instructions edited elsewhere since the tab const user = userEvent.setup(); const { relay } = community(ada.pubkey); const { remote, agents, get, set, editElsewhere } = hostedBestie("Be brief."); - const Tab = bestieTab(relay, agents).component; + const Tab = bestieTab(relay, agents, navigation).component; await act(async () => { render(); }); @@ -414,7 +441,7 @@ it("says why a hosted Bestie's instructions can't be read or saved, and lets eit const { relay } = community(ada.pubkey); const { remote, agents, get, set } = hostedBestie("Be brief."); get.mockRejectedValueOnce(new Error("Builderlab is down.")); - const Tab = bestieTab(relay, agents).component; + const Tab = bestieTab(relay, agents, navigation).component; await act(async () => { render(); }); @@ -440,7 +467,7 @@ it("says why a hosted Bestie's instructions can't be read or saved, and lets eit it("keeps Change unavailable while there is no other agent to choose", async () => { const { relay } = community(ada.pubkey, [ada]); - const Tab = bestieTab(relay, host().agents).component; + const Tab = bestieTab(relay, host().agents, navigation).component; await act(async () => { render(); }); @@ -456,7 +483,11 @@ it("asks before making a remote former Bestie your Bestie again, and Cancel chan place: "elsewhere", config: { instructions: withFeature("Be brief.", memory, true) }, } as Agent; - const Tab = formerBestieTab(relay, host([], [bea, remote]).agents).component; + const Tab = formerBestieTab( + relay, + host([], [bea, remote]).agents, + navigation, + ).component; await act(async () => { render(); }); @@ -486,7 +517,7 @@ it("asks before making a remote former Bestie your Bestie again, and Cancel chan it("tells the host only when the Bestie or its community changes", async () => { const { relay, reconnect } = community(ada.pubkey); - const tab = bestieTab(relay, host([]).agents); + const tab = bestieTab(relay, host([]).agents, navigation); const changed = vi.fn(); const stop = tab.subscribe?.(changed); await vi.waitFor(() => expect(tab.when?.(ada)).toBe(true)); @@ -505,7 +536,7 @@ it("turns memory on and off as a marked section of the instructions", async () = const user = userEvent.setup(); const { relay } = community(ada.pubkey); const { agents, save } = host(); - const Tab = bestieTab(relay, agents).component; + const Tab = bestieTab(relay, agents, navigation).component; const base = { instructions: "head-1" }; const agent = { ...ada, @@ -550,7 +581,7 @@ it("keeps memory on through the owner's edits, and offers Restore for edited mar const user = userEvent.setup(); const { relay } = community(ada.pubkey); const { agents, save } = host(); - const Tab = bestieTab(relay, agents).component; + const Tab = bestieTab(relay, agents, navigation).component; const base = { instructions: "head-2" }; const on = withFeature("Be brief.", memory, true); const close = ""; @@ -596,7 +627,7 @@ it("says why a save failed and lets the switch be tried again", async () => { const { relay } = community(ada.pubkey); const { agents, save } = host(); save.mockRejectedValueOnce(new Error("Connect to the community to save")); - const Tab = bestieTab(relay, agents).component; + const Tab = bestieTab(relay, agents, navigation).component; render(); const remembers = screen.getByRole("switch", { name: "Remembers you" }); await user.click(remembers); @@ -614,7 +645,7 @@ it("says why a save failed and lets the switch be tried again", async () => { it("offers no switch while the agent's instructions can't be read here", () => { const { relay } = community(ada.pubkey); const { agents, save } = host(); - const Tab = bestieTab(relay, agents).component; + const Tab = bestieTab(relay, agents, navigation).component; render( ); const hourly = screen.getByRole("switch", { name: "Hourly notes" }); save.mockRejectedValueOnce(new Error("Connect to the community to save")); @@ -806,7 +837,7 @@ it("offers to remove what is left of a check-in whose Interest or timer is gone" const user = userEvent.setup(); const { relay } = community(ada.pubkey); const { agents, save } = host(); - const Tab = bestieTab(relay, agents).component; + const Tab = bestieTab(relay, agents, navigation).component; const left = (slug: string, value: object) => ({ ...remembering(true), @@ -842,7 +873,7 @@ it("says a check-in paused in Attention is paused, and how to restart it", async const user = userEvent.setup(); const { relay } = community(ada.pubkey); const { agents, save } = host(); - const Tab = bestieTab(relay, agents).component; + const Tab = bestieTab(relay, agents, navigation).component; const paused = { ...remembering(true), attention: { @@ -869,7 +900,7 @@ it("says a check-in paused in Attention is paused, and how to restart it", async it("shows a Former Bestie tab while a former Bestie has a setting on, with a way back", async () => { const user = userEvent.setup(); const { relay, mainAgent } = community(bea.pubkey); - const tab = formerBestieTab(relay, host().agents); + const tab = formerBestieTab(relay, host().agents, navigation); const remembering = { ...ada, config: { instructions: withFeature("Be brief.", memory, true) }, @@ -916,8 +947,8 @@ it("removes the Bestie after asking, and shows the agent as a Former Bestie", as const user = userEvent.setup(); const { relay, mainAgent } = community(ada.pubkey); const agents = host().agents; - const tab = bestieTab(relay, agents); - const former = formerBestieTab(relay, agents); + const tab = bestieTab(relay, agents, navigation); + const former = formerBestieTab(relay, agents, navigation); const remembering = { ...ada, config: { instructions: withFeature("Be brief.", memory, true) }, @@ -968,7 +999,7 @@ it("shows a hosted former Bestie's Former Bestie tab while its memory is on, rea const { remote, agents, get, set, save } = hostedBestie( withFeature("Be brief.", memory, true), ); - const tab = formerBestieTab(relay, agents); + const tab = formerBestieTab(relay, agents, navigation); const listener = vi.fn(); const stop = tab.subscribe?.(listener); // Its instructions aren't on this device until its provider is read. @@ -1022,7 +1053,7 @@ it("keeps a hosted former Bestie's tab when an older background read ends after const user = userEvent.setup(); const { relay } = community(bea.pubkey); const { remote, agents, get } = hostedBestie("Be brief."); - const tab = formerBestieTab(relay, agents); + const tab = formerBestieTab(relay, agents, navigation); const stop = tab.subscribe?.(() => {}); await vi.waitFor(() => expect(tab.when?.(bea)).toBe(false)); // The background read starts while memory is off, and answers late. @@ -1055,7 +1086,7 @@ it("keeps a hosted former Bestie's tab when an older background read ends after it("keeps a hosted former Bestie's tab while a newer read is under way, whatever an older one answers", async () => { const { relay } = community(bea.pubkey); const { remote, agents } = hostedBestie("Be brief."); - const tab = formerBestieTab(relay, agents); + const tab = formerBestieTab(relay, agents, navigation); const stop = tab.subscribe?.(() => {}); await vi.waitFor(() => expect(tab.when?.(bea)).toBe(false)); // A failed read shows the tab, which reads again when it opens. @@ -1081,7 +1112,7 @@ it("keeps a hosted former Bestie's tab while a newer read is under way, whatever it("counts an older read's answer once a newer read is abandoned, from the moment it aborts", async () => { const { relay } = community(bea.pubkey); const { remote, agents } = hostedBestie("Be brief."); - const tab = formerBestieTab(relay, agents); + const tab = formerBestieTab(relay, agents, navigation); const stop = tab.subscribe?.(() => {}); await vi.waitFor(() => expect(tab.when?.(bea)).toBe(false)); const remembering = withFeature("Be brief.", memory, true); @@ -1112,7 +1143,7 @@ it("shows a hosted former Bestie's tab from a background read that answers after const { remote, agents, get } = hostedBestie( withFeature("Be brief.", memory, true), ); - const tab = formerBestieTab(relay, agents); + const tab = formerBestieTab(relay, agents, navigation); const stop = tab.subscribe?.(() => {}); await vi.waitFor(() => expect(tab.when?.(bea)).toBe(false)); let answer = (_text: string) => {}; @@ -1161,7 +1192,7 @@ it("shows a Former Bestie tab for a hosted agent its provider holds no instructi let list = listed([OWNER, remote.pubkey]); session.channels.list = () => list; writeView(SCOPE, "bestie:former", [ada.pubkey]); - const tab = formerBestieTab(relay, agents); + const tab = formerBestieTab(relay, agents, navigation); const stop = tab.subscribe?.(() => {}); await vi.waitFor(() => expect(tab.when?.(remote)).toBe(true)); const Tab = tab.component; @@ -1184,7 +1215,7 @@ it("keeps a hosted former Bestie's tab after a failed read, until a read shows n const user = userEvent.setup(); const { relay } = community(bea.pubkey); const { remote, agents, get } = hostedBestie("Be brief."); - const tab = formerBestieTab(relay, agents); + const tab = formerBestieTab(relay, agents, navigation); const stop = tab.subscribe?.(() => {}); await vi.waitFor(() => expect(tab.when?.(bea)).toBe(false)); get.mockRejectedValueOnce(new Error("Builderlab is down.")); @@ -1208,7 +1239,7 @@ it("keeps a hosted former Bestie's tab when memory saved on but reading it back const user = userEvent.setup(); const { relay } = community(bea.pubkey); const { remote, agents, get, set } = hostedBestie("Be brief."); - const tab = formerBestieTab(relay, agents); + const tab = formerBestieTab(relay, agents, navigation); const stop = tab.subscribe?.(() => {}); await vi.waitFor(() => expect(tab.when?.(bea)).toBe(false)); const Tab = tab.component; @@ -1236,7 +1267,7 @@ it("keeps a hosted former Bestie's tab when memory saved on but reading it back it("shows no Former Bestie tab while the account's choice is unread or unreadable", async () => { const { relay, mainAgent } = community(undefined); mainAgent.read.mockRejectedValueOnce(new Error("offline")); - const former = formerBestieTab(relay, host().agents); + const former = formerBestieTab(relay, host().agents, navigation); const remembering = { ...ada, config: { instructions: withFeature("Be brief.", memory, true) }, @@ -1257,7 +1288,7 @@ it("shows a Former Bestie tab on an account that saved none, not on one with no [null, true], ] as const) { const { relay, mainAgent } = community(record); - const former = formerBestieTab(relay, host().agents); + const former = formerBestieTab(relay, host().agents, navigation); const stop = former.subscribe?.(() => {}); await act(async () => {}); expect(mainAgent.read).toHaveBeenCalled(); @@ -1273,7 +1304,7 @@ it("offers no Remove without an account to save none to", async () => { delete (relay.snapshot() as { session: { mainAgent?: unknown } }).session .mainAgent; setDefaultAgent(SCOPE, ada.pubkey); - const Tab = bestieTab(relay, host().agents).component; + const Tab = bestieTab(relay, host().agents, navigation).component; await act(async () => { render(); }); @@ -1285,7 +1316,7 @@ it("lets a former Bestie's leftover check-in be turned off", async () => { const user = userEvent.setup(); const { relay } = community(bea.pubkey); const { agents, save } = host(); - const Tab = formerBestieTab(relay, agents).component; + const Tab = formerBestieTab(relay, agents, navigation).component; const checking = { ...ada, config: { instructions: withFeature("Be brief.", memory, true) }, diff --git a/src/bundled/bestie/BestieTab.tsx b/src/bundled/bestie/BestieTab.tsx index 277ba80cb9..d08989253d 100644 --- a/src/bundled/bestie/BestieTab.tsx +++ b/src/bundled/bestie/BestieTab.tsx @@ -5,6 +5,7 @@ import type { AgentAddedTab, Agents, } from "../../features/agents/service"; +import type { Navigation } from "../../features/navigation/controller"; import { useRelayConnection } from "../../features/relay/react"; import type { RelayData } from "../../features/relay/service"; import type { RelaySession } from "../../features/relay/session"; @@ -23,6 +24,7 @@ import { PreferenceRow } from "../../shared/design-system/ui/PreferenceRow"; import { SettingsGroup } from "../../shared/design-system/ui/SettingsGroup"; import { SwitchPreferenceRow } from "../../shared/design-system/ui/SwitchPreferenceRow"; import { bestieName, useBestieChoice } from "../agents/BestieChoice"; +import { CostRow } from "./CostRow"; import { FEATURES, type Feature, @@ -50,7 +52,11 @@ import { inCommunity, savedBestie } from "./saved"; type TabAgents = FeatureAgents & Pick; /** The Bestie tab, on the agent saved as Bestie in its community. */ -export function bestieTab(relay: RelayData, agents: TabAgents): AgentAddedTab { +export function bestieTab( + relay: RelayData, + agents: TabAgents, + navigation: Pick, +): AgentAddedTab { const bestie = savedBestie(relay); return { id: "bestie", @@ -62,7 +68,12 @@ export function bestieTab(relay: RelayData, agents: TabAgents): AgentAddedTab { inCommunity(agent, relay.snapshot()), subscribe: bestie.subscribe, component: ({ agent }) => ( - + ), }; } @@ -74,6 +85,7 @@ export function bestieTab(relay: RelayData, agents: TabAgents): AgentAddedTab { export function formerBestieTab( relay: RelayData, agents: TabAgents, + navigation: Pick, ): AgentAddedTab { const bestie = savedBestie(relay); return { @@ -105,7 +117,13 @@ export function formerBestieTab( }; }, component: ({ agent }) => ( - + ), }; } @@ -170,11 +188,13 @@ function BestieTab({ relay, agents, agent, + navigation, former = false, }: { relay: RelayData; agents: TabAgents; agent: Agent; + navigation: Pick; former?: boolean; }) { const { session, scope } = useRelayConnection(relay); @@ -271,6 +291,7 @@ function BestieTab({ )} /> )} + diff --git a/src/bundled/bestie/CostRow.test.tsx b/src/bundled/bestie/CostRow.test.tsx new file mode 100644 index 0000000000..bd7f9cd5b9 --- /dev/null +++ b/src/bundled/bestie/CostRow.test.tsx @@ -0,0 +1,148 @@ +// @vitest-environment jsdom +import "@testing-library/jest-dom/vitest"; +import { cleanup, render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { afterEach, expect, it, vi } from "vitest"; +import type { + Agent, + Agents, + SessionUsage, + UsageObservation, +} from "../../features/agents/service"; +import { dayStart } from "../usage/stats"; +import { CostRow } from "./CostRow"; +import { weekCost } from "./cost"; + +afterEach(cleanup); + +const NOW = new Date(2026, 10, 13, 15).getTime(); +const agent = { + key: "a".repeat(64), + pubkey: "a".repeat(64), + name: "Ada", + type: "test/echo", + place: "here", +} as unknown as Agent; +/** A request the harness recorded the cost of, `ago` days before NOW. */ +const request = (ago: number, usd: number): UsageObservation => ({ + at: dayStart(NOW, ago) + 60_000, + model: "test-model", + tokens: {}, + cost: { usd, source: "recorded" }, +}); +const session = ( + id: string, + observations: UsageObservation[], +): SessionUsage => ({ + id, + revision: id, + gaps: [], + startedAt: Math.min(...observations.map((entry) => entry.at)), + lastAt: Math.max(...observations.map((entry) => entry.at)), + observations, +}); +/** Agents whose type reads `usage`, or none when it is left out. */ +const agentsWith = (usage?: unknown) => + ({ + types: () => [{ key: "test/echo", ...(usage ? { usage } : {}) }], + }) as unknown as Pick; + +it("adds the last seven days up and ignores older requests", async () => { + const usage = vi.fn(async () => [ + session("one", [request(0, 0.25), request(2, 1.5)]), + session("two", [request(6, 0.5), request(8, 40)]), + ]); + const week = await weekCost( + agentsWith(usage), + agent, + new AbortController().signal, + NOW, + ); + expect(week.days).toHaveLength(7); + expect(week.days.map((day) => day.cost.value)).toEqual([ + 0.5, 0, 0, 0, 1.5, 0, 0.25, + ]); + expect(week.total).toEqual({ value: 2.25, partial: false }); + // Only the week is read, from the start of its first day. + expect(usage).toHaveBeenCalledWith(agent, { + since: dayStart(NOW, 6), + signal: expect.any(AbortSignal), + }); +}); + +it("shows the total and a daily sparkline, and opens Usage", async () => { + const user = userEvent.setup(); + const open = vi.fn(); + render( + [ + session("one", [request(0, 0.25), request(1, 1.5)]), + ])} + agent={agent} + open={open} + />, + ); + expect(await screen.findByText("$1.75")).toBeVisible(); + expect(screen.getByText("Cost, last 7 days")).toBeVisible(); + expect(screen.getByRole("img", { name: /Daily cost.*\$1\.50.*\$0\.25/ })); + await user.click(screen.getByRole("button", { name: "Open Usage" })); + expect(open).toHaveBeenCalledWith({ + version: 1, + kind: "settings", + section: "buzz.usage/usage", + }); +}); + +it("says so when the agent type reports no usage", () => { + render(); + expect( + screen.getByText(/this agent's type doesn't report its usage/), + ).toBeVisible(); + expect(screen.queryByRole("button")).toBeNull(); +}); + +it("says so, without reading, for an agent that runs elsewhere", () => { + const usage = vi.fn(); + render( + , + ); + expect(screen.getByText(/this agent runs elsewhere/)).toBeVisible(); + expect(usage).not.toHaveBeenCalled(); +}); + +it("shows a quiet error when the read rejects, and reads again on Retry", async () => { + const user = userEvent.setup(); + const usage = vi + .fn() + .mockRejectedValueOnce(new Error("a transcript was too large")) + .mockResolvedValue([session("one", [request(0, 0.4)])]); + render(); + expect( + await screen.findByText("Couldn't read this agent's sessions."), + ).toBeVisible(); + expect(screen.queryByRole("alert")).toBeNull(); + await user.click(screen.getByRole("button", { name: "Retry" })); + expect(await screen.findByText("$0.40")).toBeVisible(); + expect(usage).toHaveBeenCalledTimes(2); +}); + +it("stops reading when the tab closes", async () => { + let signal: AbortSignal | undefined; + const usage = vi.fn( + (_: Agent, options: { signal: AbortSignal }) => + new Promise(() => { + signal = options.signal; + }), + ); + const { unmount } = render( + , + ); + expect(screen.getByText("Reading its sessions…")).toBeVisible(); + await vi.waitFor(() => expect(signal).toBeDefined()); + unmount(); + expect(signal?.aborted).toBe(true); +}); diff --git a/src/bundled/bestie/CostRow.tsx b/src/bundled/bestie/CostRow.tsx new file mode 100644 index 0000000000..bff30b4443 --- /dev/null +++ b/src/bundled/bestie/CostRow.tsx @@ -0,0 +1,132 @@ +import { useEffect, useState } from "react"; +import type { Agent, Agents } from "../../features/agents/service"; +import { settingsTarget } from "../../features/navigation/buzz-links"; +import type { Navigation } from "../../features/navigation/controller"; +import { Button } from "../../shared/design-system/ui/Button"; +import { PreferenceRow } from "../../shared/design-system/ui/PreferenceRow"; +import { costText } from "../usage/format"; +import { COST_DAYS, readsUsage, type WeekCost, weekCost } from "./cost"; + +const BAR = 4; +const GAP = 2; +const HEIGHT = 20; +const day = (start: number) => + new Date(start).toLocaleDateString(undefined, { + weekday: "short", + }); + +/** A bar per day, tallest the costliest day; the figures are in its label. */ +function Sparkline({ week }: { week: WeekCost }) { + const top = Math.max(...week.days.map((entry) => entry.cost.value ?? 0), 0); + return ( + `${day(entry.start)} ${costText(entry.cost)}`) + .join(", ")}`} + width={COST_DAYS * (BAR + GAP) - GAP} + height={HEIGHT} + > + {week.days.map((entry, index) => { + const spent = entry.cost.value ?? 0; + const height = spent > 0 ? Math.max(2, (spent / top) * HEIGHT) : 1; + return ( + 0 ? 1 : 0.4} + /> + ); + })} + + ); +} + +/** The agent's estimated cost over the last week, read when the tab opens: a + * sparkline, the total and a way to Usage. It says so when the agent's type + * reports no usage or the agent isn't on this device, and when a read fails, + * with Retry; it never stands in the way of the tab. */ +export function CostRow({ + agents, + agent, + open, +}: { + agents: Pick; + agent: Agent; + open: Navigation["open"]; +}) { + const readable = readsUsage(agents, agent); + const [week, setWeek] = useState(); + const [attempt, setAttempt] = useState(0); + // biome-ignore lint/correctness/useExhaustiveDependencies: Reads again for another agent or a retry. + useEffect(() => { + setWeek(undefined); + if (!readable) return; + const controller = new AbortController(); + weekCost(agents, agent, controller.signal).then( + (read) => { + if (!controller.signal.aborted) setWeek(read); + }, + () => { + if (!controller.signal.aborted) setWeek("error"); + }, + ); + return () => controller.abort(); + }, [agent.pubkey, agent.type, readable, attempt]); + const title = `Cost, last ${COST_DAYS} days`; + if (!readable) + return ( + + ); + if (week === "error") + return ( + ( + + )} + /> + ); + if (!week) + return ; + return ( + ( +
+ + {costText(week.total)} + +
+ )} + /> + ); +} diff --git a/src/bundled/bestie/README.md b/src/bundled/bestie/README.md index 9e3167d20d..f0ca9d0919 100644 --- a/src/bundled/bestie/README.md +++ b/src/bundled/bestie/README.md @@ -83,6 +83,18 @@ no Bestie to your account: the agent stays, its check-ins stop, and its memory section and private channels stay, which its Former Bestie tab can turn off. Both need an account to save none to. +**Cost, last 7 days** shows what the agent's sessions on this device cost over +the last seven days: a bar for each day, today last, the total, and **Open +Usage**, which opens Settings → Usage (not filtered to this agent; Usage keeps +its own filters). It reads the sessions when the tab opens, through the same +agent-type `usage` read and the same estimate as the Usage plugin (`stats()` +and its price data are imported from it), and keeps nothing: no stored state, no +sync. A cost is an estimate from the harness's own record or its token counts at +published prices, not a bill, and it says so when some of it is unknown. A +hosted agent, an agent on another device and an agent whose type reports no +usage show the row as not available; a read that fails says so quietly with +**Retry**, and nothing else in the tab waits for it. + **Remembers you** adds memory rules to the agent's instructions, in a section marked `` … ``, and turning it off removes that section. The section is the memory map and its diff --git a/src/bundled/bestie/cost.ts b/src/bundled/bestie/cost.ts new file mode 100644 index 0000000000..ff616a551a --- /dev/null +++ b/src/bundled/bestie/cost.ts @@ -0,0 +1,49 @@ +// The Bestie's cost for its tab: what the Usage plugin would show for this one +// agent over the last week, computed when the tab opens from the agent type's +// own `usage` read. Nothing is stored; it is an estimate, not a bill. +import type { Agent, Agents } from "../../features/agents/service"; +import { loadPrices } from "../usage/pricing"; +import { dayStart, stats, sum, type Total } from "../usage/stats"; + +export const COST_DAYS = 7; + +/** The week's cost, oldest day first. */ +export type WeekCost = Readonly<{ + days: readonly Readonly<{ start: number; cost: Total }>[]; + total: Total; +}>; + +/** Whether the agent's sessions can be read here: it runs on this device and + * its type reports usage. */ +export const readsUsage = (agents: Pick, agent: Agent) => + agent.place === "here" && + !!agents.types().find((type) => type.key === agent.type)?.usage; + +/** The last `COST_DAYS` days of the agent's cost, today included. Rejects when + * the read does; without price data, costs the harness did not record read as + * unknown rather than wrong. */ +export async function weekCost( + agents: Pick, + agent: Agent, + signal: AbortSignal, + now = Date.now(), +): Promise { + const read = agents.types().find((type) => type.key === agent.type)?.usage; + if (!read || agent.place !== "here") throw new Error("No usage"); + const [sessions] = await Promise.all([ + read(agent, { since: dayStart(now, COST_DAYS - 1), signal }), + loadPrices().catch(() => {}), + ]); + const week = stats( + [{ agent, harness: agent.type, sessions }], + now, + COST_DAYS, + ); + return { + days: week.days.map((day) => ({ + start: day.start, + cost: sum(day.costs.values()), + })), + total: week.cost, + }; +} diff --git a/src/bundled/bestie/index.tsx b/src/bundled/bestie/index.tsx index f8c371ee37..444152ecbb 100644 --- a/src/bundled/bestie/index.tsx +++ b/src/bundled/bestie/index.tsx @@ -36,8 +36,10 @@ export const inject = [ "panels", ]; export const apply: PluginModule["apply"] = (ctx) => { - ctx.agents.registerTab(bestieTab(ctx.relay, ctx.agents)); - ctx.agents.registerTab(formerBestieTab(ctx.relay, ctx.agents)); + ctx.agents.registerTab(bestieTab(ctx.relay, ctx.agents, ctx.navigation)); + ctx.agents.registerTab( + formerBestieTab(ctx.relay, ctx.agents, ctx.navigation), + ); // Whoever is Bestie, on any device, only it checks in. ctx.effect(() => stopFormerCheckIns(ctx.relay, ctx.agents)); // A hosted former Bestie's memory is on its provider, read here for its tab. From 094aa0206652a28f3846ea975f87165bf0e3928b Mon Sep 17 00:00:00 2001 From: Riley Crane Date: Fri, 13 Nov 2026 15:11:33 -0800 Subject: [PATCH 2/6] test(bestie): give the tab fixture navigation and a week of usage The Bestie tab now takes the host's navigation for its Cost row, and the layout fixture still built it without one, so the tab threw before it rendered. The fixture now passes a navigation and gives its agent type a `usage` read with recorded costs, so the row shows its sparkline, total and Open Usage. The layout journey waits for that row before measuring, so the widest new row is part of the fit check at every width and text size. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Riley Crane --- tests/browser/bestie-tab.spec.mjs | 4 ++++ tests/fixtures/bestie-tab.tsx | 26 ++++++++++++++++++++++++-- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/tests/browser/bestie-tab.spec.mjs b/tests/browser/bestie-tab.spec.mjs index 06a605d6d4..67656bff08 100644 --- a/tests/browser/bestie-tab.spec.mjs +++ b/tests/browser/bestie-tab.spec.mjs @@ -18,6 +18,10 @@ for (const [variant, query] of [ await expect( page.getByText("Private channels", { exact: false }).first(), ).toBeVisible(); + // The Cost row has read the week before its width is measured. + await expect( + page.getByRole("button", { name: "Open Usage" }), + ).toBeVisible(); for (const width of ["28rem", "20rem"]) { for (const fontSize of ["16px", "20px"]) { await page.evaluate( diff --git a/tests/fixtures/bestie-tab.tsx b/tests/fixtures/bestie-tab.tsx index 9ba9ba1e17..9eb17ac166 100644 --- a/tests/fixtures/bestie-tab.tsx +++ b/tests/fixtures/bestie-tab.tsx @@ -76,9 +76,30 @@ const relay = { snapshot: () => connection, subscribe: () => () => {}, } as unknown as RelayData; +// A recorded cost on three of the last seven days, so the Cost row shows its +// sparkline, total and Open Usage at the panel's widths. +const DAY = 86_400_000; +const request = (ago: number, usd: number) => ({ + at: Date.now() - ago * DAY, + model: "claude-sonnet-5-5", + tokens: {}, + cost: { usd, source: "recorded" }, +}); +const sessions = [ + { + id: "week", + revision: "week", + gaps: [], + startedAt: Date.now() - 5 * DAY, + lastAt: Date.now(), + observations: [request(5, 1.25), request(2, 0.4), request(0, 2.1)], + }, +]; const agents = { save: async () => {}, - types: () => [{ key: "claude-code", adopt: () => ({}) }], + types: () => [ + { key: "claude-code", adopt: () => ({}), usage: async () => sessions }, + ], // Both are on this device, so neither is asked about as remote. find: (pubkey: string) => [ADA, BEA].includes(pubkey) ? { pubkey, place: "here" } : undefined, @@ -103,7 +124,8 @@ const agent = { ), }, } as unknown as Agent; -const tab = (former ? formerBestieTab : bestieTab)(relay, agents); +const navigation = { open: async () => {} }; +const tab = (former ? formerBestieTab : bestieTab)(relay, agents, navigation); const Tab = tab.component; const root = document.getElementById("root"); if (!root) throw new Error("Missing fixture root"); From 6ce3a12b3eb5850bbfcc99e0b1ceec866d1ca0d9 Mon Sep 17 00:00:00 2001 From: Riley Crane Date: Fri, 13 Nov 2026 15:42:53 -0800 Subject: [PATCH 3/6] fix(bestie): offer Open Usage only while Usage is on The Cost row's Open Usage opened the Usage plugin's settings card, and Usage is off by default, so on a fresh install the button led to a page that isn't available. The row now shows the button only while that card is registered, following the settings cards as Usage is turned on or off. The cost and sparkline still show either way: they come from the agent type's own usage read. The row's rendered tests also read their week from the real clock against fixed sample dates, so they would fail a week after those dates. They now hold Date at the sample day. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Riley Crane --- docs/buzz-help.md | 5 +- src/bundled/bestie/BestieTab.test.tsx | 105 +++++++++++++++++--------- src/bundled/bestie/BestieTab.tsx | 15 +++- src/bundled/bestie/CostRow.test.tsx | 86 +++++++++++++++++++-- src/bundled/bestie/CostRow.tsx | 36 +++++---- src/bundled/bestie/README.md | 7 +- src/bundled/bestie/index.tsx | 7 +- tests/fixtures/bestie-tab.tsx | 9 ++- 8 files changed, 206 insertions(+), 64 deletions(-) diff --git a/docs/buzz-help.md b/docs/buzz-help.md index 0fbb1eb607..103c862203 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -1288,8 +1288,9 @@ available rather than silently discarding it. (Builderlab does) has the tab and can use **Remembers you**; hosted agents cannot use Bestie's Attention check-ins. The tab's **Cost** row shows an estimate of what a local Bestie's sessions on this computer cost over the - last 7 days, with **Open Usage**. It is not a bill, and it says when the - agent's type reports no usage or the agent runs elsewhere. + last 7 days, with **Open Usage** while the Usage plugin is on. It is not a + bill, and it says when the agent's type reports no usage or the agent runs + elsewhere. - An agent running on this device can also show, change or remove your Bestie when you ask it to. It saves to this device and your account, as the menu does, and accepts only your agents you can tag in this community. It also diff --git a/src/bundled/bestie/BestieTab.test.tsx b/src/bundled/bestie/BestieTab.test.tsx index 011ef52bb0..00f63a3848 100644 --- a/src/bundled/bestie/BestieTab.test.tsx +++ b/src/bundled/bestie/BestieTab.test.tsx @@ -46,6 +46,7 @@ const member = (name: string, digit: string): Agent => const ada = member("Ada", "a"); const bea = member("Bea", "b"); const navigation = { open: vi.fn(async () => ({ status: "opened" })) } as never; +const settingsCards = { has: () => true, subscribe: () => () => {} }; /** Agents that save as a synced editor would: the agent's next config. * `listed` are the agents it finds, Ada and Bea, both on this device. */ @@ -125,7 +126,7 @@ function community(saved: string | null | undefined, agents = [ada, bea]) { it("shows on the saved Bestie only, and moves when Change picks another", async () => { const user = userEvent.setup(); const { relay, mainAgent } = community(ada.pubkey); - const tab = bestieTab(relay, host([]).agents, navigation); + const tab = bestieTab(relay, host([]).agents, navigation, settingsCards); const changed = vi.fn(); const stop = tab.subscribe?.(changed); // Nothing shows before the account's choice is read. @@ -167,7 +168,7 @@ it("shows the Bestie's cost for the week, without a failed read stopping the tab ...host().agents, types: () => [{ key: "test/echo", adopt: () => ({}), usage }], } as unknown as Parameters[1]; - const tab = bestieTab(relay, agents, navigation); + const tab = bestieTab(relay, agents, navigation, settingsCards); const stop = tab.subscribe?.(() => {}); await vi.waitFor(() => expect(tab.when?.(ada)).toBe(true)); const Tab = tab.component; @@ -201,7 +202,7 @@ it("puts this device back on the account's Bestie when a failed Change is closed const user = userEvent.setup(); const { relay, mainAgent } = community(ada.pubkey); mainAgent.write.mockRejectedValueOnce(new Error("offline")); - const tab = bestieTab(relay, host([]).agents, navigation); + const tab = bestieTab(relay, host([]).agents, navigation, settingsCards); const stop = tab.subscribe?.(() => {}); await vi.waitFor(() => expect(tab.when?.(ada)).toBe(true)); const Tab = tab.component; @@ -219,7 +220,7 @@ it("keeps the Bestie an agent saved when its tab closes over a failed Change", a const user = userEvent.setup(); const { relay, mainAgent } = community(ada.pubkey); mainAgent.write.mockRejectedValueOnce(new Error("offline")); - const tab = bestieTab(relay, host([]).agents, navigation); + const tab = bestieTab(relay, host([]).agents, navigation, settingsCards); const subscribe = tab.subscribe ?? (() => () => {}); const stop = subscribe(() => {}); await vi.waitFor(() => expect(tab.when?.(ada)).toBe(true)); @@ -251,7 +252,7 @@ it("puts this device back when a Change still saving fails after the panel close fail = reject; }), ); - const tab = bestieTab(relay, host([]).agents, navigation); + const tab = bestieTab(relay, host([]).agents, navigation, settingsCards); const stop = tab.subscribe?.(() => {}); await vi.waitFor(() => expect(tab.when?.(ada)).toBe(true)); const Tab = tab.component; @@ -272,6 +273,7 @@ it("offers a remote agent in Change, and says what it can't do before switching" relay, host([], [ada, bea, cara]).agents, navigation, + settingsCards, ).component; await act(async () => { render(); @@ -296,7 +298,12 @@ it("offers a remote agent in Change, and says what it can't do before switching" it("says nothing of remote agents when switching to one on this device", async () => { const user = userEvent.setup(); const { relay } = community(ada.pubkey); - const Tab = bestieTab(relay, host([]).agents, navigation).component; + const Tab = bestieTab( + relay, + host([]).agents, + navigation, + settingsCards, + ).component; await act(async () => { render(); }); @@ -316,7 +323,7 @@ it("shows a hosted Bestie's switches as unavailable when its provider has no ins } as Agent; const { relay } = community(ada.pubkey); const { agents, save } = host(["block.builderlab/builderlab"], [remote, bea]); - const Tab = bestieTab(relay, agents, navigation).component; + const Tab = bestieTab(relay, agents, navigation, settingsCards).component; await act(async () => { render(); }); @@ -366,7 +373,7 @@ function hostedBestie(text: string) { it("shows a hosted Bestie's tab, not one on another device's", async () => { const { relay } = community(ada.pubkey); - const tab = bestieTab(relay, host().agents, navigation); + const tab = bestieTab(relay, host().agents, navigation, settingsCards); const stop = tab.subscribe?.(() => {}); await vi.waitFor(() => expect(tab.when?.(ada)).toBe(true)); stop?.(); @@ -378,7 +385,7 @@ it("turns a hosted Bestie's memory on and off through its provider, and never to const user = userEvent.setup(); const { relay } = community(ada.pubkey); const { remote, agents, save, get, set } = hostedBestie("Be brief."); - const Tab = bestieTab(relay, agents, navigation).component; + const Tab = bestieTab(relay, agents, navigation, settingsCards).component; await act(async () => { render(); }); @@ -411,7 +418,7 @@ it("never replaces a hosted Bestie's instructions edited elsewhere since the tab const user = userEvent.setup(); const { relay } = community(ada.pubkey); const { remote, agents, get, set, editElsewhere } = hostedBestie("Be brief."); - const Tab = bestieTab(relay, agents, navigation).component; + const Tab = bestieTab(relay, agents, navigation, settingsCards).component; await act(async () => { render(); }); @@ -441,7 +448,7 @@ it("says why a hosted Bestie's instructions can't be read or saved, and lets eit const { relay } = community(ada.pubkey); const { remote, agents, get, set } = hostedBestie("Be brief."); get.mockRejectedValueOnce(new Error("Builderlab is down.")); - const Tab = bestieTab(relay, agents, navigation).component; + const Tab = bestieTab(relay, agents, navigation, settingsCards).component; await act(async () => { render(); }); @@ -467,7 +474,12 @@ it("says why a hosted Bestie's instructions can't be read or saved, and lets eit it("keeps Change unavailable while there is no other agent to choose", async () => { const { relay } = community(ada.pubkey, [ada]); - const Tab = bestieTab(relay, host().agents, navigation).component; + const Tab = bestieTab( + relay, + host().agents, + navigation, + settingsCards, + ).component; await act(async () => { render(); }); @@ -487,6 +499,7 @@ it("asks before making a remote former Bestie your Bestie again, and Cancel chan relay, host([], [bea, remote]).agents, navigation, + settingsCards, ).component; await act(async () => { render(); @@ -517,7 +530,7 @@ it("asks before making a remote former Bestie your Bestie again, and Cancel chan it("tells the host only when the Bestie or its community changes", async () => { const { relay, reconnect } = community(ada.pubkey); - const tab = bestieTab(relay, host([]).agents, navigation); + const tab = bestieTab(relay, host([]).agents, navigation, settingsCards); const changed = vi.fn(); const stop = tab.subscribe?.(changed); await vi.waitFor(() => expect(tab.when?.(ada)).toBe(true)); @@ -536,7 +549,7 @@ it("turns memory on and off as a marked section of the instructions", async () = const user = userEvent.setup(); const { relay } = community(ada.pubkey); const { agents, save } = host(); - const Tab = bestieTab(relay, agents, navigation).component; + const Tab = bestieTab(relay, agents, navigation, settingsCards).component; const base = { instructions: "head-1" }; const agent = { ...ada, @@ -581,7 +594,7 @@ it("keeps memory on through the owner's edits, and offers Restore for edited mar const user = userEvent.setup(); const { relay } = community(ada.pubkey); const { agents, save } = host(); - const Tab = bestieTab(relay, agents, navigation).component; + const Tab = bestieTab(relay, agents, navigation, settingsCards).component; const base = { instructions: "head-2" }; const on = withFeature("Be brief.", memory, true); const close = ""; @@ -627,7 +640,7 @@ it("says why a save failed and lets the switch be tried again", async () => { const { relay } = community(ada.pubkey); const { agents, save } = host(); save.mockRejectedValueOnce(new Error("Connect to the community to save")); - const Tab = bestieTab(relay, agents, navigation).component; + const Tab = bestieTab(relay, agents, navigation, settingsCards).component; render(); const remembers = screen.getByRole("switch", { name: "Remembers you" }); await user.click(remembers); @@ -645,7 +658,7 @@ it("says why a save failed and lets the switch be tried again", async () => { it("offers no switch while the agent's instructions can't be read here", () => { const { relay } = community(ada.pubkey); const { agents, save } = host(); - const Tab = bestieTab(relay, agents, navigation).component; + const Tab = bestieTab(relay, agents, navigation, settingsCards).component; render( ); const hourly = screen.getByRole("switch", { name: "Hourly notes" }); save.mockRejectedValueOnce(new Error("Connect to the community to save")); @@ -837,7 +850,7 @@ it("offers to remove what is left of a check-in whose Interest or timer is gone" const user = userEvent.setup(); const { relay } = community(ada.pubkey); const { agents, save } = host(); - const Tab = bestieTab(relay, agents, navigation).component; + const Tab = bestieTab(relay, agents, navigation, settingsCards).component; const left = (slug: string, value: object) => ({ ...remembering(true), @@ -873,7 +886,7 @@ it("says a check-in paused in Attention is paused, and how to restart it", async const user = userEvent.setup(); const { relay } = community(ada.pubkey); const { agents, save } = host(); - const Tab = bestieTab(relay, agents, navigation).component; + const Tab = bestieTab(relay, agents, navigation, settingsCards).component; const paused = { ...remembering(true), attention: { @@ -900,7 +913,7 @@ it("says a check-in paused in Attention is paused, and how to restart it", async it("shows a Former Bestie tab while a former Bestie has a setting on, with a way back", async () => { const user = userEvent.setup(); const { relay, mainAgent } = community(bea.pubkey); - const tab = formerBestieTab(relay, host().agents, navigation); + const tab = formerBestieTab(relay, host().agents, navigation, settingsCards); const remembering = { ...ada, config: { instructions: withFeature("Be brief.", memory, true) }, @@ -947,8 +960,8 @@ it("removes the Bestie after asking, and shows the agent as a Former Bestie", as const user = userEvent.setup(); const { relay, mainAgent } = community(ada.pubkey); const agents = host().agents; - const tab = bestieTab(relay, agents, navigation); - const former = formerBestieTab(relay, agents, navigation); + const tab = bestieTab(relay, agents, navigation, settingsCards); + const former = formerBestieTab(relay, agents, navigation, settingsCards); const remembering = { ...ada, config: { instructions: withFeature("Be brief.", memory, true) }, @@ -999,7 +1012,7 @@ it("shows a hosted former Bestie's Former Bestie tab while its memory is on, rea const { remote, agents, get, set, save } = hostedBestie( withFeature("Be brief.", memory, true), ); - const tab = formerBestieTab(relay, agents, navigation); + const tab = formerBestieTab(relay, agents, navigation, settingsCards); const listener = vi.fn(); const stop = tab.subscribe?.(listener); // Its instructions aren't on this device until its provider is read. @@ -1053,7 +1066,7 @@ it("keeps a hosted former Bestie's tab when an older background read ends after const user = userEvent.setup(); const { relay } = community(bea.pubkey); const { remote, agents, get } = hostedBestie("Be brief."); - const tab = formerBestieTab(relay, agents, navigation); + const tab = formerBestieTab(relay, agents, navigation, settingsCards); const stop = tab.subscribe?.(() => {}); await vi.waitFor(() => expect(tab.when?.(bea)).toBe(false)); // The background read starts while memory is off, and answers late. @@ -1086,7 +1099,7 @@ it("keeps a hosted former Bestie's tab when an older background read ends after it("keeps a hosted former Bestie's tab while a newer read is under way, whatever an older one answers", async () => { const { relay } = community(bea.pubkey); const { remote, agents } = hostedBestie("Be brief."); - const tab = formerBestieTab(relay, agents, navigation); + const tab = formerBestieTab(relay, agents, navigation, settingsCards); const stop = tab.subscribe?.(() => {}); await vi.waitFor(() => expect(tab.when?.(bea)).toBe(false)); // A failed read shows the tab, which reads again when it opens. @@ -1112,7 +1125,7 @@ it("keeps a hosted former Bestie's tab while a newer read is under way, whatever it("counts an older read's answer once a newer read is abandoned, from the moment it aborts", async () => { const { relay } = community(bea.pubkey); const { remote, agents } = hostedBestie("Be brief."); - const tab = formerBestieTab(relay, agents, navigation); + const tab = formerBestieTab(relay, agents, navigation, settingsCards); const stop = tab.subscribe?.(() => {}); await vi.waitFor(() => expect(tab.when?.(bea)).toBe(false)); const remembering = withFeature("Be brief.", memory, true); @@ -1143,7 +1156,7 @@ it("shows a hosted former Bestie's tab from a background read that answers after const { remote, agents, get } = hostedBestie( withFeature("Be brief.", memory, true), ); - const tab = formerBestieTab(relay, agents, navigation); + const tab = formerBestieTab(relay, agents, navigation, settingsCards); const stop = tab.subscribe?.(() => {}); await vi.waitFor(() => expect(tab.when?.(bea)).toBe(false)); let answer = (_text: string) => {}; @@ -1192,7 +1205,7 @@ it("shows a Former Bestie tab for a hosted agent its provider holds no instructi let list = listed([OWNER, remote.pubkey]); session.channels.list = () => list; writeView(SCOPE, "bestie:former", [ada.pubkey]); - const tab = formerBestieTab(relay, agents, navigation); + const tab = formerBestieTab(relay, agents, navigation, settingsCards); const stop = tab.subscribe?.(() => {}); await vi.waitFor(() => expect(tab.when?.(remote)).toBe(true)); const Tab = tab.component; @@ -1215,7 +1228,7 @@ it("keeps a hosted former Bestie's tab after a failed read, until a read shows n const user = userEvent.setup(); const { relay } = community(bea.pubkey); const { remote, agents, get } = hostedBestie("Be brief."); - const tab = formerBestieTab(relay, agents, navigation); + const tab = formerBestieTab(relay, agents, navigation, settingsCards); const stop = tab.subscribe?.(() => {}); await vi.waitFor(() => expect(tab.when?.(bea)).toBe(false)); get.mockRejectedValueOnce(new Error("Builderlab is down.")); @@ -1239,7 +1252,7 @@ it("keeps a hosted former Bestie's tab when memory saved on but reading it back const user = userEvent.setup(); const { relay } = community(bea.pubkey); const { remote, agents, get, set } = hostedBestie("Be brief."); - const tab = formerBestieTab(relay, agents, navigation); + const tab = formerBestieTab(relay, agents, navigation, settingsCards); const stop = tab.subscribe?.(() => {}); await vi.waitFor(() => expect(tab.when?.(bea)).toBe(false)); const Tab = tab.component; @@ -1267,7 +1280,12 @@ it("keeps a hosted former Bestie's tab when memory saved on but reading it back it("shows no Former Bestie tab while the account's choice is unread or unreadable", async () => { const { relay, mainAgent } = community(undefined); mainAgent.read.mockRejectedValueOnce(new Error("offline")); - const former = formerBestieTab(relay, host().agents, navigation); + const former = formerBestieTab( + relay, + host().agents, + navigation, + settingsCards, + ); const remembering = { ...ada, config: { instructions: withFeature("Be brief.", memory, true) }, @@ -1288,7 +1306,12 @@ it("shows a Former Bestie tab on an account that saved none, not on one with no [null, true], ] as const) { const { relay, mainAgent } = community(record); - const former = formerBestieTab(relay, host().agents, navigation); + const former = formerBestieTab( + relay, + host().agents, + navigation, + settingsCards, + ); const stop = former.subscribe?.(() => {}); await act(async () => {}); expect(mainAgent.read).toHaveBeenCalled(); @@ -1304,7 +1327,12 @@ it("offers no Remove without an account to save none to", async () => { delete (relay.snapshot() as { session: { mainAgent?: unknown } }).session .mainAgent; setDefaultAgent(SCOPE, ada.pubkey); - const Tab = bestieTab(relay, host().agents, navigation).component; + const Tab = bestieTab( + relay, + host().agents, + navigation, + settingsCards, + ).component; await act(async () => { render(); }); @@ -1316,7 +1344,12 @@ it("lets a former Bestie's leftover check-in be turned off", async () => { const user = userEvent.setup(); const { relay } = community(bea.pubkey); const { agents, save } = host(); - const Tab = formerBestieTab(relay, agents, navigation).component; + const Tab = formerBestieTab( + relay, + agents, + navigation, + settingsCards, + ).component; const checking = { ...ada, config: { instructions: withFeature("Be brief.", memory, true) }, diff --git a/src/bundled/bestie/BestieTab.tsx b/src/bundled/bestie/BestieTab.tsx index d08989253d..e94cd78346 100644 --- a/src/bundled/bestie/BestieTab.tsx +++ b/src/bundled/bestie/BestieTab.tsx @@ -6,6 +6,7 @@ import type { Agents, } from "../../features/agents/service"; import type { Navigation } from "../../features/navigation/controller"; +import type { SettingsCards } from "../../features/settings/service"; import { useRelayConnection } from "../../features/relay/react"; import type { RelayData } from "../../features/relay/service"; import type { RelaySession } from "../../features/relay/session"; @@ -50,12 +51,14 @@ import { inCommunity, savedBestie } from "./saved"; /** The agents a tab saves to, and finds to know which are remote. */ type TabAgents = FeatureAgents & Pick; +type TabCards = Pick; /** The Bestie tab, on the agent saved as Bestie in its community. */ export function bestieTab( relay: RelayData, agents: TabAgents, navigation: Pick, + settingsCards: TabCards, ): AgentAddedTab { const bestie = savedBestie(relay); return { @@ -73,6 +76,7 @@ export function bestieTab( agents={agents} agent={agent} navigation={navigation} + settingsCards={settingsCards} /> ), }; @@ -86,6 +90,7 @@ export function formerBestieTab( relay: RelayData, agents: TabAgents, navigation: Pick, + settingsCards: TabCards, ): AgentAddedTab { const bestie = savedBestie(relay); return { @@ -122,6 +127,7 @@ export function formerBestieTab( agents={agents} agent={agent} navigation={navigation} + settingsCards={settingsCards} former /> ), @@ -189,12 +195,14 @@ function BestieTab({ agents, agent, navigation, + settingsCards, former = false, }: { relay: RelayData; agents: TabAgents; agent: Agent; navigation: Pick; + settingsCards: TabCards; former?: boolean; }) { const { session, scope } = useRelayConnection(relay); @@ -291,7 +299,12 @@ function BestieTab({ )} /> )} - +
diff --git a/src/bundled/bestie/CostRow.test.tsx b/src/bundled/bestie/CostRow.test.tsx index bd7f9cd5b9..f61a83e370 100644 --- a/src/bundled/bestie/CostRow.test.tsx +++ b/src/bundled/bestie/CostRow.test.tsx @@ -1,8 +1,8 @@ // @vitest-environment jsdom import "@testing-library/jest-dom/vitest"; -import { cleanup, render, screen } from "@testing-library/react"; +import { act, cleanup, render, screen } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; -import { afterEach, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; import type { Agent, Agents, @@ -13,7 +13,16 @@ import { dayStart } from "../usage/stats"; import { CostRow } from "./CostRow"; import { weekCost } from "./cost"; -afterEach(cleanup); +// The rendered row reads its week back from now: hold now at NOW. Only Date +// is faked, so the row's reads and user events still run on real timers. +beforeEach(() => { + vi.useFakeTimers({ toFake: ["Date"] }); + vi.setSystemTime(NOW); +}); +afterEach(() => { + cleanup(); + vi.useRealTimers(); +}); const NOW = new Date(2026, 10, 13, 15).getTime(); const agent = { @@ -41,6 +50,24 @@ const session = ( lastAt: Math.max(...observations.map((entry) => entry.at)), observations, }); +/** Settings cards with Usage's registered while `usage.on`; `turn` changes + * that and tells subscribers. */ +const cards = (on: boolean) => { + const listeners = new Set<() => void>(); + const usage = { on }; + return { + has: (key: string) => usage.on && key === "buzz.usage/usage", + subscribe: (listener: () => void) => { + listeners.add(listener); + return () => void listeners.delete(listener); + }, + turn(next: boolean) { + usage.on = next; + for (const listener of listeners) listener(); + }, + }; +}; +const usageOn = cards(true); /** Agents whose type reads `usage`, or none when it is left out. */ const agentsWith = (usage?: unknown) => ({ @@ -80,6 +107,7 @@ it("shows the total and a daily sparkline, and opens Usage", async () => { ])} agent={agent} open={open} + settingsCards={usageOn} />, ); expect(await screen.findByText("$1.75")).toBeVisible(); @@ -93,8 +121,41 @@ it("shows the total and a daily sparkline, and opens Usage", async () => { }); }); +it("shows the cost but offers no Open Usage while Usage is off, until it is on", async () => { + const user = userEvent.setup(); + const open = vi.fn(); + const settingsCards = cards(false); + render( + [session("one", [request(0, 0.25)])])} + agent={agent} + open={open} + settingsCards={settingsCards} + />, + ); + expect(await screen.findByText("$0.25")).toBeVisible(); + expect(screen.getByRole("img", { name: /Daily cost/ })).toBeVisible(); + expect(screen.queryByRole("button", { name: "Open Usage" })).toBeNull(); + act(() => settingsCards.turn(true)); + await user.click(screen.getByRole("button", { name: "Open Usage" })); + expect(open).toHaveBeenCalledWith({ + version: 1, + kind: "settings", + section: "buzz.usage/usage", + }); + act(() => settingsCards.turn(false)); + expect(screen.queryByRole("button", { name: "Open Usage" })).toBeNull(); +}); + it("says so when the agent type reports no usage", () => { - render(); + render( + , + ); expect( screen.getByText(/this agent's type doesn't report its usage/), ).toBeVisible(); @@ -108,6 +169,7 @@ it("says so, without reading, for an agent that runs elsewhere", () => { agents={agentsWith(usage)} agent={{ ...agent, place: "hosted" } as Agent} open={vi.fn()} + settingsCards={usageOn} />, ); expect(screen.getByText(/this agent runs elsewhere/)).toBeVisible(); @@ -120,7 +182,14 @@ it("shows a quiet error when the read rejects, and reads again on Retry", async .fn() .mockRejectedValueOnce(new Error("a transcript was too large")) .mockResolvedValue([session("one", [request(0, 0.4)])]); - render(); + render( + , + ); expect( await screen.findByText("Couldn't read this agent's sessions."), ).toBeVisible(); @@ -139,7 +208,12 @@ it("stops reading when the tab closes", async () => { }), ); const { unmount } = render( - , + , ); expect(screen.getByText("Reading its sessions…")).toBeVisible(); await vi.waitFor(() => expect(signal).toBeDefined()); diff --git a/src/bundled/bestie/CostRow.tsx b/src/bundled/bestie/CostRow.tsx index bff30b4443..31b32adc72 100644 --- a/src/bundled/bestie/CostRow.tsx +++ b/src/bundled/bestie/CostRow.tsx @@ -1,12 +1,15 @@ -import { useEffect, useState } from "react"; +import { useEffect, useState, useSyncExternalStore } from "react"; import type { Agent, Agents } from "../../features/agents/service"; import { settingsTarget } from "../../features/navigation/buzz-links"; import type { Navigation } from "../../features/navigation/controller"; +import type { SettingsCards } from "../../features/settings/service"; import { Button } from "../../shared/design-system/ui/Button"; import { PreferenceRow } from "../../shared/design-system/ui/PreferenceRow"; import { costText } from "../usage/format"; import { COST_DAYS, readsUsage, type WeekCost, weekCost } from "./cost"; +/** The Usage plugin's settings card, there only while Usage is on. */ +const USAGE = "buzz.usage/usage"; const BAR = 4; const GAP = 2; const HEIGHT = 20; @@ -48,19 +51,26 @@ function Sparkline({ week }: { week: WeekCost }) { } /** The agent's estimated cost over the last week, read when the tab opens: a - * sparkline, the total and a way to Usage. It says so when the agent's type - * reports no usage or the agent isn't on this device, and when a read fails, - * with Retry; it never stands in the way of the tab. */ + * sparkline, the total and, while the Usage plugin is on, a way to it. The + * figures come from the agent type's own read, so they show either way. It + * says so when the agent's type reports no usage or the agent isn't on this + * device, and when a read fails, with Retry; it never stands in the way of + * the tab. */ export function CostRow({ agents, agent, open, + settingsCards, }: { agents: Pick; agent: Agent; open: Navigation["open"]; + settingsCards: Pick; }) { const readable = readsUsage(agents, agent); + const usagePage = useSyncExternalStore(settingsCards.subscribe, () => + settingsCards.has(USAGE), + ); const [week, setWeek] = useState(); const [attempt, setAttempt] = useState(0); // biome-ignore lint/correctness/useExhaustiveDependencies: Reads again for another agent or a retry. @@ -116,15 +126,15 @@ export function CostRow({
{costText(week.total)} - + {usagePage && ( + + )}
)} /> diff --git a/src/bundled/bestie/README.md b/src/bundled/bestie/README.md index f0ca9d0919..d65153fac3 100644 --- a/src/bundled/bestie/README.md +++ b/src/bundled/bestie/README.md @@ -84,9 +84,10 @@ section and private channels stay, which its Former Bestie tab can turn off. Both need an account to save none to. **Cost, last 7 days** shows what the agent's sessions on this device cost over -the last seven days: a bar for each day, today last, the total, and **Open -Usage**, which opens Settings → Usage (not filtered to this agent; Usage keeps -its own filters). It reads the sessions when the tab opens, through the same +the last seven days: a bar for each day, today last, the total, and, while the +Usage plugin is on, **Open Usage**, which opens Settings → Usage (not filtered +to this agent; Usage keeps its own filters). With Usage off, its settings card +is not registered, so the row shows the figures without the button. It reads the sessions when the tab opens, through the same agent-type `usage` read and the same estimate as the Usage plugin (`stats()` and its price data are imported from it), and keeps nothing: no stored state, no sync. A cost is an estimate from the harness's own record or its token counts at diff --git a/src/bundled/bestie/index.tsx b/src/bundled/bestie/index.tsx index 444152ecbb..9b40f64b0c 100644 --- a/src/bundled/bestie/index.tsx +++ b/src/bundled/bestie/index.tsx @@ -34,11 +34,14 @@ export const inject = [ "agents", "conversation", "panels", + "settingsCards", ]; export const apply: PluginModule["apply"] = (ctx) => { - ctx.agents.registerTab(bestieTab(ctx.relay, ctx.agents, ctx.navigation)); ctx.agents.registerTab( - formerBestieTab(ctx.relay, ctx.agents, ctx.navigation), + bestieTab(ctx.relay, ctx.agents, ctx.navigation, ctx.settingsCards), + ); + ctx.agents.registerTab( + formerBestieTab(ctx.relay, ctx.agents, ctx.navigation, ctx.settingsCards), ); // Whoever is Bestie, on any device, only it checks in. ctx.effect(() => stopFormerCheckIns(ctx.relay, ctx.agents)); diff --git a/tests/fixtures/bestie-tab.tsx b/tests/fixtures/bestie-tab.tsx index 9eb17ac166..3b21885dfd 100644 --- a/tests/fixtures/bestie-tab.tsx +++ b/tests/fixtures/bestie-tab.tsx @@ -125,7 +125,14 @@ const agent = { }, } as unknown as Agent; const navigation = { open: async () => {} }; -const tab = (former ? formerBestieTab : bestieTab)(relay, agents, navigation); +// Usage is on, so the row offers Open Usage too. +const settingsCards = { has: () => true, subscribe: () => () => {} }; +const tab = (former ? formerBestieTab : bestieTab)( + relay, + agents, + navigation, + settingsCards, +); const Tab = tab.component; const root = document.getElementById("root"); if (!root) throw new Error("Missing fixture root"); From 50299ef176b1cd3d3c27aabe384e00f36109b280 Mon Sep 17 00:00:00 2001 From: Riley Crane Date: Mon, 16 Nov 2026 17:54:43 -0800 Subject: [PATCH 4/6] fix(bestie): read Usage's window for the week's cost goose shares one workspace read between concurrent callers and keeps only the sessions the first caller's window covers. When the Bestie tab's seven-day read started first, Usage's 30-day read joined it and lost every session last active 8-30 days ago. Read Usage's window and add up the week. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Riley Crane --- src/bundled/bestie/CostRow.test.tsx | 89 ++++++++++++++++++++++++++++- src/bundled/bestie/cost.ts | 6 +- 2 files changed, 90 insertions(+), 5 deletions(-) diff --git a/src/bundled/bestie/CostRow.test.tsx b/src/bundled/bestie/CostRow.test.tsx index f61a83e370..dc908dc04a 100644 --- a/src/bundled/bestie/CostRow.test.tsx +++ b/src/bundled/bestie/CostRow.test.tsx @@ -9,7 +9,12 @@ import type { SessionUsage, UsageObservation, } from "../../features/agents/service"; -import { dayStart } from "../usage/stats"; +import type { EventData } from "../../features/relay/events"; +import { turnPrompt } from "../claude-code/prompt"; +import { fakeSpawn } from "../goose/goose-testing"; +import { GooseHistory } from "../goose/transcript"; +import { readUsage } from "../goose/usage"; +import { dayStart, since } from "../usage/stats"; import { CostRow } from "./CostRow"; import { weekCost } from "./cost"; @@ -90,13 +95,91 @@ it("adds the last seven days up and ignores older requests", async () => { 0.5, 0, 0, 0, 1.5, 0, 0.25, ]); expect(week.total).toEqual({ value: 2.25, partial: false }); - // Only the week is read, from the start of its first day. + // Usage's own window is read, so a read Usage joins misses nothing. expect(usage).toHaveBeenCalledWith(agent, { - since: dayStart(NOW, 6), + since: since(NOW), signal: expect.any(AbortSignal), }); }); +it("leaves Usage's month whole when its read joins the week's", async () => { + // goose shares one workspace read between every agent's concurrent reads. + const mention = { + id: "1".repeat(64), + pubkey: "b".repeat(64), + kind: 9, + created_at: NOW / 1000, + content: "@Ada fix the build", + tags: [["h", "chan"]], + sig: "", + } as EventData; + const ask = turnPrompt({ + agent: agent.pubkey, + event: mention, + channel: { id: "chan", name: "general" }, + scope: "thread", + context: [], + total: 1, + }); + const saved = (sessionId: string, ago: number, cost: number) => { + const at = dayStart(NOW, ago) + 60_000; + return { + sessionId, + title: `Ada · #general · ${sessionId}`, + cwd: "/home/test/.buzz", + updatedAt: new Date(at).toISOString(), + conversation: [ + { + role: "user", + created: at / 1000, + content: [{ type: "text", text: ask }], + metadata: { userVisible: true }, + }, + { + role: "assistant", + created: at / 1000, + content: [{ type: "text", text: "Done." }], + metadata: { + userVisible: true, + usage: { + inputTokens: 1, + outputTokens: 1, + cost, + costSource: "estimated", + }, + }, + }, + ], + }; + }; + const goose = fakeSpawn({ + home: "/home/test", + history: [saved("recent", 2, 0.25), saved("older", 20, 3)], + }); + const history = new GooseHistory(goose); + const read = (from: number) => + readUsage( + history, + agent.pubkey, + "~/.buzz", + from, + new AbortController().signal, + ); + const goosey = agentsWith((reader: Agent, options: { since: number }) => + read(options.since), + ); + const [week, month] = await Promise.all([ + weekCost(goosey, agent, new AbortController().signal, NOW), + read(since(NOW)), + ]); + expect(goose.geese).toHaveLength(1); + expect(month.map((session) => session.id).sort()).toEqual([ + "older", + "recent", + ]); + expect(week.total).toEqual({ value: 0.25, partial: false }); +}); + it("shows the total and a daily sparkline, and opens Usage", async () => { const user = userEvent.setup(); const open = vi.fn(); diff --git a/src/bundled/bestie/cost.ts b/src/bundled/bestie/cost.ts index ff616a551a..1558ed6426 100644 --- a/src/bundled/bestie/cost.ts +++ b/src/bundled/bestie/cost.ts @@ -3,7 +3,7 @@ // own `usage` read. Nothing is stored; it is an estimate, not a bill. import type { Agent, Agents } from "../../features/agents/service"; import { loadPrices } from "../usage/pricing"; -import { dayStart, stats, sum, type Total } from "../usage/stats"; +import { since, stats, sum, type Total } from "../usage/stats"; export const COST_DAYS = 7; @@ -30,8 +30,10 @@ export async function weekCost( ): Promise { const read = agents.types().find((type) => type.key === agent.type)?.usage; if (!read || agent.place !== "here") throw new Error("No usage"); + // Usage's window, not just the week: a harness that shares one read + // between concurrent callers keeps only what the first one asked for. const [sessions] = await Promise.all([ - read(agent, { since: dayStart(now, COST_DAYS - 1), signal }), + read(agent, { since: since(now), signal }), loadPrices().catch(() => {}), ]); const week = stats( From 1b53680a11c117dda2d8c45a8a433bac0f1bdc14 Mon Sep 17 00:00:00 2001 From: Riley Crane Date: Mon, 16 Nov 2026 18:00:18 -0800 Subject: [PATCH 5/6] fix(bestie): keep a focused Retry through the cost read Retry cleared the failed read, so the loading row replaced the focused button and a keyboard user lost their place. Keep the failed row, with Retry busy, until the read settles; on recovery, hand focus to Open Usage, or to the daily sparkline while Usage is off. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Riley Crane --- src/bundled/bestie/CostRow.test.tsx | 51 +++++++++++++++++++++++- src/bundled/bestie/CostRow.tsx | 61 +++++++++++++++++++++++------ 2 files changed, 98 insertions(+), 14 deletions(-) diff --git a/src/bundled/bestie/CostRow.test.tsx b/src/bundled/bestie/CostRow.test.tsx index dc908dc04a..b9ccf78e0c 100644 --- a/src/bundled/bestie/CostRow.test.tsx +++ b/src/bundled/bestie/CostRow.test.tsx @@ -165,7 +165,7 @@ it("leaves Usage's month whole when its read joins the week's", async () => { from, new AbortController().signal, ); - const goosey = agentsWith((reader: Agent, options: { since: number }) => + const goosey = agentsWith((_: Agent, options: { since: number }) => read(options.since), ); const [week, month] = await Promise.all([ @@ -282,6 +282,55 @@ it("shows a quiet error when the read rejects, and reads again on Retry", async expect(usage).toHaveBeenCalledTimes(2); }); +it.each([ + ["Open Usage", usageOn, { role: "button", name: "Open Usage" }], + [ + "the week while Usage is off", + cards(false), + { role: "img", name: /Daily cost/ }, + ], +] as const)( + "keeps a focused Retry while it reads, then hands focus to %s", + async (_, settingsCards, target) => { + const user = userEvent.setup(); + const reads: ((result: SessionUsage[] | Error) => void)[] = []; + const usage = vi.fn( + () => + new Promise((resolve, reject) => + reads.push((result) => + result instanceof Error ? reject(result) : resolve(result), + ), + ), + ); + render( + , + ); + await vi.waitFor(() => expect(reads).toHaveLength(1)); + act(() => reads[0]?.(new Error("first"))); + const retry = await screen.findByRole("button", { name: "Retry" }); + await user.click(retry); + await vi.waitFor(() => expect(reads).toHaveLength(2)); + // The read is pending: the same Retry stays, busy and focused. + expect(screen.getByRole("button", { name: "Retry" })).toBe(retry); + expect(retry).toHaveFocus(); + expect(retry).toHaveAttribute("aria-busy", "true"); + // A failed retry leaves it focused for another. + await act(async () => reads[1]?.(new Error("second"))); + await vi.waitFor(() => expect(retry).not.toHaveAttribute("aria-busy")); + expect(retry).toHaveFocus(); + await user.click(retry); + await vi.waitFor(() => expect(reads).toHaveLength(3)); + await act(async () => reads[2]?.([session("one", [request(0, 0.4)])])); + expect(await screen.findByText("$0.40")).toBeVisible(); + expect(screen.getByRole(target.role, { name: target.name })).toHaveFocus(); + }, +); + it("stops reading when the tab closes", async () => { let signal: AbortSignal | undefined; const usage = vi.fn( diff --git a/src/bundled/bestie/CostRow.tsx b/src/bundled/bestie/CostRow.tsx index 31b32adc72..e460759831 100644 --- a/src/bundled/bestie/CostRow.tsx +++ b/src/bundled/bestie/CostRow.tsx @@ -1,4 +1,12 @@ -import { useEffect, useState, useSyncExternalStore } from "react"; +import { + type Ref, + useCallback, + useEffect, + useLayoutEffect, + useRef, + useState, + useSyncExternalStore, +} from "react"; import type { Agent, Agents } from "../../features/agents/service"; import { settingsTarget } from "../../features/navigation/buzz-links"; import type { Navigation } from "../../features/navigation/controller"; @@ -19,11 +27,13 @@ const day = (start: number) => }); /** A bar per day, tallest the costliest day; the figures are in its label. */ -function Sparkline({ week }: { week: WeekCost }) { +function Sparkline({ ref, week }: { ref: Ref; week: WeekCost }) { const top = Math.max(...week.days.map((entry) => entry.cost.value ?? 0), 0); return ( `${day(entry.start)} ${costText(entry.cost)}`) .join(", ")}`} @@ -71,23 +81,45 @@ export function CostRow({ const usagePage = useSyncExternalStore(settingsCards.subscribe, () => settingsCards.has(USAGE), ); - const [week, setWeek] = useState(); + // A read is kept for the agent it was for; Retry keeps the failed one, and + // its focused Retry, on screen until the next read settles. + const key = `${agent.pubkey}:${agent.type}`; + const [read, setRead] = useState<{ key: string; week: WeekCost | "error" }>(); + const week = read?.key === key ? read.week : undefined; const [attempt, setAttempt] = useState(0); + const [pending, setPending] = useState(false); // biome-ignore lint/correctness/useExhaustiveDependencies: Reads again for another agent or a retry. useEffect(() => { - setWeek(undefined); if (!readable) return; + setPending(true); const controller = new AbortController(); - weekCost(agents, agent, controller.signal).then( - (read) => { - if (!controller.signal.aborted) setWeek(read); - }, - () => { - if (!controller.signal.aborted) setWeek("error"); - }, + const settle = (result: WeekCost | "error") => { + if (controller.signal.aborted) return; + setRead({ key, week: result }); + setPending(false); + }; + weekCost(agents, agent, controller.signal).then(settle, () => + settle("error"), ); return () => controller.abort(); - }, [agent.pubkey, agent.type, readable, attempt]); + }, [key, readable, attempt]); + const retryFocus = useRef(false); + const retryButton = useCallback((button: HTMLButtonElement | null) => { + if (!button) return; + // Capture ownership before removal, not after focus has fallen to body. + return () => { + retryFocus.current = document.activeElement === button; + }; + }, []); + const openUsage = useRef(null); + const cost = useRef(null); + useLayoutEffect(() => { + if (!retryFocus.current) return; + retryFocus.current = false; + // A recovered Retry hands its focus to the week it read. + if (week === "error" || document.activeElement !== document.body) return; + (openUsage.current ?? cost.current)?.focus({ preventScroll: true }); + }, [week]); const title = `Cost, last ${COST_DAYS} days`; if (!readable) return ( @@ -107,7 +139,9 @@ export function CostRow({ subtitle="Couldn't read this agent's sessions." trailing={(label) => (
- + {costText(week.total)} {usagePage && ( - )} +
)} /> diff --git a/src/bundled/bestie/README.md b/src/bundled/bestie/README.md index d65153fac3..8afa08ea10 100644 --- a/src/bundled/bestie/README.md +++ b/src/bundled/bestie/README.md @@ -83,11 +83,12 @@ no Bestie to your account: the agent stays, its check-ins stop, and its memory section and private channels stay, which its Former Bestie tab can turn off. Both need an account to save none to. -**Cost, last 7 days** shows what the agent's sessions on this device cost over -the last seven days: a bar for each day, today last, the total, and, while the -Usage plugin is on, **Open Usage**, which opens Settings → Usage (not filtered -to this agent; Usage keeps its own filters). With Usage off, its settings card -is not registered, so the row shows the figures without the button. It reads the sessions when the tab opens, through the same +**Cost, last 7 days** is there only while the Usage plugin is on. It shows +what the agent's sessions on this device cost over the last seven days: a bar +for each day, today last, the total, and **Open Usage**, which opens Settings → +Usage (not filtered to this agent; Usage keeps its own filters). With Usage off, +its settings card is not registered, so neither tab shows the row and nothing is +read; turning Usage off stops a read under way. It reads the sessions when the tab opens, through the same agent-type `usage` read and the same estimate as the Usage plugin (`stats()` and its price data are imported from it), and keeps nothing: no stored state, no sync. A cost is an estimate from the harness's own record or its token counts at