:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(desktop): keep run cost visible when the stream reports no usage (#94157)
Alessandro Pogliaghidef74a68ed4c
diff --git a/products/desktop/packages/agent/src/adapters/claude/claude-agent.clear.test.ts b/products/desktop/packages/agent/src/adapters/claude/claude-agent.clear.test.tsindex a82c54c40845..b94df955d36d 100644--- a/products/desktop/packages/agent/src/adapters/claude/claude-agent.clear.test.ts+++ b/products/desktop/packages/agent/src/adapters/claude/claude-agent.clear.test.ts@@ -153,6 +153,7 @@ function installFakeSession(notificationHistory: [] as unknown[],taskRunId: "run-1",lastContextWindowSize: 200_000,+ contextUsed: undefined as number | undefined,modelId: overrides.modelId ?? "claude-sonnet-4-6",taskState: new Map(),};@@ -211,6 +212,7 @@ describe("ClaudeAcpAgent /clear", () => {const { agent, client } = makeAgent();const { session, oldQuery, endSpy } = installFakeSession(agent, "s-1");session.taskState.set("task-1", { title: "old task" });+ session.contextUsed = 150_000;const result = await agent.prompt({sessionId: "s-1",@@ -276,6 +278,7 @@ describe("ClaudeAcpAgent /clear", () => {used: 0,size: 200_000,});+ expect(session.contextUsed).toBeUndefined();});it("re-roots /clear on a pinned live model without colliding with its own fallback model", async () => {diff --git a/products/desktop/packages/agent/src/adapters/claude/claude-agent.streamed-text.test.ts b/products/desktop/packages/agent/src/adapters/claude/claude-agent.streamed-text.test.tsindex 77cc5bb5d2a1..f3d46b581d81 100644--- a/products/desktop/packages/agent/src/adapters/claude/claude-agent.streamed-text.test.ts+++ b/products/desktop/packages/agent/src/adapters/claude/claude-agent.streamed-text.test.ts@@ -358,6 +358,80 @@ describe("ClaudeAcpAgent.prompt — streamed assistant text wiring", () => {expect(updates.every(({ size }) => size === 1_000_000)).toBe(true);});+ it.each([+ {+ source: "the SDK context usage",+ contextUsage: { totalTokens: 900 },+ expectedUpdates: [{ used: 900, size: 200_000 }],+ },+ {+ source: "nothing, so no usage reaches the client",+ contextUsage: {},+ expectedUpdates: [],+ },+ ])(+ "falls back to $source rather than the result's loop aggregate",+ async ({ contextUsage, expectedUpdates }) => {+ const { agent, client } = makeAgent();+ const sessionId = "s-zero-stream-usage";+ const { query, input } = installFakeSession(agent, sessionId);+ vi.mocked(query.getContextUsage).mockResolvedValue(+ contextUsage as Awaited<ReturnType<typeof query.getContextUsage>>,+ );++ const promptPromise = agent.prompt({+ sessionId,+ prompt: [{ type: "text", text: "hi" }],+ });+ await tick();++ await echoUserMessage(query, input);+ await send(query, messageStart(sessionId, "msg-zero"));+ await send(query, assistantMessage(sessionId, "msg-zero", "done"));+ await send(query, {+ ...resultSuccess(sessionId),+ usage: {+ input_tokens: 1200,+ output_tokens: 300,+ cache_read_input_tokens: 0,+ cache_creation_input_tokens: 0,+ },+ });+ await promptPromise;++ expect(usageUpdates(client.sessionUpdate.mock.calls)).toEqual(+ expectedUpdates,+ );+ },+ );++ it("settles the turn when the SDK context usage never answers", async () => {+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });+ try {+ const { agent, client } = makeAgent();+ const sessionId = "s-hung-context-usage";+ const { query, input } = installFakeSession(agent, sessionId);+ vi.mocked(query.getContextUsage).mockReturnValue(new Promise(() => {}));++ const promptPromise = agent.prompt({+ sessionId,+ prompt: [{ type: "text", text: "hi" }],+ });+ await tick();++ await echoUserMessage(query, input);+ await send(query, messageStart(sessionId, "msg-hung"));+ await send(query, assistantMessage(sessionId, "msg-hung", "done"));+ await send(query, resultSuccess(sessionId));+ await vi.advanceTimersByTimeAsync(5_000);+ await promptPromise;++ expect(usageUpdates(client.sessionUpdate.mock.calls)).toEqual([]);+ } finally {+ vi.useRealTimers();+ }+ });+it("keeps the original turn open until a pending steer is consumed", async () => {const { agent, client } = makeAgent();const sessionId = "s-steer-ordering";diff --git a/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts b/products/desktop/packages/agent/src/adapters/claude/claude-agent.tsindex 44da07077f67..3f7ade76a2e9 100644--- a/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts+++ b/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts@@ -322,13 +322,40 @@ function shouldEmitRawMessage();}+interface SdkTokenUsage {+ input_tokens?: number | null;+ output_tokens?: number | null;+ cache_read_input_tokens?: number | null;+ cache_creation_input_tokens?: number | null;+}++function sumSdkUsage(usage: SdkTokenUsage): number {+ return (+ (usage.input_tokens ?? 0) ++ (usage.output_tokens ?? 0) ++ (usage.cache_read_input_tokens ?? 0) ++ (usage.cache_creation_input_tokens ?? 0)+ );+}++const CONTEXT_USAGE_TIMEOUT_MS = 5_000;+async function fetchContextUsedTokens(sdkQuery: Query,logger: Logger,): Promise<number | null> {try {- const usage = await sdkQuery.getContextUsage();- return usage.totalTokens;+ const usage = await withTimeout(+ sdkQuery.getContextUsage(),+ CONTEXT_USAGE_TIMEOUT_MS,+ );+ if (usage.result === "timeout") {+ logger.warn(+ `Timed out after ${CONTEXT_USAGE_TIMEOUT_MS}ms fetching context usage from SDK`,+ );+ return null;+ }+ return usage.value.totalTokens;} catch (error) {logger.error("Failed to fetch context usage from SDK:", error);return null;@@ -1261,6 +1288,18 @@ export class ClaudeAcpAgent extends BaseAcpAgent {}}+ if (!isTaskNotification && lastAssistantTotalUsage === null) {+ const usedTokens = await withAbort(+ fetchContextUsedTokens(query, this.logger),+ cancelController.signal,+ );+ const total =+ usedTokens.result === "success" ? (usedTokens.value ?? 0) : 0;+ if (total > 0) {+ recordContextUsage(total);+ }+ }+session.contextSize = windowSize();if (lastAssistantTotalUsage !== null) {session.contextUsed = lastAssistantTotalUsage;@@ -1440,11 +1479,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {};}- const nextTotal =- lastStreamUsage.input_tokens +- lastStreamUsage.output_tokens +- lastStreamUsage.cache_read_input_tokens +- lastStreamUsage.cache_creation_input_tokens;+ const nextTotal = sumSdkUsage(lastStreamUsage);if (recordContextUsage(nextTotal)) {await this.client.sessionUpdate({@@ -1549,11 +1584,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {cache_read_input_tokens: number | null;cache_creation_input_tokens: number | null;};- const nextTotal =- (usage.input_tokens ?? 0) +- (usage.output_tokens ?? 0) +- (usage.cache_read_input_tokens ?? 0) +- (usage.cache_creation_input_tokens ?? 0);+ const nextTotal = sumSdkUsage(usage);if (recordContextUsage(nextTotal)) {await this.client.sessionUpdate({@@ -1930,6 +1961,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {session.input = newInput;session.queryOptions = newOptions;session.abortController = newAbortController;+ session.contextUsed = undefined;const result = await withTimeout(newQuery.initializationResult(),diff --git a/products/desktop/packages/ui/src/features/sessions/components/ContextUsageIndicator.test.tsx b/products/desktop/packages/ui/src/features/sessions/components/ContextUsageIndicator.test.tsxindex b506847b70dc..08ea03450463 100644--- a/products/desktop/packages/ui/src/features/sessions/components/ContextUsageIndicator.test.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/ContextUsageIndicator.test.tsx@@ -55,6 +55,21 @@ describe("ContextUsageIndicator", () => {expect(container.querySelector("button")).toBeNull();});+ it("shows the cost on its own when usage is null", () => {+ enableCost(true);+ const { container } = render(+ <Theme>+ <ContextUsageIndicator+ usage={null}+ taskId="task-1"+ originProduct="user_created"+ />+ </Theme>,+ );+ expect(screen.getByText("$0.42")).toBeInTheDocument();+ expect(container.querySelector("button")).toBeNull();+ });+// The ring carries no text, so the accessible name is the only way the// numbers reach a reader — including the "/0 · 0%" an unknown window must// never claim, and the cost while it has no text of its own.diff --git a/products/desktop/packages/ui/src/features/sessions/components/ContextUsageIndicator.tsx b/products/desktop/packages/ui/src/features/sessions/components/ContextUsageIndicator.tsxindex 69d0f451c59b..911e0f8b34c7 100644--- a/products/desktop/packages/ui/src/features/sessions/components/ContextUsageIndicator.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/ContextUsageIndicator.tsx@@ -42,16 +42,26 @@ export function ContextUsageIndicator({);const taskUsage = costEnabled ? fetchedTaskUsage : undefined;- if (!usage) return null;+ const showCost = taskUsage !== undefined;+ const showCostText = showCost && costVisible;+ const costText = showCostText ? (+ <Text className="select-none font-medium text-[13px] text-gray-11 tabular-nums">+ {formatCostUsd(taskUsage.total_cost_usd)}+ </Text>+ ) : null;- const { used, size, percentage } = usage;+ if (!usage && !costText) return null;++ const { used, size, percentage } = usage ?? {+ used: 0,+ size: 0,+ percentage: 0,+ };// The context window can be unknown (size 0) — show just the token count// rather than a misleading "X/0 · 0%".const hasSize = size > 0;const strokeDashoffset = CIRCUMFERENCE - (percentage / 100) * CIRCUMFERENCE;const color = getOverallUsageColor(percentage);- const showCost = taskUsage !== undefined;- const showCostText = showCost && costVisible;// The ring carries no text, so the token figures reach a reader only through// the accessible name. Cost joins them only while it has no text of its own,// which would otherwise be announced twice.@@ -61,66 +71,64 @@ export function ContextUsageIndicator({: "";return (<div className="flex items-center gap-1">- <Popover>- <PopoverTrigger- render={- <Button- type="button"- variant="default"- size="icon-sm"- aria-label={- hasSize- ? `Context usage: ${percentage}%${costSuffix}`- : `Context usage: ${formatTokensCompact(used)} tokens${costSuffix}`- }- >- {/* viewBox, not width/height: quill sizes a button's svg down to- its icon slot, which would crop an unscaled drawing. */}- <svg- viewBox={`0 0 ${CIRCLE_SIZE} ${CIRCLE_SIZE}`}- className="-rotate-90 size-4 shrink-0"- role="img"- aria-hidden="true"+ {usage && (+ <Popover>+ <PopoverTrigger+ render={+ <Button+ type="button"+ variant="default"+ size="icon-sm"+ aria-label={+ hasSize+ ? `Context usage: ${percentage}%${costSuffix}`+ : `Context usage: ${formatTokensCompact(used)} tokens${costSuffix}`+ }>- <circle- cx={CIRCLE_SIZE / 2}- cy={CIRCLE_SIZE / 2}- r={RADIUS}- fill="none"- stroke="var(--border)"- strokeWidth={STROKE_WIDTH}- />- <circle- cx={CIRCLE_SIZE / 2}- cy={CIRCLE_SIZE / 2}- r={RADIUS}- fill="none"- stroke={color}- strokeWidth={STROKE_WIDTH}- strokeDasharray={CIRCUMFERENCE}- strokeDashoffset={strokeDashoffset}- strokeLinecap="round"- />- </svg>- </Button>- }- />- {/* quill's popup is a fixed 18rem; the token figures sit on their own+ {/* viewBox, not width/height: quill sizes a button's svg down to+ its icon slot, which would crop an unscaled drawing. */}+ <svg+ viewBox={`0 0 ${CIRCLE_SIZE} ${CIRCLE_SIZE}`}+ className="-rotate-90 size-4 shrink-0"+ role="img"+ aria-hidden="true"+ >+ <circle+ cx={CIRCLE_SIZE / 2}+ cy={CIRCLE_SIZE / 2}+ r={RADIUS}+ fill="none"+ stroke="var(--border)"+ strokeWidth={STROKE_WIDTH}+ />+ <circle+ cx={CIRCLE_SIZE / 2}+ cy={CIRCLE_SIZE / 2}+ r={RADIUS}+ fill="none"+ stroke={color}+ strokeWidth={STROKE_WIDTH}+ strokeDasharray={CIRCUMFERENCE}+ strokeDashoffset={strokeDashoffset}+ strokeLinecap="round"+ />+ </svg>+ </Button>+ }+ />+ {/* quill's popup is a fixed 18rem; the token figures sit on their ownline and would spill out of it. */}- <PopoverContent- side="top"- align="end"- sideOffset={6}- className="w-auto min-w-[280px] gap-3"- >- <ContextBreakdownPopover usage={usage} taskUsage={taskUsage} />- </PopoverContent>- </Popover>- {showCostText && (- <Text className="select-none font-medium text-[13px] text-gray-11 tabular-nums">- {formatCostUsd(taskUsage.total_cost_usd)}- </Text>+ <PopoverContent+ side="top"+ align="end"+ sideOffset={6}+ className="w-auto min-w-[280px] gap-3"+ >+ <ContextBreakdownPopover usage={usage} taskUsage={taskUsage} />+ </PopoverContent>+ </Popover>)}+ {costText}</div>);}