From e60f75156b2dbac1c4b8ce699f7948a2aa80ae61 Mon Sep 17 00:00:00 2001 From: LHaghfoss Date: Wed, 25 Nov 2026 23:05:56 +0100 Subject: [PATCH] feat(desktop): show a thread's total cost, time and tokens in its panel The Activity section opens with the thread's cost (reported, else its turns at list price), the time its turns ran (the running one counting up) and its tokens. The context meter shows its percentage and warms at 70% and 90%. --- apps/desktop/src/ui/ThreadDetails.tsx | 145 +++++++++++++++-------- apps/desktop/src/ui/storedTurns.ts | 8 +- apps/desktop/src/ui/threadTotals.test.ts | 41 +++++++ apps/desktop/src/ui/threadTotals.ts | 60 ++++++++++ 4 files changed, 204 insertions(+), 50 deletions(-) create mode 100644 apps/desktop/src/ui/threadTotals.test.ts create mode 100644 apps/desktop/src/ui/threadTotals.ts diff --git a/apps/desktop/src/ui/ThreadDetails.tsx b/apps/desktop/src/ui/ThreadDetails.tsx index 8cd230619..348383377 100644 --- a/apps/desktop/src/ui/ThreadDetails.tsx +++ b/apps/desktop/src/ui/ThreadDetails.tsx @@ -5,13 +5,14 @@ import { type ReactNode, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import { pullErrorTitle } from "../acp/rustcode"; -import { modelName, projectName } from "../acp/types"; +import { modelName, projectName, type SessionUsage } from "../acp/types"; import { STATUS_LABEL } from "../acp/v2"; import { type GitChanges, gitChangeSummary, openExternal, openPath } from "../lib/native"; import { appPlatform, fileManagerName } from "../lib/platform"; +import { useNow } from "../lib/useNow"; import { contextPercent } from "../state/details"; import { turnItemsByEnd } from "../state/fold"; -import { estimateUsd, formatCost } from "../state/pricing"; +import { formatCost } from "../state/pricing"; import { PULL_LIMIT, usePullList } from "../state/pullQueries"; import { engineBusy } from "../state/runState"; import { showPanel, useApp, worktreeOf } from "../state/store"; @@ -42,6 +43,7 @@ import { StatusIcon } from "./Status"; import { useStoredTurns, withStoredTurns } from "./storedTurns"; import { type LogTurn, TurnEvents } from "./TurnEvents"; import { TurnTrace } from "./TurnTrace"; +import { contextTone, threadTotals, turnCost } from "./threadTotals"; /** * The thread's working tree against HEAD, read once its turn ends, so a finished turn counts. Only @@ -97,6 +99,22 @@ export function ThreadDetails() { const counts = useMemo(() => threadCounts(items ?? []), [items]); const running = isRunning(thread) || isLoading(thread) || !!thread?.enginePhase || engineBusy(status); const changes = useChanges(host ? undefined : thread?.cwd, isRunning(thread)); + const entries = useMemo(() => turnEntries(items ?? [], running), [items, running]); + const stored = useStoredTurns(id ?? undefined, entries.length); + const turns = useMemo(() => withStoredTurns(entries, stored), [entries, stored]); + const liveStart = thread?.turn?.startedAt ?? thread?.enginePhase?.startedAt; + const now = useNow(liveStart !== undefined); + const totals = useMemo( + () => + threadTotals( + turns, + thread?.usage, + harnessId, + summary?.model, + liveStart === undefined ? 0 : Math.max(0, now - liveStart), + ), + [turns, thread?.usage, harnessId, summary?.model, liveStart, now], + ); // Which sections are folded away: the reader's habit, kept for every thread. const [folded, setFolded] = useState(readFolded); // A row elsewhere (`+2 nested` in the strip's popover) opens a section: the fold is read again. @@ -132,10 +150,6 @@ export function ThreadDetails() { ["Messages", String(counts.messages)], ["Tool calls", String(counts.tools)], ]; - if (usage?.cost !== undefined && (!usage.currency || usage.currency === "USD")) - activity.push(["Cost", formatCost(usage.cost)]); - if (usage?.inputTokens !== undefined) activity.push(["Tokens in", formatTokens(usage.inputTokens)]); - if (usage?.outputTokens !== undefined) activity.push(["Tokens out", formatTokens(usage.outputTokens)]); if (counts.startedAt) activity.push(["Started", relativeAge(counts.startedAt)]); if (summary?.updatedAt) activity.push(["Last active", relativeAge(summary.updatedAt)]); @@ -221,6 +235,29 @@ export function ThreadDetails() { )}
+
+ + + +
{activity.map(([label, value]) => (
@@ -229,28 +266,11 @@ export function ThreadDetails() {
))}
- {usage && used !== undefined && ( -
- Context -
-
-
- - {formatTokens(usage.used)} / {formatTokens(usage.size)} - -
- )} + {usage && used !== undefined && }
void; }) { - const entries = useMemo(() => turnEntries(items, running), [items, running]); - const stored = useStoredTurns(threadKey, entries.length); - const turns = useMemo(() => withStoredTurns(entries, stored).reverse(), [entries, stored]); + const turns = useMemo(() => [...oldestFirst].reverse(), [oldestFirst]); const byEnd = useMemo(() => turnItemsByEnd(items, undefined, running), [items, running]); const ends = useMemo(() => { const map = new Map>(); @@ -501,6 +507,51 @@ function TurnScroll({ children }: { children: ReactNode }) { ); } +/** One of the Activity section's headline numbers: a small label over a large value. */ +function Total({ label, value, tip }: { label: string; value: string; tip: string }) { + return ( + +
+
{label}
+
{value}
+
+
+ ); +} + +const TONE_BAR = { accent: "bg-accent", warning: "bg-warning", danger: "bg-danger" } as const; +const TONE_TEXT = { accent: "text-fg", warning: "text-warning", danger: "text-danger" } as const; + +/** How full the context window is: the percentage up front, a bar that warms as it fills. */ +function ContextMeter({ used, usage }: { used: number; usage: SessionUsage }) { + const tone = contextTone(used); + return ( +
+
+ Context + {used}% + + + {formatTokens(usage.used)} / {formatTokens(usage.size)} + +
+
+
+
+
+ ); +} + /** A section's way to its full view: the diff, the pull list. */ function OpenButton({ label, onClick }: { label: string; onClick: () => void }) { return ( diff --git a/apps/desktop/src/ui/storedTurns.ts b/apps/desktop/src/ui/storedTurns.ts index d05d6675e..c66c2a234 100644 --- a/apps/desktop/src/ui/storedTurns.ts +++ b/apps/desktop/src/ui/storedTurns.ts @@ -19,6 +19,8 @@ const START_SLACK_MS = 5_000; const STORED_TURN_ROWS = 1_000; +const NO_STORED_TURNS: readonly StoredTurn[] = []; + /** The thread's recorded turns, oldest first. */ export function storedTurnsSql(threadId: string): string { const id = threadId.replaceAll("'", "''"); @@ -79,7 +81,7 @@ export function withStoredTurns(entries: readonly TurnEntry[], stored: readonly * cannot answer leaves the list empty: the rows then show what the transcript knows. */ export function useStoredTurns(threadKey: string | undefined, settled: number): readonly StoredTurn[] { - const [stored, setStored] = useState([]); + const [stored, setStored] = useState<{ key: string; rows: readonly StoredTurn[] } | null>(null); useEffect(() => { if (!threadKey || settled === 0) return; const { host, id } = splitThreadKey(threadKey); @@ -89,12 +91,12 @@ export function useStoredTurns(threadKey: string | undefined, settled: number): conn .request(Method.dataQuery, { sql: storedTurnsSql(id), limit: STORED_TURN_ROWS }, 10_000) .then((answer) => { - if (live) setStored(parseStoredTurns(answer)); + if (live) setStored({ key: threadKey, rows: parseStoredTurns(answer) }); }) .catch(() => {}); return () => { live = false; }; }, [threadKey, settled]); - return stored; + return stored && stored.key === threadKey ? stored.rows : NO_STORED_TURNS; } diff --git a/apps/desktop/src/ui/threadTotals.test.ts b/apps/desktop/src/ui/threadTotals.test.ts new file mode 100644 index 000000000..cc8219ab4 --- /dev/null +++ b/apps/desktop/src/ui/threadTotals.test.ts @@ -0,0 +1,41 @@ +import { describe, expect, test } from "bun:test"; +import type { TurnEntry } from "./overview"; +import { contextTone, threadTotals } from "./threadTotals"; + +const turn = (over: Partial): TurnEntry => ({ + id: "t", + prompt: "p", + outcome: "completed", + ...over, +}); + +describe("threadTotals", () => { + test("takes the thread's reported dollars over its turns", () => { + const totals = threadTotals( + [turn({ cost: 1, elapsedMs: 1_000 })], + { used: 1, size: 2, estimated: false, cost: 3 }, + undefined, + undefined, + ); + expect(totals).toMatchObject({ usd: 3, estimated: false, workedMs: 1_000 }); + }); + + test("adds the turns' costs and the running turn's time when the thread reported none", () => { + const totals = threadTotals( + [turn({ cost: 0.5, elapsedMs: 2_000, tokens: 10 }), turn({ cost: 0.25, elapsedMs: 3_000, tokens: 5 })], + undefined, + undefined, + undefined, + 4_000, + ); + expect(totals).toEqual({ usd: 0.75, estimated: false, workedMs: 9_000, tokens: 15 }); + }); + + test("knows no cost when no turn has one", () => { + expect(threadTotals([turn({})], undefined, undefined, undefined).usd).toBeUndefined(); + }); + + test("warms the context meter as it fills", () => { + expect([contextTone(10), contextTone(75), contextTone(95)]).toEqual(["accent", "warning", "danger"]); + }); +}); diff --git a/apps/desktop/src/ui/threadTotals.ts b/apps/desktop/src/ui/threadTotals.ts new file mode 100644 index 000000000..1bb3e9e6a --- /dev/null +++ b/apps/desktop/src/ui/threadTotals.ts @@ -0,0 +1,60 @@ +import type { SessionUsage } from "../acp/types"; +import { estimateUsd } from "../state/pricing"; +import { logTotals, type TurnEntry } from "./overview"; + +/** The thread's headline numbers in the side panel: what it cost, how long it worked, its tokens. */ +export interface ThreadTotals { + usd?: number; + /** Part of `usd` is the turns' tokens at list price, not what the harness reported. */ + estimated: boolean; + workedMs: number; + tokens?: number; +} + +/** A turn's cost: what the harness reported, else its tokens at list price. */ +export function turnCost( + turn: TurnEntry, + harness: string | undefined, + model: string | undefined, +): { usd: number; estimated: boolean } | undefined { + if (turn.cost !== undefined) return { usd: turn.cost, estimated: false }; + const counts = turn.counts; + if (!harness || !counts) return undefined; + const usd = estimateUsd(harness, model, { + input: counts.inputTokens, + output: counts.outputTokens, + cached: counts.cachedTokens, + }); + return usd === undefined ? undefined : { usd, estimated: true }; +} + +/** + * The thread's own reported cost when it has one in dollars, else the sum of its turns' costs. + * `liveMs` is how long the turn still running has gone so far, so the clock moves while it works. + */ +export function threadTotals( + turns: readonly TurnEntry[], + usage: SessionUsage | undefined, + harness: string | undefined, + model: string | undefined, + liveMs = 0, +): ThreadTotals { + const { tokens, agentMs } = logTotals(turns, usage); + const workedMs = agentMs + liveMs; + if (usage?.cost !== undefined && (!usage.currency || usage.currency === "USD")) + return { usd: usage.cost, estimated: false, workedMs, tokens }; + let usd: number | undefined; + let estimated = false; + for (const turn of turns) { + const cost = turnCost(turn, harness, model); + if (!cost) continue; + usd = (usd ?? 0) + cost.usd; + estimated ||= cost.estimated; + } + return { usd, estimated, workedMs, tokens }; +} + +/** How full the context window is, as the meter's colour: calm, then a warning, then danger. */ +export function contextTone(percent: number): "accent" | "warning" | "danger" { + return percent >= 90 ? "danger" : percent >= 70 ? "warning" : "accent"; +}