diff --git a/CHANGELOG.md b/CHANGELOG.md index ded79881..7c87ef95 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,7 @@ ## Unreleased - Bot avatars show what their bot is doing, using `open-bot-avatar` 0.3.0: three hopping dots while it thinks, bent over the work while it writes, searches, remembers, or uses tools, an exclamation mark while it retries, a short celebration when a reply finishes, and waiting in a group chat while it answers next. Live avatars ease from one state to the next instead of restarting. The `/avatars` page previews every state. Paused bots and disabled automations no longer show a dimmed, still avatar. -- 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. +- **Settings** > **Providers** has a **Usage** tab: tokens and cost for each model across all of the account's bots, grouped by provider, and for tools that call a model of their own, with totals. `GET /v1/usage` returns the same figures. Job panes now include tool costs, such as intent checks, in their cost. - When a bot's model can't read images and no vision model is set, the web chat warns as soon as an image is attached and links to the bot's profile and the vision model setting. The server refuses such a message before recording a turn, so the error shows once, names the bot, and the message goes back to the composer. `GET /v1/models` returns `images` for each model. - 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. diff --git a/apps/docs/content/concepts/chats.mdx b/apps/docs/content/concepts/chats.mdx index f15b5ea7..797dd6e4 100644 --- a/apps/docs/content/concepts/chats.mdx +++ b/apps/docs/content/concepts/chats.mdx @@ -46,15 +46,6 @@ 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/docs/content/getting-started/providers.md b/apps/docs/content/getting-started/providers.md index bbe61efa..cc7733fa 100644 --- a/apps/docs/content/getting-started/providers.md +++ b/apps/docs/content/getting-started/providers.md @@ -104,7 +104,17 @@ that read images. | **Set** | Gets the vision model's description of each image, including any visible text, and can ask it follow-up questions about an image. The transcript keeps the image. | The vision model describes each image once per conversation, and its tokens and -cost count toward the conversation's usage. Bots whose model reads images never -use it. +cost count toward [usage](#usage). Bots whose model reads images never use it. + +## Usage + +To see what your bots have spent, open **Settings** > **Providers** and select +**Usage**. It lists tokens and cost for each model, grouped by provider, with a +total for each provider and for your account. **Tools** lists tools that call a +model of their own, such as questions to the vision model and intent checks. + +Usage covers every bot's chat and jobs since each started. Deleting a bot +removes its usage. Providers that bill by subscription, such as Claude Code, +report no cost, so only their tokens show. Over the API, use `GET /v1/usage`. With a provider connected, [create your first bot](/getting-started/first-bot). diff --git a/apps/docs/content/reference/api.md b/apps/docs/content/reference/api.md index d7e45a82..30476aa0 100644 --- a/apps/docs/content/reference/api.md +++ b/apps/docs/content/reference/api.md @@ -65,7 +65,7 @@ The token reaches no other route. | **Event relay** | `/v1/event-relay`, `/v1/event-sources`, `/v1/event-sources/{id}` | | **Voice gateway** | `/v1/voice-gateway`, `/v1/voice-gateway/token` | | **Voice gateway token** | `GET /v1/voice/events`, `POST /v1/voice/lines/{username}/messages`, `GET /v1/voice/lines/{username}/events`, `GET /v1/voice/lines/{username}/executions/{executionId}`, `PUT /v1/voice/lines`, `PUT /v1/voice/lines/{username}/calls/{callId}`, `POST /v1/voice/calls/{callId}` | -| **Providers & models** | `/v1/providers`, `/v1/providers/{provider}`, `POST /v1/providers/{provider}/login`, `/v1/provider-logins/{id}`, `POST /v1/provider-logins/{id}/responses`, `/v1/models`, `/v1/vision-model` | +| **Providers & models** | `/v1/providers`, `/v1/providers/{provider}`, `POST /v1/providers/{provider}/login`, `/v1/provider-logins/{id}`, `POST /v1/provider-logins/{id}/responses`, `/v1/models`, `/v1/vision-model`, `/v1/usage` | | **Password managers** | `/v1/password-managers`, `/v1/password-managers/{id}` | | **MCP servers** | `/v1/mcp-servers`, `/v1/mcp-servers/{id}`, `/v1/mcp-servers/{id}/oauth`, `POST /v1/mcp-servers/{id}/oauth/callback` | diff --git a/apps/server/src/bots/bots-reads.ts b/apps/server/src/bots/bots-reads.ts index 7c5386cf..c11efce0 100644 --- a/apps/server/src/bots/bots-reads.ts +++ b/apps/server/src/bots/bots-reads.ts @@ -18,6 +18,7 @@ import { type TranscriptMessage, } from "../transcript/transcript"; import type { JobKindName } from "../shared/job-kinds"; +import { usageSummary } from "./usage-summary"; export const botsReads = (context: BotsContext, lookup: BotsLookup) => { const { agents, conversations, events, executions, runtime, schedules } = @@ -145,10 +146,26 @@ export const botsReads = (context: BotsContext, lookup: BotsLookup) => { ); }); + // A bot with no conversation has never called a model; skipping it leaves its harness unopened. + const usage = Effect.gen(function* () { + const states = yield* Effect.forEach( + yield* agents.list, + Effect.fnUntraced(function* (each) { + const [first] = yield* conversations.list(each.id, true); + + return first ? [yield* pi(() => runtime.usage(each))] : []; + }), + { concurrency: "unbounded" }, + ); + + return usageSummary(states.flat()); + }).pipe(Effect.withSpan("Bots.usage")); + return { origin, snapshot, agentPreviews, + usage, history: Effect.fn("Bots.history")(function* ( agentId: string, options: PageOptions, diff --git a/apps/server/src/bots/bots-service.ts b/apps/server/src/bots/bots-service.ts index f9257981..3f76e596 100644 --- a/apps/server/src/bots/bots-service.ts +++ b/apps/server/src/bots/bots-service.ts @@ -58,6 +58,7 @@ export const botsService = (context: BotsContext): Bots["Service"] => { changed: notifications.changed, onSettled: notifications.onSettled, agentPreviews: reads.agentPreviews, + usage: reads.usage, announceJobAnswer: notifications.announceJobAnswer, announce: notifications.emit, snapshot: reads.snapshot, diff --git a/apps/server/src/bots/bots.ts b/apps/server/src/bots/bots.ts index a0a4332e..98ee383d 100644 --- a/apps/server/src/bots/bots.ts +++ b/apps/server/src/bots/bots.ts @@ -25,6 +25,7 @@ import type { } from "../transcript/transcript"; import type { ReplyReference } from "../contract/push"; import type { CallEventData } from "../transcript/entries"; +import type { usageSummary } from "./usage-summary"; export type ChatPreviewActivity = { type: "chat-preview"; @@ -100,6 +101,8 @@ export class Bots extends Context.Service< readonly agentPreviews: Effect.Effect< { agent: Agent; lastMessage: string }[] >; + /** Tokens and cost of every model and tool across all of the account's bots, since each bot's first conversation. */ + readonly usage: Effect.Effect, AppError>; /** * Tells activity listeners about the bot's answer to a job's report, such as a desktop job asking for the owner. * Job reports reach the chat without an execution, so a finished execution never announces them. diff --git a/apps/server/src/bots/chat-api.ts b/apps/server/src/bots/chat-api.ts index 537dde49..fac9d1f5 100644 --- a/apps/server/src/bots/chat-api.ts +++ b/apps/server/src/bots/chat-api.ts @@ -5,6 +5,7 @@ import type { chatSnapshotResponse, codingJobsResponse, desktopJobsResponse, + usageResponse, } from "../contract/api-responses"; import type { Register } from "../contract/route"; import { attachmentHeaders } from "../shared/attachments"; @@ -30,6 +31,11 @@ const registerChatReadRoutes = (options: ChatRoutesOptions) => { return c.json(snapshot, 200); }); + register.plain(routes.usage, async (c) => { + const usage: z.output = await service.usage(); + + return c.json(usage, 200); + }); register.plain(routes.history, async (c) => c.json(await service.history(c.req.param("id"), c.req.valid("query")), 200), ); diff --git a/apps/server/src/bots/runtime.ts b/apps/server/src/bots/runtime.ts index a1363dc2..ffca2996 100644 --- a/apps/server/src/bots/runtime.ts +++ b/apps/server/src/bots/runtime.ts @@ -436,6 +436,11 @@ export class AgentRuntime { return (await this.open(agent)).harness; } + /** Every conversation's `pi.usage` in the bot's harness, summed: its chat, jobs, and any other conversation. */ + async usage(agent: Agent) { + return (await this.open(agent)).harness.usage(BACKGROUND_CONTEXT); + } + private skillTools(agent: Agent) { const currentAgent = () => { const current = this.callbacks.currentAgent(agent); diff --git a/apps/server/src/bots/usage-summary.test.ts b/apps/server/src/bots/usage-summary.test.ts new file mode 100644 index 00000000..8310b81d --- /dev/null +++ b/apps/server/src/bots/usage-summary.test.ts @@ -0,0 +1,55 @@ +import { expect, test } from "bun:test"; +import type { UsageState } from "@earendil-works/pi-durable"; +import { usageSummary } from "./usage-summary"; + +const usage = (totalTokens: number, cost: number) => ({ + input: totalTokens, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens, + cost: { input: cost, output: 0, cacheRead: 0, cacheWrite: 0, total: cost }, +}); + +test("sums each model and tool across bots, most tokens first", () => { + const first: UsageState = { + models: { + "anthropic/claude-sonnet-5-5": usage(100, 0.5), + "openai/gpt-6": usage(10, 0.25), + }, + tools: { vision: usage(5, 0.01) }, + }; + + const second: UsageState = { + models: { "openai/gpt-6": usage(200, 1) }, + tools: {}, + }; + + expect(usageSummary([first, second])).toEqual({ + models: [ + { provider: "openai", model: "gpt-6", tokens: 210, cost: 1.25 }, + { + provider: "anthropic", + model: "claude-sonnet-5-5", + tokens: 100, + cost: 0.5, + }, + ], + tools: [{ name: "vision", tokens: 5, cost: 0.01 }], + }); +}); + +test("splits a model key at its first slash", () => { + const state: UsageState = { + models: { "openrouter/meta/llama-5": usage(1, 0) }, + tools: {}, + }; + + expect(usageSummary([state]).models).toEqual([ + { provider: "openrouter", model: "meta/llama-5", tokens: 1, cost: 0 }, + ]); +}); + +test("returns empty lists without usage", () => { + expect(usageSummary([])).toEqual({ models: [], tools: [] }); +}); diff --git a/apps/server/src/bots/usage-summary.ts b/apps/server/src/bots/usage-summary.ts new file mode 100644 index 00000000..9ab28f14 --- /dev/null +++ b/apps/server/src/bots/usage-summary.ts @@ -0,0 +1,40 @@ +import type { UsageState } from "@earendil-works/pi-durable"; + +type Totals = { tokens: number; cost: number }; + +type Bucket = UsageState["models"]; + +const sum = (states: readonly UsageState[], bucket: keyof UsageState) => { + const totals = new Map(); + + for (const state of states) + for (const [key, usage] of Object.entries(state[bucket])) { + const total = totals.get(key) ?? { tokens: 0, cost: 0 }; + + total.tokens += usage.totalTokens; + total.cost += usage.cost.total; + totals.set(key, total); + } + + return [...totals].sort(([, a], [, b]) => b.tokens - a.tokens); +}; + +/** Pi Durable keys a model `provider/modelId`; a model ID may hold a slash of its own, so split at the first. */ +const modelOf = (key: string) => { + const slash = key.indexOf("/"); + + return slash < 0 + ? { provider: "", model: key } + : { provider: key.slice(0, slash), model: key.slice(slash + 1) }; +}; + +/** Tokens and cost of every model and tool across `states`, most tokens first. */ +export function usageSummary(states: readonly UsageState[]) { + return { + models: sum(states, "models").map(([key, totals]) => ({ + ...modelOf(key), + ...totals, + })), + tools: sum(states, "tools").map(([name, totals]) => ({ name, ...totals })), + }; +} diff --git a/apps/server/src/contract/api-contract.ts b/apps/server/src/contract/api-contract.ts index 37c0ae9c..fb19bd31 100644 --- a/apps/server/src/contract/api-contract.ts +++ b/apps/server/src/contract/api-contract.ts @@ -1580,6 +1580,14 @@ export const routes = { operationId: "listProviders", responses: { 200: json(z.array(response.providerResponse)) }, }), + usage: define({ + method: "get", + path: "/v1/usage", + operationId: "getUsage", + description: + "Tokens and cost of each model and tool across all of the account's bots: their chats, jobs, and other conversations, since each started. Most tokens first. A deleted bot's usage is gone with it.", + responses: { 200: json(response.usageResponse) }, + }), previewReasoning: define({ method: "post", path: "/v1/reasoning/preview", diff --git a/apps/server/src/contract/api-responses.ts b/apps/server/src/contract/api-responses.ts index a06df473..21053b7d 100644 --- a/apps/server/src/contract/api-responses.ts +++ b/apps/server/src/contract/api-responses.ts @@ -1025,6 +1025,26 @@ export const providerResponse = z }) .openapi("Provider"); +const usageTotals = { + tokens: z.number(), + cost: z.number().openapi({ + description: + "US dollars. Zero for providers that bill by subscription, such as Claude Code.", + }), +}; + +export const usageResponse = z + .object({ + models: z.array( + z.object({ provider: z.string(), model: z.string(), ...usageTotals }), + ), + tools: z.array(z.object({ name: z.string(), ...usageTotals })).openapi({ + description: + "Tools that call a model of their own, such as vision questions and intent checks.", + }), + }) + .openapi("Usage"); + /** One object rather than a union, so generated clients keep the nullable prompt. */ export const loginPrompt = z.object({ id: z.string(), diff --git a/apps/server/src/message-gateway/message-gateway.test.ts b/apps/server/src/message-gateway/message-gateway.test.ts index 1ef3c881..6554f93f 100644 --- a/apps/server/src/message-gateway/message-gateway.test.ts +++ b/apps/server/src/message-gateway/message-gateway.test.ts @@ -190,6 +190,7 @@ async function fixture( changed: unexpected, onSettled: unsubscribe, agentPreviews: unexpected(), + usage: unexpected(), announceJobAnswer: unexpected, announce: unexpected, snapshot: unexpected, diff --git a/apps/web/features/bot-chat/chat-usage.dom.test.tsx b/apps/web/features/bot-chat/chat-usage.dom.test.tsx deleted file mode 100644 index 2b4fa717..00000000 --- a/apps/web/features/bot-chat/chat-usage.dom.test.tsx +++ /dev/null @@ -1,95 +0,0 @@ -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 deleted file mode 100644 index c9a3f745..00000000 --- a/apps/web/features/bot-chat/chat-usage.tsx +++ /dev/null @@ -1,62 +0,0 @@ -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 !== null && ( -

    - 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 ad2e6f0f..6b1008d0 100644 --- a/apps/web/features/bot-chat/details.tsx +++ b/apps/web/features/bot-chat/details.tsx @@ -21,7 +21,6 @@ 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)); @@ -112,7 +111,6 @@ function DetailsBody({ bot, onClose }: { bot: Bot; onClose: () => void }) { - ); } diff --git a/apps/web/features/providers/api.ts b/apps/web/features/providers/api.ts index 154e7965..47ac2c1d 100644 --- a/apps/web/features/providers/api.ts +++ b/apps/web/features/providers/api.ts @@ -5,6 +5,7 @@ import type { loginSessionResponse, modelResponse, providerResponse, + usageResponse, visionModelResponse, } from "@crumble/server/contract/api-responses"; import { api, queryClient } from "@/lib/api"; @@ -15,6 +16,8 @@ export type ProviderSignIn = z.infer; export type Provider = z.infer; +export type Usage = z.infer; + export type JudgeModel = z.infer; export type VisionModel = z.infer; @@ -36,6 +39,11 @@ export const providersQuery = queryOptions({ queryFn: ({ signal }) => api<"providers">("/v1/providers", { signal }), }); +export const usageQuery = queryOptions({ + queryKey: ["usage"], + queryFn: ({ signal }) => api<"usage">("/v1/usage", { signal }), +}); + export async function invalidateProviders() { await queryClient.invalidateQueries({ queryKey: providersQuery.queryKey }); await queryClient.invalidateQueries({ queryKey: modelsKey }); diff --git a/apps/web/features/providers/provider-tile.tsx b/apps/web/features/providers/provider-tile.tsx new file mode 100644 index 00000000..4433fd6c --- /dev/null +++ b/apps/web/features/providers/provider-tile.tsx @@ -0,0 +1,18 @@ +import { MarkupLogo } from "@/components/brand-logo"; +import { RowTile } from "@/components/page"; +import type { Provider } from "./api"; +import { providerLogo } from "./provider-logos"; + +export function ProviderTile({ provider }: { provider: Provider }) { + const logo = providerLogo(provider.provider); + + return logo ? ( + + + + ) : ( + + {provider.name.slice(0, 1).toUpperCase()} + + ); +} diff --git a/apps/web/features/providers/providers.tsx b/apps/web/features/providers/providers.tsx index 0eb74855..6592327f 100644 --- a/apps/web/features/providers/providers.tsx +++ b/apps/web/features/providers/providers.tsx @@ -1,5 +1,9 @@ -import { useState } from "react"; -import { useMutation, useQuery } from "@tanstack/react-query"; +import { type ReactNode, useState } from "react"; +import { + type UseQueryResult, + useMutation, + useQuery, +} from "@tanstack/react-query"; import { IconCheck, IconCopy, @@ -7,7 +11,6 @@ import { IconLogin, IconTrash, } from "@tabler/icons-react"; -import { MarkupLogo } from "@/components/brand-logo"; import { EditorSheet } from "@/components/form-fields"; import { SecretSourceField, @@ -25,9 +28,9 @@ import { } from "@/components/ui/empty"; import { FieldError } from "@/components/ui/field"; import { Skeleton } from "@/components/ui/skeleton"; +import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { RowMenu, - RowTile, Section, SettingRow, StatusDot, @@ -44,9 +47,11 @@ import { providersQuery, providerPath, invalidateProviders, + usageQuery, } from "./api"; import { SignInDialog } from "./provider-sign-in"; -import { providerLogo } from "./provider-logos"; +import { ProviderTile } from "./provider-tile"; +import { UsageView } from "./usage"; const EXTERNAL_STATUS = { signed_in: "Signed in", @@ -116,20 +121,6 @@ function providerKeyAvailable(provider: Provider, editing: boolean) { ); } -function ProviderTile({ provider }: { provider: Provider }) { - const logo = providerLogo(provider.provider); - - return logo ? ( - - - - ) : ( - - {provider.name.slice(0, 1).toUpperCase()} - - ); -} - function ProviderActions({ provider, credential, @@ -375,24 +366,79 @@ function ProviderSection({ ); } +type ProvidersView = "setup" | "usage"; + +function ProvidersTabs({ + view, + onView, +}: { + view: ProvidersView; + onView: (view: ProvidersView) => void; +}) { + return ( + onView(value === "usage" ? "usage" : "setup")} + > + + Setup + Usage + + + ); +} + export function ProvidersSettings() { const providers = useQuery(providersQuery); + const [view, setView] = useState("setup"); + const usage = useQuery({ ...usageQuery, enabled: view === "usage" }); + const refreshed = view === "usage" ? usage : providers; + + return ( + void refreshed.refetch()} + refreshing={refreshed.isFetching} + > + {view === "usage" ? ( + <> + + + + ) : ( + } + /> + )} + + ); +} + +function ProvidersSetup({ + providers, + tabs, +}: { + providers: UseQueryResult; + tabs: ReactNode; +}) { const [search, setSearch] = useState(""); const [signingIn, setSigningIn] = useState(null); const shown = matching(providers.data ?? [], search.trim().toLowerCase()); const ready = shown.filter((provider) => provider.configured); return ( - void providers.refetch()} - refreshing={providers.isFetching} - > - + <> +
    + {tabs} +
    + +
    +
    {providers.isPending && } {providers.isError && {providers.error.message}} {providers.isSuccess && shown.length === 0 && ( @@ -421,6 +467,6 @@ export function ProvidersSettings() { onClose={() => setSigningIn(null)} /> )} -
    + ); } diff --git a/apps/web/features/providers/usage.dom.test.tsx b/apps/web/features/providers/usage.dom.test.tsx new file mode 100644 index 00000000..5a1bd852 --- /dev/null +++ b/apps/web/features/providers/usage.dom.test.tsx @@ -0,0 +1,133 @@ +import { expect, test } from "bun:test"; +import { + QueryClient, + QueryClientProvider, + useQuery, +} from "@tanstack/react-query"; +import { Window } from "happy-dom"; +import { act } from "react"; +import { type Provider, type Usage, usageQuery } from "./api"; +import { UsageView } from "./usage"; + +const anthropic: Provider = { + provider: "anthropic", + name: "Anthropic", + configured: true, + authMethods: [], + credentialType: "api_key", + apiKey: { configured: true, passwordManager: null, reference: null }, + activeLoginId: null, + externalAuth: null, +}; + +function Harness({ providers }: { providers: Provider[] }) { + return ; +} + +async function render(usage: Usage, providers: Provider[] = [anthropic]) { + 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, so the view makes no request. + const client = new QueryClient({ + defaultOptions: { queries: { retry: false, staleTime: Infinity } }, + }); + + client.setQueryData(usageQuery.queryKey, 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); + }, + }; +} + +// Logos carry an SVG title, but are aria-hidden: leave them out as a screen reader would. +const heading = (section: Element) => { + const h2 = section.querySelector("h2"); + + const hidden = [...(h2?.querySelectorAll("[aria-hidden]") ?? [])] + .map((element) => element.textContent) + .join(""); + + return h2?.textContent?.replace(hidden, ""); +}; + +const sections = (container: HTMLElement) => + [...container.querySelectorAll("section")].map((section) => ({ + title: heading(section), + text: section.textContent, + })); + +test("groups models by provider, with a total for each and for the account", async () => { + const { container, cleanup } = await render({ + models: [ + { provider: "openai", model: "gpt-6", tokens: 12_345, cost: 0.25 }, + { provider: "anthropic", model: "sonnet", tokens: 900, cost: 0.5 }, + { provider: "openai", model: "gpt-6-mini", tokens: 100, cost: 0.01 }, + ], + tools: [{ name: "vision", tokens: 50, cost: 0.02 }], + }); + + try { + const found = sections(container); + + expect(found.map((section) => section.title)).toEqual([ + "openai", + "Anthropic", + "Tools", + ]); + expect(found[0]?.text).toContain("12K tokens 路 $0.2600"); + expect(found[0]?.text).toContain("gpt-6-mini100 tokens 路 $0.0100"); + expect(container.textContent).toContain("$0.7800"); + } finally { + await cleanup(); + } +}); + +test("shows tokens without a cost for a subscription provider", async () => { + const { container, cleanup } = await render({ + models: [{ provider: "claude-code", model: "opus", tokens: 50, cost: 0 }], + tools: [], + }); + + try { + expect(container.textContent).not.toContain("$"); + expect(container.textContent).toContain("opus50 tokens"); + } finally { + await cleanup(); + } +}); + +test("says so before any bot has called a model", async () => { + const { container, cleanup } = await render({ models: [], tools: [] }); + + try { + expect(container.textContent).toContain("No usage yet"); + } finally { + await cleanup(); + } +}); diff --git a/apps/web/features/providers/usage.tsx b/apps/web/features/providers/usage.tsx new file mode 100644 index 00000000..9a3c6409 --- /dev/null +++ b/apps/web/features/providers/usage.tsx @@ -0,0 +1,148 @@ +import type { UseQueryResult } from "@tanstack/react-query"; +import { + Empty, + EmptyDescription, + EmptyHeader, + EmptyTitle, +} from "@/components/ui/empty"; +import { FieldError } from "@/components/ui/field"; +import { Skeleton } from "@/components/ui/skeleton"; +import { Section, SettingRow } from "@/components/page"; +import { formatCost, formatTokens } from "@/features/chat/usage"; +import type { Provider, Usage } from "./api"; +import { ProviderTile } from "./provider-tile"; + +type Totals = { tokens: number; cost: number }; + +const amount = ({ tokens, cost }: Totals) => + [formatTokens(tokens), formatCost(cost)].filter(Boolean).join(" 路 "); + +const total = (rows: readonly Totals[]) => + rows.reduce( + (sum, row) => ({ + tokens: sum.tokens + row.tokens, + cost: sum.cost + row.cost, + }), + { tokens: 0, cost: 0 }, + ); + +function Amount({ totals }: { totals: Totals }) { + return ( + + {amount(totals)} + + ); +} + +/** The usage's models by provider, in the order of each provider's first, and so largest, model. */ +function byProvider(models: Usage["models"]) { + const groups = new Map(); + + for (const row of models) + groups.set(row.provider, [...(groups.get(row.provider) ?? []), row]); + + return [...groups]; +} + +function ProviderUsage({ + id, + provider, + models, +}: { + id: string; + provider: Provider | undefined; + models: Usage["models"]; +}) { + return ( +
    } + action={} + > + {models.map((row) => ( + {row.model}} + > + + + ))} +
    + ); +} + +function UsageSections({ + usage, + providers, +}: { + usage: Usage; + providers: Provider[]; +}) { + if (!usage.models.length && !usage.tools.length) + return ( + + + No usage yet + + Usage shows here once a bot calls a model. + + + + ); + + const all = total([...usage.models, ...usage.tools]); + + return ( + <> +
    +

    + {formatCost(all.cost) ?? formatTokens(all.tokens)} +

    +

    + {formatCost(all.cost) && `${formatTokens(all.tokens)}. `} + Every bot's chat and jobs, since each started. Providers that bill by + subscription, such as Claude Code, report no cost. +

    +
    + {byProvider(usage.models).map(([id, models]) => ( + item.provider === id)} + models={models} + /> + ))} + {usage.tools.length > 0 && ( +
    } + > + {usage.tools.map((row) => ( + {row.name}} + > + + + ))} +
    + )} + + ); +} + +/** Tokens and cost of the account's bots, grouped by provider, then by model. */ +export function UsageView({ + usage, + providers, +}: { + usage: UseQueryResult; + providers: Provider[]; +}) { + if (usage.isPending) return ; + + if (usage.isError) return {usage.error.message}; + + return ; +} diff --git a/openapi/openapi.json b/openapi/openapi.json index bdec46eb..84c363b1 100644 --- a/openapi/openapi.json +++ b/openapi/openapi.json @@ -4424,6 +4424,66 @@ "message" ] }, + "Usage": { + "type": "object", + "properties": { + "models": { + "type": "array", + "items": { + "type": "object", + "properties": { + "provider": { + "type": "string" + }, + "model": { + "type": "string" + }, + "tokens": { + "type": "number" + }, + "cost": { + "type": "number", + "description": "US dollars. Zero for providers that bill by subscription, such as Claude Code." + } + }, + "required": [ + "provider", + "model", + "tokens", + "cost" + ] + } + }, + "tools": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "tokens": { + "type": "number" + }, + "cost": { + "type": "number", + "description": "US dollars. Zero for providers that bill by subscription, such as Claude Code." + } + }, + "required": [ + "name", + "tokens", + "cost" + ] + }, + "description": "Tools that call a model of their own, such as vision questions and intent checks." + } + }, + "required": [ + "models", + "tools" + ] + }, "ReasoningPreview": { "type": "object", "properties": { @@ -26363,6 +26423,112 @@ } } }, + "/v1/usage": { + "get": { + "operationId": "getUsage", + "description": "Tokens and cost of each model and tool across all of the account's bots: their chats, jobs, and other conversations, since each started. Most tokens first. A deleted bot's usage is gone with it.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Usage" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, "/v1/reasoning/preview": { "post": { "operationId": "previewReasoning",