diff --git a/docs/buzz-help.md b/docs/buzz-help.md index bfda636962..3cec2576c0 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -1286,7 +1286,11 @@ 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. While the Usage plugin is on, 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. With Usage off there is no Cost row. - 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..648320062c 100644 --- a/src/bundled/bestie/BestieTab.test.tsx +++ b/src/bundled/bestie/BestieTab.test.tsx @@ -45,6 +45,8 @@ 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; +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. */ @@ -124,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); + 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. @@ -159,6 +161,66 @@ 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, settingsCards); + 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?.(); +}); + +it("shows no cost on a Bestie or a Former Bestie, and reads none, while Usage is off", async () => { + const usage = vi.fn(async () => []); + const agents = { + ...host().agents, + types: () => [{ key: "test/echo", adopt: () => ({}), usage }], + } as unknown as Parameters[1]; + const usageOff = { has: () => false, subscribe: () => () => {} }; + const bestie = community(ada.pubkey); + const tab = bestieTab(bestie.relay, agents, navigation, usageOff); + const stop = tab.subscribe?.(() => {}); + await vi.waitFor(() => expect(tab.when?.(ada)).toBe(true)); + const Tab = tab.component; + const { unmount } = render(); + expect(screen.getByText("This is your Bestie")).toBeVisible(); + expect(screen.queryByText("Cost, last 7 days")).toBeNull(); + unmount(); + stop?.(); + + const remembering = { + ...ada, + config: { instructions: withFeature("Be brief.", memory, true) }, + } as Agent; + const former = formerBestieTab( + community(bea.pubkey).relay, + agents, + navigation, + usageOff, + ); + const stopFormer = former.subscribe?.(() => {}); + await vi.waitFor(() => expect(former.when?.(remembering)).toBe(true)); + const Former = former.component; + render(); + expect(screen.getByText("Private channels Ada can read")).toBeVisible(); + expect(screen.queryByText("Cost, last 7 days")).toBeNull(); + expect(usage).not.toHaveBeenCalled(); + stopFormer?.(); +}); + const deviceChoice = () => readView(SCOPE, "solo:default-agent", null); /** Opens Change and confirms Bea in place of Ada. */ @@ -178,7 +240,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, settingsCards); const stop = tab.subscribe?.(() => {}); await vi.waitFor(() => expect(tab.when?.(ada)).toBe(true)); const Tab = tab.component; @@ -196,7 +258,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, settingsCards); const subscribe = tab.subscribe ?? (() => () => {}); const stop = subscribe(() => {}); await vi.waitFor(() => expect(tab.when?.(ada)).toBe(true)); @@ -228,7 +290,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, settingsCards); const stop = tab.subscribe?.(() => {}); await vi.waitFor(() => expect(tab.when?.(ada)).toBe(true)); const Tab = tab.component; @@ -245,7 +307,12 @@ 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, + settingsCards, + ).component; await act(async () => { render(); }); @@ -269,7 +336,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).component; + const Tab = bestieTab( + relay, + host([]).agents, + navigation, + settingsCards, + ).component; await act(async () => { render(); }); @@ -289,7 +361,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, settingsCards).component; await act(async () => { render(); }); @@ -339,7 +411,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, settingsCards); const stop = tab.subscribe?.(() => {}); await vi.waitFor(() => expect(tab.when?.(ada)).toBe(true)); stop?.(); @@ -351,7 +423,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, settingsCards).component; await act(async () => { render(); }); @@ -384,7 +456,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, settingsCards).component; await act(async () => { render(); }); @@ -414,7 +486,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, settingsCards).component; await act(async () => { render(); }); @@ -440,7 +512,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).component; + const Tab = bestieTab( + relay, + host().agents, + navigation, + settingsCards, + ).component; await act(async () => { render(); }); @@ -456,7 +533,12 @@ 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, + settingsCards, + ).component; await act(async () => { render(); }); @@ -486,7 +568,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, settingsCards); const changed = vi.fn(); const stop = tab.subscribe?.(changed); await vi.waitFor(() => expect(tab.when?.(ada)).toBe(true)); @@ -505,7 +587,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, settingsCards).component; const base = { instructions: "head-1" }; const agent = { ...ada, @@ -550,7 +632,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, settingsCards).component; const base = { instructions: "head-2" }; const on = withFeature("Be brief.", memory, true); const close = ""; @@ -596,7 +678,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, settingsCards).component; render(); const remembers = screen.getByRole("switch", { name: "Remembers you" }); await user.click(remembers); @@ -614,7 +696,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, settingsCards).component; render( ); const hourly = screen.getByRole("switch", { name: "Hourly notes" }); save.mockRejectedValueOnce(new Error("Connect to the community to save")); @@ -806,7 +888,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, settingsCards).component; const left = (slug: string, value: object) => ({ ...remembering(true), @@ -842,7 +924,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, settingsCards).component; const paused = { ...remembering(true), attention: { @@ -869,7 +951,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, settingsCards); const remembering = { ...ada, config: { instructions: withFeature("Be brief.", memory, true) }, @@ -916,8 +998,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, settingsCards); + const former = formerBestieTab(relay, agents, navigation, settingsCards); const remembering = { ...ada, config: { instructions: withFeature("Be brief.", memory, true) }, @@ -968,7 +1050,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, settingsCards); const listener = vi.fn(); const stop = tab.subscribe?.(listener); // Its instructions aren't on this device until its provider is read. @@ -1022,7 +1104,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, 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. @@ -1055,7 +1137,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, 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. @@ -1081,7 +1163,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, settingsCards); const stop = tab.subscribe?.(() => {}); await vi.waitFor(() => expect(tab.when?.(bea)).toBe(false)); const remembering = withFeature("Be brief.", memory, true); @@ -1112,7 +1194,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, settingsCards); const stop = tab.subscribe?.(() => {}); await vi.waitFor(() => expect(tab.when?.(bea)).toBe(false)); let answer = (_text: string) => {}; @@ -1161,7 +1243,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, settingsCards); const stop = tab.subscribe?.(() => {}); await vi.waitFor(() => expect(tab.when?.(remote)).toBe(true)); const Tab = tab.component; @@ -1184,7 +1266,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, settingsCards); const stop = tab.subscribe?.(() => {}); await vi.waitFor(() => expect(tab.when?.(bea)).toBe(false)); get.mockRejectedValueOnce(new Error("Builderlab is down.")); @@ -1208,7 +1290,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, settingsCards); const stop = tab.subscribe?.(() => {}); await vi.waitFor(() => expect(tab.when?.(bea)).toBe(false)); const Tab = tab.component; @@ -1236,7 +1318,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); + const former = formerBestieTab( + relay, + host().agents, + navigation, + settingsCards, + ); const remembering = { ...ada, config: { instructions: withFeature("Be brief.", memory, true) }, @@ -1257,7 +1344,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); + const former = formerBestieTab( + relay, + host().agents, + navigation, + settingsCards, + ); const stop = former.subscribe?.(() => {}); await act(async () => {}); expect(mainAgent.read).toHaveBeenCalled(); @@ -1273,7 +1365,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).component; + const Tab = bestieTab( + relay, + host().agents, + navigation, + settingsCards, + ).component; await act(async () => { render(); }); @@ -1285,7 +1382,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).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 277ba80cb9..e94cd78346 100644 --- a/src/bundled/bestie/BestieTab.tsx +++ b/src/bundled/bestie/BestieTab.tsx @@ -5,6 +5,8 @@ import type { AgentAddedTab, 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"; @@ -23,6 +25,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, @@ -48,9 +51,15 @@ 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): AgentAddedTab { +export function bestieTab( + relay: RelayData, + agents: TabAgents, + navigation: Pick, + settingsCards: TabCards, +): AgentAddedTab { const bestie = savedBestie(relay); return { id: "bestie", @@ -62,7 +71,13 @@ export function bestieTab(relay: RelayData, agents: TabAgents): AgentAddedTab { inCommunity(agent, relay.snapshot()), subscribe: bestie.subscribe, component: ({ agent }) => ( - + ), }; } @@ -74,6 +89,8 @@ export function bestieTab(relay: RelayData, agents: TabAgents): AgentAddedTab { export function formerBestieTab( relay: RelayData, agents: TabAgents, + navigation: Pick, + settingsCards: TabCards, ): AgentAddedTab { const bestie = savedBestie(relay); return { @@ -105,7 +122,14 @@ export function formerBestieTab( }; }, component: ({ agent }) => ( - + ), }; } @@ -170,11 +194,15 @@ function BestieTab({ relay, agents, agent, + navigation, + settingsCards, former = false, }: { relay: RelayData; agents: TabAgents; agent: Agent; + navigation: Pick; + settingsCards: TabCards; former?: boolean; }) { const { session, scope } = useRelayConnection(relay); @@ -271,6 +299,12 @@ function BestieTab({ )} /> )} + diff --git a/src/bundled/bestie/CostRow.test.tsx b/src/bundled/bestie/CostRow.test.tsx new file mode 100644 index 0000000000..8d82e262e9 --- /dev/null +++ b/src/bundled/bestie/CostRow.test.tsx @@ -0,0 +1,366 @@ +// @vitest-environment jsdom +import "@testing-library/jest-dom/vitest"; +import { act, cleanup, render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import type { + Agent, + Agents, + SessionUsage, + UsageObservation, +} from "../../features/agents/service"; +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"; + +// 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 = { + 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, +}); +/** 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) => + ({ + 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 }); + // Usage's own window is read, so a read Usage joins misses nothing. + expect(usage).toHaveBeenCalledWith(agent, { + 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((_: 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(); + render( + [ + session("one", [request(0, 0.25), request(1, 1.5)]), + ])} + agent={agent} + open={open} + settingsCards={usageOn} + />, + ); + 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("shows nothing and reads nothing while Usage is off, until it is on", async () => { + const usage = vi.fn(async () => [session("one", [request(0, 0.25)])]); + const settingsCards = cards(false); + const { container } = render( + , + ); + expect(container).toBeEmptyDOMElement(); + expect(usage).not.toHaveBeenCalled(); + act(() => settingsCards.turn(true)); + expect(await screen.findByText("$0.25")).toBeVisible(); + expect(screen.getByRole("button", { name: "Open Usage" })).toBeVisible(); + expect(usage).toHaveBeenCalledTimes(1); + act(() => settingsCards.turn(false)); + expect(container).toBeEmptyDOMElement(); +}); + +it("stops its read when Usage turns off", async () => { + let signal: AbortSignal | undefined; + const usage = vi.fn( + (_: Agent, options: { signal: AbortSignal }) => + new Promise(() => { + signal = options.signal; + }), + ); + const settingsCards = cards(true); + render( + , + ); + await vi.waitFor(() => expect(signal).toBeDefined()); + act(() => settingsCards.turn(false)); + expect(signal?.aborted).toBe(true); +}); + +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.each([ + ["Open Usage", usageOn, { role: "button", name: "Open Usage" }], +] 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( + (_: 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..715a152ede --- /dev/null +++ b/src/bundled/bestie/CostRow.tsx @@ -0,0 +1,174 @@ +import { + 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"; +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; +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} + /> + ); + })} + + ); +} + +type Props = { + agents: Pick; + agent: Agent; + open: Navigation["open"]; + settingsCards: Pick; +}; + +/** The agent's estimated cost over the last week, only while the Usage plugin + * is on: with Usage off there is no row and nothing is read, and turning it + * off stops a read under way. */ +export function CostRow(props: Props) { + const { settingsCards } = props; + const usage = useSyncExternalStore(settingsCards.subscribe, () => + settingsCards.has(USAGE), + ); + return usage ? : null; +} + +/** The week's cost, 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. */ +function WeekCostRow({ agents, agent, open }: Props) { + const readable = readsUsage(agents, agent); + // 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(() => { + if (!readable) return; + setPending(true); + const controller = new AbortController(); + 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(); + }, [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); + 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?.focus({ preventScroll: true }); + }, [week]); + 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..8afa08ea10 100644 --- a/src/bundled/bestie/README.md +++ b/src/bundled/bestie/README.md @@ -83,6 +83,20 @@ 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** 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 +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..1558ed6426 --- /dev/null +++ b/src/bundled/bestie/cost.ts @@ -0,0 +1,51 @@ +// 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 { since, 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"); + // 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: since(now), 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..9b40f64b0c 100644 --- a/src/bundled/bestie/index.tsx +++ b/src/bundled/bestie/index.tsx @@ -34,10 +34,15 @@ export const inject = [ "agents", "conversation", "panels", + "settingsCards", ]; 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.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)); // A hosted former Bestie's memory is on its provider, read here for its tab. 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..3b21885dfd 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,15 @@ const agent = { ), }, } as unknown as Agent; -const tab = (former ? formerBestieTab : bestieTab)(relay, agents); +const navigation = { open: async () => {} }; +// 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");