Skip to content

: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.

feat(desktop): show per-task usage costs (#81009)

Adam Bowker10df2f65d0e4
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.ts
index 6ecd81e659fc..ab84b3e768e4 100644
--- a/products/desktop/packages/api-client/src/posthog-client.ts
+++ b/products/desktop/packages/api-client/src/posthog-client.ts
@@ -228,6 +228,12 @@ export interface TaskRunSessionLogsPage {
matchingCount: number | null;
}
+export interface TaskUsage {
+ token_cost_usd: number;
+ compute_cost_usd: number;
+ total_cost_usd: number;
+}
+
export interface TaskListOptions {
repository?: string;
createdBy?: number;
@@ -2497,6 +2503,20 @@ export class PostHogAPIClient {
return normalizeTaskResponse(data, { teamId });
}
+ async getTaskUsage(taskId: string): Promise<TaskUsage> {
+ const teamId = await this.getTeamId();
+ const urlPath = `/api/projects/${teamId}/tasks/${taskId}/usage/`;
+ const response = await this.api.fetcher.fetch({
+ method: "get",
+ url: new URL(`${this.api.baseUrl}${urlPath}`),
+ path: urlPath,
+ });
+ if (!response.ok) {
+ throw new Error(`Failed to fetch task usage: ${response.statusText}`);
+ }
+ return (await response.json()) as TaskUsage;
+ }
+
async getPinnedTaskIds(): Promise<string[]> {
const teamId = await this.getTeamId();
const urlPath = `/api/projects/${teamId}/tasks/pinned/`;
diff --git a/products/desktop/packages/shared/src/flags.ts b/products/desktop/packages/shared/src/flags.ts
index 47a43833537a..efa9d90ae88e 100644
--- a/products/desktop/packages/shared/src/flags.ts
+++ b/products/desktop/packages/shared/src/flags.ts
@@ -38,6 +38,11 @@ export const LOCAL_MCP_IMPORT_FLAG = "posthog-code-local-mcp-import";
export const MCP_GATEWAY_FLAG = "mcp-gateway";
/** Per-task estimated cost readout in the context usage indicator. */
export const TASK_COST_FLAG = "posthog-code-task-cost";
+/**
+ * Shows the task cost as text beside the context ring rather than only inside
+ * the popover. Requires TASK_COST_FLAG, which is what fetches the figure.
+ */
+export const TASK_COST_VISIBLE_FLAG = "posthog-code-task-cost-visible";
/**
* Remote in-app announcements. The flag's JSON payload carries the
* announcements (schema: `announcements.ts`); rollout % arms the system.
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ContextBreakdownPopover.test.tsx b/products/desktop/packages/ui/src/features/sessions/components/ContextBreakdownPopover.test.tsx
index cf30e422f21b..345b67df3f12 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/ContextBreakdownPopover.test.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/ContextBreakdownPopover.test.tsx
@@ -88,6 +88,27 @@ describe("ContextBreakdownPopover", () => {
expect(screen.queryByText("Rules")).not.toBeInTheDocument();
});
+ it("renders the authoritative task cost breakdown", () => {
+ render(
+ <Theme>
+ <ContextBreakdownPopover
+ usage={usageWith(null)}
+ taskUsage={{
+ token_cost_usd: 12.34,
+ compute_cost_usd: 0.56,
+ total_cost_usd: 12.9,
+ }}
+ />
+ </Theme>,
+ );
+ expect(screen.getByText("Estimated cost")).toBeInTheDocument();
+ expect(screen.getByText("Tokens")).toBeInTheDocument();
+ expect(screen.getByText("Cloud compute")).toBeInTheDocument();
+ expect(screen.getByText("$12.90")).toBeInTheDocument();
+ expect(screen.getByText("$12.34")).toBeInTheDocument();
+ expect(screen.getByText("$0.56")).toBeInTheDocument();
+ });
+
it("scales segments to the context window, not the used tokens", () => {
const { container } = render(
<Theme>
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ContextBreakdownPopover.tsx b/products/desktop/packages/ui/src/features/sessions/components/ContextBreakdownPopover.tsx
index adb73299c6c6..c17256bdf19f 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/ContextBreakdownPopover.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/ContextBreakdownPopover.tsx
@@ -1,3 +1,4 @@
+import type { TaskUsage } from "@posthog/api-client/posthog-client";
import {
CONTEXT_CATEGORIES,
formatCostUsd,
@@ -8,14 +9,14 @@ import type { ContextUsage } from "@posthog/ui/features/sessions/hooks/useContex
interface ContextBreakdownPopoverProps {
usage: ContextUsage;
- showCost?: boolean;
+ taskUsage?: TaskUsage;
}
export function ContextBreakdownPopover({
usage,
- showCost = false,
+ taskUsage,
}: ContextBreakdownPopoverProps) {
- const { used, size, percentage, cost, breakdown } = usage;
+ const { used, size, percentage, breakdown } = usage;
const fillColor = getOverallUsageColor(percentage);
// The context window can be unknown (size 0) — show just the token count
// rather than a misleading "~X / 0 tokens · 0% full".
@@ -72,18 +73,55 @@ export function ContextBreakdownPopover({
</span>
)}
- {showCost && cost && (
- <div className="flex items-center justify-between border-border border-t pt-2 text-[13px]">
- <span className="text-muted-foreground">Estimated cost</span>
- <span className="font-medium text-foreground tabular-nums">
- {formatCostUsd(cost.amount)}
- </span>
+ {taskUsage && (
+ <div className="border-border border-t pt-2.5">
+ <div className="overflow-hidden rounded-md border border-border/70 bg-muted/20">
+ <div className="flex items-center justify-between gap-6 px-2.5 py-1.5">
+ <span className="font-medium text-[11px] text-muted-foreground">
+ Estimated cost
+ </span>
+ <span className="font-semibold text-[15px] text-foreground tabular-nums leading-none">
+ {formatCostUsd(taskUsage.total_cost_usd)}
+ </span>
+ </div>
+ <div className="grid grid-cols-2 border-border/70 border-t bg-background/40">
+ <CostDetail label="Tokens" value={taskUsage.token_cost_usd} />
+ <CostDetail
+ label="Cloud compute"
+ value={taskUsage.compute_cost_usd}
+ divided
+ />
+ </div>
+ </div>
</div>
)}
</div>
);
}
+function CostDetail({
+ label,
+ value,
+ divided = false,
+}: {
+ label: string;
+ value: number;
+ divided?: boolean;
+}) {
+ return (
+ <div
+ className={`flex min-w-0 flex-col px-2.5 py-1.5 ${divided ? "border-border/70 border-l" : ""}`}
+ >
+ <span className="truncate text-[10px] text-muted-foreground">
+ {label}
+ </span>
+ <span className="font-medium text-[12px] text-foreground tabular-nums">
+ {formatCostUsd(value)}
+ </span>
+ </div>
+ );
+}
+
function SegmentedBar({
breakdown,
size,
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.tsx
index cf048a7590ad..8bec20ff19fb 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
@@ -1,16 +1,42 @@
+import { TASK_COST_VISIBLE_FLAG } from "@posthog/shared";
import type { ContextUsage } from "@posthog/ui/features/sessions/hooks/useContextUsage";
import { Theme } from "@radix-ui/themes";
-import { render } from "@testing-library/react";
+import { render, screen } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { ContextUsageIndicator } from "./ContextUsageIndicator";
-const flagState = vi.hoisted(() => ({ enabled: false }));
+const flagState = vi.hoisted(() => ({ cost: false, costVisible: false }));
+const taskUsageState = vi.hoisted(() => ({
+ data: undefined as
+ | {
+ token_cost_usd: number;
+ compute_cost_usd: number;
+ total_cost_usd: number;
+ }
+ | undefined,
+}));
vi.mock("@posthog/ui/features/feature-flags/useFeatureFlag", () => ({
- useFeatureFlag: () => flagState.enabled,
+ useFeatureFlag: (key: string) =>
+ key === TASK_COST_VISIBLE_FLAG ? flagState.costVisible : flagState.cost,
+}));
+vi.mock("@posthog/ui/features/sessions/hooks/useTaskUsage", () => ({
+ useTaskUsage: () => taskUsageState,
}));
+function enableCost(costVisible = false) {
+ flagState.cost = true;
+ flagState.costVisible = costVisible;
+ taskUsageState.data = {
+ token_cost_usd: 0.4,
+ compute_cost_usd: 0.02,
+ total_cost_usd: 0.42,
+ };
+}
+
beforeEach(() => {
- flagState.enabled = false;
+ flagState.cost = false;
+ flagState.costVisible = false;
+ taskUsageState.data = undefined;
});
function usage(overrides?: Partial<ContextUsage>): ContextUsage {
@@ -36,33 +62,54 @@ describe("ContextUsageIndicator", () => {
// 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 the flag is supposed to surface.
+ // never claim, and the cost while it has no text of its own.
it.each([
- ["a known window", {}, false, "Context usage: 25%"],
+ ["a known window", {}, false, false, "Context usage: 25%"],
[
"an unknown window (size 0)",
{ used: 50_000, size: 0, percentage: 0 },
false,
+ false,
"Context usage: 50K tokens",
],
- [
- "cost enabled",
- { cost: { amount: 0.42, currency: "USD" } },
- true,
- "Context usage: 25% · $0.42",
- ],
- ])("names itself for %s", (_case, overrides, costEnabled, expected) => {
- flagState.enabled = costEnabled;
- const { container } = render(
+ ["cost enabled", {}, true, false, "Context usage: 25% · $0.42"],
+ ["cost shown as text", {}, true, true, "Context usage: 25%"],
+ ])(
+ "names itself for %s",
+ (_case, overrides, costEnabled, costVisible, expected) => {
+ if (costEnabled) enableCost(costVisible);
+ const { container } = render(
+ <Theme>
+ <ContextUsageIndicator
+ usage={usage(overrides as Partial<ContextUsage>)}
+ taskId="task-1"
+ />
+ </Theme>,
+ );
+ expect(
+ container.querySelector("button")?.getAttribute("aria-label"),
+ ).toBe(expected);
+ },
+ );
+
+ it("shows the cost beside the ring once the visible flag is on", () => {
+ enableCost(true);
+ render(
<Theme>
- <ContextUsageIndicator
- usage={usage(overrides as Partial<ContextUsage>)}
- />
+ <ContextUsageIndicator usage={usage()} taskId="task-1" />
</Theme>,
);
- expect(container.querySelector("button")?.getAttribute("aria-label")).toBe(
- expected,
+ expect(screen.getByText("$0.42")).toBeInTheDocument();
+ });
+
+ it("keeps the cost in the popover while the visible flag is off", () => {
+ enableCost();
+ render(
+ <Theme>
+ <ContextUsageIndicator usage={usage()} taskId="task-1" />
+ </Theme>,
);
+ expect(screen.queryByText("$0.42")).not.toBeInTheDocument();
});
it("renders a finite stroke offset at 0% (no NaN/Infinity)", () => {
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ContextUsageIndicator.tsx b/products/desktop/packages/ui/src/features/sessions/components/ContextUsageIndicator.tsx
index 46f002f3dde0..1e3f997880ba 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/ContextUsageIndicator.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/ContextUsageIndicator.tsx
@@ -3,8 +3,9 @@ import {
Popover,
PopoverContent,
PopoverTrigger,
+ Text,
} from "@posthog/quill";
-import { TASK_COST_FLAG } from "@posthog/shared";
+import { TASK_COST_FLAG, TASK_COST_VISIBLE_FLAG } from "@posthog/shared";
import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";
import {
formatCostUsd,
@@ -12,6 +13,7 @@ import {
getOverallUsageColor,
} from "@posthog/ui/features/sessions/contextColors";
import type { ContextUsage } from "@posthog/ui/features/sessions/hooks/useContextUsage";
+import { useTaskUsage } from "@posthog/ui/features/sessions/hooks/useTaskUsage";
import { ContextBreakdownPopover } from "./ContextBreakdownPopover";
const CIRCLE_SIZE = 20;
@@ -21,77 +23,98 @@ const CIRCUMFERENCE = 2 * Math.PI * RADIUS;
interface ContextUsageIndicatorProps {
usage: ContextUsage | null;
+ taskId?: string;
+ focused?: boolean;
}
-export function ContextUsageIndicator({ usage }: ContextUsageIndicatorProps) {
+export function ContextUsageIndicator({
+ usage,
+ taskId,
+ focused = true,
+}: ContextUsageIndicatorProps) {
const costEnabled = useFeatureFlag(TASK_COST_FLAG) || import.meta.env.DEV;
+ const costVisible = useFeatureFlag(TASK_COST_VISIBLE_FLAG);
+ const { data: taskUsage } = useTaskUsage(taskId, costEnabled && focused);
if (!usage) return null;
- const { used, size, percentage, cost } = usage;
+ const { used, size, percentage } = usage;
// 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 = costEnabled && cost !== null;
+ const showCost = costEnabled && 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.
+ const costSuffix =
+ showCost && !showCostText
+ ? ` · ${formatCostUsd(taskUsage.total_cost_usd)}`
+ : "";
return (
- <Popover>
- <PopoverTrigger
- render={
- <Button
- type="button"
- variant="default"
- size="icon-sm"
- aria-label={
- hasSize
- ? `Context usage: ${percentage}%` +
- (showCost ? ` · ${formatCostUsd(cost.amount)}` : "")
- : `Context usage: ${formatTokensCompact(used)} tokens` +
- (showCost ? ` · ${formatCostUsd(cost.amount)}` : "")
- }
- >
- {/* 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"
+ <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}`
+ }
>
- <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
- line and would spill out of it. */}
- <PopoverContent
- side="top"
- align="end"
- sideOffset={6}
- className="w-auto min-w-[280px] gap-3"
- >
- <ContextBreakdownPopover usage={usage} showCost={showCost} />
- </PopoverContent>
- </Popover>
+ {/* 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 own
+ line 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>
+ )}
+ </div>
);
}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx b/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx
index a11263ec2792..609b439c509e 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx
@@ -866,7 +866,11 @@ export function SessionView({
) : undefined
}
toolbarEndSlot={
- <ContextUsageIndicator usage={contextUsage} />
+ <ContextUsageIndicator
+ usage={contextUsage}
+ taskId={taskId}
+ focused={isActiveSession !== false}
+ />
}
onToggleMessagingMode={toggleMessagingMode}
onAttachmentsChange={handleAttachmentsChange}
diff --git a/products/desktop/packages/ui/src/features/sessions/hooks/useTaskUsage.ts b/products/desktop/packages/ui/src/features/sessions/hooks/useTaskUsage.ts
new file mode 100644
index 000000000000..15dbb023642e
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/hooks/useTaskUsage.ts
@@ -0,0 +1,24 @@
+import type { TaskUsage } from "@posthog/api-client/posthog-client";
+import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";
+import type { UseQueryResult } from "@tanstack/react-query";
+
+const TASK_USAGE_REFRESH_MS = 60_000;
+
+export function useTaskUsage(
+ taskId: string | undefined,
+ enabled: boolean,
+): UseQueryResult<TaskUsage> {
+ return useAuthenticatedQuery(
+ ["task-usage", taskId],
+ (client): Promise<TaskUsage> => {
+ if (!taskId) throw new Error("Task usage is unavailable");
+ return client.getTaskUsage(taskId);
+ },
+ {
+ enabled: enabled && taskId !== undefined,
+ staleTime: TASK_USAGE_REFRESH_MS,
+ refetchInterval: TASK_USAGE_REFRESH_MS,
+ refetchOnMount: "always",
+ },
+ );
+}