Repository navigation
feat(web): show each bot chat's model and tool usage #146
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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( | ||
| <QueryClientProvider client={client}> | ||
| <ChatUsage botId="b1" /> | ||
| </QueryClientProvider>, | ||
| ); | ||
| }); | ||
|
|
||
| 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(); | ||
| } | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 ( | ||
| <li className="flex items-baseline gap-2 text-sm"> | ||
| <span className="min-w-0 flex-1 truncate" title={row.name}> | ||
| {label(row)} | ||
| {row.kind === "tool" && ( | ||
| <span className="text-muted-foreground"> (tool)</span> | ||
| )} | ||
| </span> | ||
| <span className="shrink-0 text-xs text-muted-foreground tabular-nums"> | ||
| {[formatTokens(row.tokens), cost].filter(Boolean).join(" · ")} | ||
| </span> | ||
| </li> | ||
| ); | ||
| } | ||
|
|
||
| /** 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 ( | ||
| <section className="flex flex-col gap-3"> | ||
| <h2 className="text-sm font-medium text-muted-foreground">Usage</h2> | ||
| {rows.length === 0 ? ( | ||
| <p className="text-sm text-muted-foreground">No usage yet</p> | ||
| ) : ( | ||
| <> | ||
| <ul className="flex flex-col gap-1.5"> | ||
| {rows.map((row) => ( | ||
| <Row key={`${row.kind}:${row.name}`} row={row} /> | ||
| ))} | ||
| </ul> | ||
| {total && ( | ||
| <p className="text-xs text-muted-foreground"> | ||
| Total {total}. Jobs have their own usage. | ||
| </p> | ||
| )} | ||
| </> | ||
| )} | ||
| </section> | ||
| ); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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"); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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<typeof usageDocument>; | ||
|
|
||
| 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), | ||
| ); | ||
| } |
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
React Doctor ·
react-doctor/rendering-conditional-render(warning)Your users see a stray '0' on screen when a number before
&&is zero, so usevalue > 0,Boolean(value), or a ternary instead.Fix → Use
{items.length > 0 && <List />}, or a ternary like{items.length ? <List /> : null}.Docs