From 31d4c164736985f4f351956ffa36a2b2434f0f37 Mon Sep 17 00:00:00 2001 From: Laura Thiel Date: Mon, 16 Nov 2026 13:22:44 +0100 Subject: [PATCH] feat(web): show each bot chat's model and tool usage A bot's details list the tokens and cost of every model and tool its bot chat has used, with a total. Job panes now include the tools bucket in their cost. Closes #105 --- CHANGELOG.md | 1 + apps/docs/content/concepts/chats.mdx | 9 ++ apps/server/src/contract/tool-details.ts | 17 ++-- .../features/bot-chat/chat-usage.dom.test.tsx | 95 +++++++++++++++++++ apps/web/features/bot-chat/chat-usage.tsx | 62 ++++++++++++ apps/web/features/bot-chat/details.tsx | 2 + apps/web/features/chat/usage.test.ts | 50 ++++++++++ apps/web/features/chat/usage.ts | 45 +++++++++ apps/web/features/jobs/jobs.test.ts | 21 ---- apps/web/features/jobs/jobs.tsx | 19 ++-- 10 files changed, 278 insertions(+), 43 deletions(-) create mode 100644 apps/web/features/bot-chat/chat-usage.dom.test.tsx create mode 100644 apps/web/features/bot-chat/chat-usage.tsx create mode 100644 apps/web/features/chat/usage.test.ts create mode 100644 apps/web/features/chat/usage.ts delete mode 100644 apps/web/features/jobs/jobs.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 80e3bae6..6f51fb0c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- A bot's details in the web chat show **Usage**: tokens and cost for each model and tool its bot chat has used, with a total. Job panes now include tool costs, such as intent checks, in their cost. - Pinned conversations are saved on the account, so every app shows the same pins in the same order. The session returns them as `pinnedConversations`, `update-user` saves the whole list (up to nine `agent:` or `group:` keys), and `/v1/events` sends a `pins` event to the account's open apps when they change. On the web, pin or unpin a bot chat or group chat from its **More** menu in the sidebar, and drag pins in the **Pinned** section to reorder them. - Bots may stay quiet after automations. A scheduled or event automation, and a succeeded script automation's result, tell the bot it can react with ๐Ÿ‘ instead of replying when the run found nothing the owner needs, unless the automation asks for a message every time. A reaction sends no notification. Results of failed, timed-out, and interrupted script runs don't carry the note. - Push notifications wait at least three seconds after enqueue and are suppressed on every device when the reply was seen or its bot or group chat is active in a focused web tab. Request cards count as seen only after their content loads and appears in the viewport. Browser notifications and unread counters are unchanged. diff --git a/apps/docs/content/concepts/chats.mdx b/apps/docs/content/concepts/chats.mdx index 503c3a00..be1ffbe3 100644 --- a/apps/docs/content/concepts/chats.mdx +++ b/apps/docs/content/concepts/chats.mdx @@ -46,6 +46,15 @@ flowchart LR **Compaction never deletes anything you can see.** It only changes what the bot reads on its next turn. +## Usage + +In the web client, a bot's details show **Usage** for its bot chat: the tokens +and cost of each model the chat has used, including the vision model, and of +tools that call a model of their own, such as questions to the vision model. +Providers that bill by subscription, such as Claude Code, report no cost, so +only their tokens show. Jobs keep their own usage, including their intent +checks, shown in each job's pane. + ## Files In the web client, attach any file up to 100 MB, with at most eight files per diff --git a/apps/server/src/contract/tool-details.ts b/apps/server/src/contract/tool-details.ts index c5b6cfe9..b10c1578 100644 --- a/apps/server/src/contract/tool-details.ts +++ b/apps/server/src/contract/tool-details.ts @@ -3,16 +3,15 @@ import { botRequestResponse } from "./api-responses"; import type { ChartLayout } from "./chart"; import { webSource } from "./web-search"; -/** Pi Durable's usage document, as far as clients sum its cost. */ +const usageTotals = z.looseObject({ + totalTokens: z.number().optional(), + cost: z.looseObject({ total: z.number().optional() }).optional(), +}); + +/** Pi Durable's usage document, as far as clients sum its tokens and cost. `tools` holds tool results' own spend, such as vision and intent checks. */ export const usageDocument = z.looseObject({ - models: z - .record( - z.string(), - z.looseObject({ - cost: z.looseObject({ total: z.number().optional() }).optional(), - }), - ) - .optional(), + models: z.record(z.string(), usageTotals).optional(), + tools: z.record(z.string(), usageTotals).optional(), }); export const jobDetails = z.object({ diff --git a/apps/web/features/bot-chat/chat-usage.dom.test.tsx b/apps/web/features/bot-chat/chat-usage.dom.test.tsx new file mode 100644 index 00000000..2b4fa717 --- /dev/null +++ b/apps/web/features/bot-chat/chat-usage.dom.test.tsx @@ -0,0 +1,95 @@ +import { expect, test } from "bun:test"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { Window } from "happy-dom"; +import { act } from "react"; +import { CHAT_KEY } from "@/features/chat/api"; +import type { UsageDocument } from "@/features/chat/usage"; +import { ChatUsage } from "./chat-usage"; + +async function render(usage: UsageDocument | undefined) { + const window = new Window({ url: "http://localhost" }); + const globals = Object.getOwnPropertyDescriptors(globalThis); + Object.defineProperties(globalThis, { + window: { configurable: true, value: window }, + document: { configurable: true, value: window.document }, + HTMLElement: { configurable: true, value: window.HTMLElement }, + IS_REACT_ACT_ENVIRONMENT: { configurable: true, value: true }, + }); + + // Fresh cached data: the section reads the snapshot the chat already streams, with no request of its own. + const client = new QueryClient({ + defaultOptions: { queries: { retry: false, staleTime: Infinity } }, + }); + + // The section reads only `usage`, so the rest of the snapshot is left out. + client.setQueryData([CHAT_KEY, "b1"], { usage }); + + const { createRoot } = await import("react-dom/client"); + const container = document.createElement("div"); + document.body.append(container); + const root = createRoot(container); + + await act(async () => { + root.render( + + + , + ); + }); + + return { + container, + cleanup: async () => { + await act(async () => root.unmount()); + client.clear(); + await window.happyDOM.abort(); + Object.defineProperties(globalThis, globals); + }, + }; +} + +test("lists the chat's models and tools with tokens, cost, and a total", async () => { + const { container, cleanup } = await render({ + models: { + "openai/gpt-5": { totalTokens: 12_345, cost: { total: 0.25 } }, + }, + tools: { intent: { totalTokens: 900, cost: { total: 0.01 } } }, + }); + + try { + const rows = [...container.querySelectorAll("li")].map( + (row) => row.textContent, + ); + + expect(rows).toEqual([ + "gpt-512K tokens ยท $0.2500", + "intent (tool)900 tokens ยท $0.0100", + ]); + expect(container.textContent).toContain("Total $0.2600."); + } finally { + await cleanup(); + } +}); + +test("shows tokens without a cost for a subscription provider", async () => { + const { container, cleanup } = await render({ + models: { "claude-code/opus": { totalTokens: 50, cost: { total: 0 } } }, + }); + + try { + expect(container.querySelector("li")?.textContent).toBe("opus50 tokens"); + expect(container.textContent).not.toContain("Total"); + } finally { + await cleanup(); + } +}); + +test("says so before the chat's first request", async () => { + const { container, cleanup } = await render(undefined); + + try { + expect(container.textContent).toContain("No usage yet"); + } finally { + await cleanup(); + } +}); diff --git a/apps/web/features/bot-chat/chat-usage.tsx b/apps/web/features/bot-chat/chat-usage.tsx new file mode 100644 index 00000000..32baa42b --- /dev/null +++ b/apps/web/features/bot-chat/chat-usage.tsx @@ -0,0 +1,62 @@ +import { useQuery } from "@tanstack/react-query"; +import { usageDocument } from "@crumble/server/contract/tool-details"; +import { chatQuery } from "@/features/chat/api"; +import { + type UsageRow, + costLine, + formatCost, + formatTokens, + usageRows, +} from "@/features/chat/usage"; + +/** `provider/modelId` shows as the model ID; the provider is the bot's or obvious from it. */ +const label = (row: UsageRow) => + row.kind === "model" ? row.name.slice(row.name.indexOf("/") + 1) : row.name; + +function Row({ row }: { row: UsageRow }) { + const cost = formatCost(row.cost); + + return ( +
  • + + {label(row)} + {row.kind === "tool" && ( + (tool) + )} + + + {[formatTokens(row.tokens), cost].filter(Boolean).join(" ยท ")} + +
  • + ); +} + +/** Tokens and cost of the bot chat's own models and tools, from the live snapshot. */ +export function ChatUsage({ botId }: { botId: string }) { + const snapshot = useQuery(chatQuery(botId)).data; + const usage = usageDocument.safeParse(snapshot?.usage).data; + const rows = usageRows(usage); + const total = costLine(usage); + + return ( +
    +

    Usage

    + {rows.length === 0 ? ( +

    No usage yet

    + ) : ( + <> +
      + {rows.map((row) => ( + + ))} +
    + {total && ( +

    + Total {total}. Jobs have their own usage. +

    + )} + + )} +
    + ); +} diff --git a/apps/web/features/bot-chat/details.tsx b/apps/web/features/bot-chat/details.tsx index 6b1008d0..ad2e6f0f 100644 --- a/apps/web/features/bot-chat/details.tsx +++ b/apps/web/features/bot-chat/details.tsx @@ -21,6 +21,7 @@ import { DesktopPreview } from "@/features/bot-desktop/desktop"; import { finished } from "@/features/automations/timing"; import { BOT_TOOL } from "@crumble/server/contract/tools"; import { RecentFiles } from "@/features/library/recent"; +import { ChatUsage } from "./chat-usage"; function Automation({ schedule }: { schedule: Schedule }) { const toggle = useMutation(toggleScheduleOptions(schedule.id)); @@ -111,6 +112,7 @@ function DetailsBody({ bot, onClose }: { bot: Bot; onClose: () => void }) { + ); } diff --git a/apps/web/features/chat/usage.test.ts b/apps/web/features/chat/usage.test.ts new file mode 100644 index 00000000..d5a83f80 --- /dev/null +++ b/apps/web/features/chat/usage.test.ts @@ -0,0 +1,50 @@ +import { expect, test } from "bun:test"; +import { usageDocument } from "@crumble/server/contract/tool-details"; +import { costLine, formatTokens, usageRows } from "./usage"; + +const priced = { totalTokens: 1200, cost: { total: 1.5 } }; + +test("costLine sums every model", () => { + expect(costLine({ models: { "a/one": priced, "b/two": priced } })).toBe( + "$3.0000", + ); +}); + +test("costLine counts tools such as vision and intent checks", () => { + expect( + costLine({ models: { "a/one": priced }, tools: { intent: priced } }), + ).toBe("$3.0000"); +}); + +test("costLine is empty for a provider that reports no cost", () => { + expect( + costLine({ models: { "claude-code/one": { cost: { total: 0 } } } }), + ).toBeNull(); +}); + +test("costLine is empty before the first request", () => { + expect(costLine(undefined)).toBeNull(); + expect(costLine({ models: {} })).toBeNull(); +}); + +test("usageRows lists models, then tools, with tokens and cost", () => { + expect( + usageRows({ + tools: { vision: { totalTokens: 300 } }, + models: { "a/one": priced }, + }), + ).toEqual([ + { kind: "model", name: "a/one", tokens: 1200, cost: 1.5 }, + { kind: "tool", name: "vision", tokens: 300, cost: 0 }, + ]); +}); + +test("a document that doesn't parse has no rows", () => { + expect(usageRows(usageDocument.safeParse("nonsense").data)).toEqual([]); +}); + +test("formatTokens abbreviates large counts", () => { + expect(formatTokens(1)).toBe("1 token"); + expect(formatTokens(950)).toBe("950 tokens"); + expect(formatTokens(12_345)).toBe("12K tokens"); +}); diff --git a/apps/web/features/chat/usage.ts b/apps/web/features/chat/usage.ts new file mode 100644 index 00000000..aa2254b9 --- /dev/null +++ b/apps/web/features/chat/usage.ts @@ -0,0 +1,45 @@ +import type { z } from "zod"; +import type { usageDocument } from "@crumble/server/contract/tool-details"; + +/** Parse with `usageDocument` where it arrives: the API types a usage document as unknown. */ +export type UsageDocument = z.infer; + +type Bucket = UsageDocument["models"]; + +export type UsageRow = { + kind: "model" | "tool"; + /** `provider/modelId` for a model, the tool's name for a tool. */ + name: string; + tokens: number; + cost: number; +}; + +/** A usage document's models, then its tools, each with its tokens and cost. */ +export function usageRows(document: UsageDocument | undefined): UsageRow[] { + const rows = (kind: UsageRow["kind"], bucket: Bucket) => + Object.entries(bucket ?? {}).map(([name, totals]) => ({ + kind, + name, + tokens: totals.totalTokens ?? 0, + cost: totals.cost?.total ?? 0, + })); + + return [...rows("model", document?.models), ...rows("tool", document?.tools)]; +} + +/** Subscription providers such as Claude Code report zero, which says nothing, so zero shows no cost. */ +export function formatCost(cost: number) { + return cost > 0 ? `$${cost.toFixed(4)}` : null; +} + +const compact = new Intl.NumberFormat("en", { notation: "compact" }); + +export const formatTokens = (tokens: number) => + `${compact.format(tokens)} ${tokens === 1 ? "token" : "tokens"}`; + +/** The cost of every model and tool in a usage document, or null when nothing reported one. */ +export function costLine(document: UsageDocument | undefined) { + return formatCost( + usageRows(document).reduce((sum, row) => sum + row.cost, 0), + ); +} diff --git a/apps/web/features/jobs/jobs.test.ts b/apps/web/features/jobs/jobs.test.ts deleted file mode 100644 index ab388978..00000000 --- a/apps/web/features/jobs/jobs.test.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { expect, test } from "bun:test"; -import { costLine } from "./jobs"; - -const priced = { cost: { total: 1.5 } }; - -test("costLine sums every model", () => { - expect(costLine({ models: { "a/one": priced, "b/two": priced } })).toBe( - "$3.0000", - ); -}); - -test("costLine is empty for a provider that reports no cost", () => { - expect( - costLine({ models: { "claude-code/one": { cost: { total: 0 } } } }), - ).toBeNull(); -}); - -test("costLine is empty before the first request", () => { - expect(costLine(undefined)).toBeNull(); - expect(costLine({ models: {} })).toBeNull(); -}); diff --git a/apps/web/features/jobs/jobs.tsx b/apps/web/features/jobs/jobs.tsx index fe3feb10..7c7ead33 100644 --- a/apps/web/features/jobs/jobs.tsx +++ b/apps/web/features/jobs/jobs.tsx @@ -33,19 +33,9 @@ import { api } from "@/lib/api"; import { JOB_KINDS } from "./kinds"; import { type JobRef } from "./api"; import { Reply } from "@/components/markdown"; -import { usageDocument } from "@crumble/server/contract/tool-details"; import { blocksOf } from "@/features/chat/tool-details"; - -/** A job's cost over its models. Subscription providers such as Claude Code report zero, which says nothing. */ -export function costLine(usage: Job["usage"]) { - const models = Object.values( - usageDocument.safeParse(usage).data?.models ?? {}, - ); - - const cost = models.reduce((sum, model) => sum + (model.cost?.total ?? 0), 0); - - return cost > 0 ? `$${cost.toFixed(4)}` : null; -} +import { costLine } from "@/features/chat/usage"; +import { usageDocument } from "@crumble/server/contract/tool-details"; const STEP_ICONS = { terminal: IconTerminal2, @@ -313,7 +303,10 @@ async function downloadTranscript(botId: string, job: JobRef) { function JobTitle({ job, current }: { job: JobRef; current: Job | undefined }) { const { icon: Icon } = JOB_KINDS[job.kind]; - const subtitle = [current?.model?.model, costLine(current?.usage)]; + const subtitle = [ + current?.model?.model, + costLine(usageDocument.safeParse(current?.usage).data), + ]; return ( <>