Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
- 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:<id>` or `group:<id>` 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.
Expand Down
9 changes: 9 additions & 0 deletions apps/docs/content/concepts/chats.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 8 additions & 9 deletions apps/server/src/contract/tool-details.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down
95 changes: 95 additions & 0 deletions apps/web/features/bot-chat/chat-usage.dom.test.tsx
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();
}
});
62 changes: 62 additions & 0 deletions apps/web/features/bot-chat/chat-usage.tsx
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 && (

Copy link
Copy Markdown

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 use value > 0, Boolean(value), or a ternary instead.

Fix → Use {items.length > 0 && <List />}, or a ternary like {items.length ? <List /> : null}.

Docs

<p className="text-xs text-muted-foreground">
Total {total}. Jobs have their own usage.
</p>
)}
</>
)}
</section>
);
}
2 changes: 2 additions & 0 deletions apps/web/features/bot-chat/details.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down Expand Up @@ -111,6 +112,7 @@ function DetailsBody({ bot, onClose }: { bot: Bot; onClose: () => void }) {
<AutomationList schedules={schedules} automations={automations} />
</section>
<RecentFiles botId={bot.id} onNavigate={onClose} />
<ChatUsage botId={bot.id} />
</div>
);
}
Expand Down
50 changes: 50 additions & 0 deletions apps/web/features/chat/usage.test.ts
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");
});
45 changes: 45 additions & 0 deletions apps/web/features/chat/usage.ts
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),
);
}
21 changes: 0 additions & 21 deletions apps/web/features/jobs/jobs.test.ts

This file was deleted.

19 changes: 6 additions & 13 deletions apps/web/features/jobs/jobs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 (
<>
Expand Down
Loading