Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(issues): show per-run token usage on the execution log (MUL-5762) (#6440)
Jiayuan Zhangba129b196308
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.tsindex a3ef58c9e9..45bd67be93 100644--- a/packages/core/api/client.test.ts+++ b/packages/core/api/client.test.ts@@ -700,6 +700,87 @@ describe("ApiClient", () => {]);});+ it("parses per-run token usage on task runs", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify([+ {+ id: "task-1",+ status: "completed",+ usage: [+ {+ provider: "anthropic",+ model: "claude-opus-5",+ input_tokens: 96_000,+ output_tokens: 34_000,+ cache_read_tokens: 712_000,+ cache_write_tokens: 50_000,+ cost_usd_ticks: 19_990_000_000,+ },+ ],+ },+ // No usage at all — a run from before usage reporting.+ { id: "task-2", status: "completed" },+ ]),+ { status: 200, headers: { "Content-Type": "application/json" } },+ ),+ ),+ );++ const client = new ApiClient("https://api.example.test");+ const tasks = await client.listTasksByIssue("issue-1");++ expect(tasks[0]?.usage).toHaveLength(1);+ expect(tasks[0]?.usage?.[0]).toMatchObject({+ model: "claude-opus-5",+ input_tokens: 96_000,+ cache_read_tokens: 712_000,+ cost_usd_ticks: 19_990_000_000,+ });+ // Absent, not [] — "we have no figure" must stay distinguishable from+ // "the figure is zero" all the way to the UI.+ expect(tasks[1]?.usage).toBeUndefined();+ });++ it("keeps task runs when per-run usage is malformed", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify([+ // Usage is not an array at all.+ { id: "task-1", status: "completed", usage: "1.2M" },+ // Usage is an array, but an entry has a string where a count belongs.+ {+ id: "task-2",+ status: "completed",+ usage: [{ model: "claude-opus-5", input_tokens: "many" }],+ },+ {+ id: "task-3",+ status: "completed",+ usage: [{ model: "gpt-5.6-terra", input_tokens: 31_000 }],+ },+ ]),+ { status: 200, headers: { "Content-Type": "application/json" } },+ ),+ ),+ );++ const client = new ApiClient("https://api.example.test");+ const tasks = await client.listTasksByIssue("issue-1");++ // A bad usage payload costs that row its figure and nothing else — the+ // execution log still lists every run.+ expect(tasks).toHaveLength(3);+ expect(tasks[0]?.usage).toBeUndefined();+ expect(tasks[1]?.usage).toBeUndefined();+ expect(tasks[2]?.usage?.[0]?.input_tokens).toBe(31_000);+ expect(tasks[2]?.usage?.[0]?.output_tokens).toBe(0);+ });+it("uses the expected HTTP contract for autopilot endpoints", async () => {const fetchMock = vi.fn().mockImplementation(() => Promise.resolve(new Response(JSON.stringify({ autopilots: [], runs: [], total: 0 }), {diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 640a33e087..6d0b534cf7 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -1164,6 +1164,20 @@ const OptionalStringArraySchema = z.preprocess(z.array(z.string()).optional(),);+// One (provider, model) slice of a run's token usage. Token counts default to+// 0 rather than failing the row: a slice missing one counter is still worth+// pricing on the counters it does have, and the "we have no usage at all" case+// is carried by the field's absence, not by a zeroed entry.+const TaskUsageSchema = z.object({+ provider: z.string().optional(),+ model: z.string().default(""),+ input_tokens: z.number().default(0),+ output_tokens: z.number().default(0),+ cache_read_tokens: z.number().default(0),+ cache_write_tokens: z.number().default(0),+ cost_usd_ticks: z.number().optional(),+}).loose();+export const AgentTaskSchema = z.object({id: z.string(),agent_id: z.string().default(""),@@ -1194,6 +1208,12 @@ export const AgentTaskSchema = z.object({work_dir: z.string().optional(),relative_work_dir: z.string().optional(),attribution: TaskAttributionSchema.optional(),+ // Per-run token usage. Same independent-degradation rule as the coverage+ // arrays above: usage is additive display metadata, so one malformed entry+ // must cost the row its usage figure, not erase the whole execution log.+ // `.catch(undefined)` collapses a bad array to "no usage recorded", which+ // the UI already renders as an em dash.+ usage: z.array(TaskUsageSchema).optional().catch(undefined),}).loose();export const AgentTaskListSchema = z.array(AgentTaskSchema);diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.tsindex 4bc959543e..e5cdefcca1 100644--- a/packages/core/types/agent.ts+++ b/packages/core/types/agent.ts@@ -369,6 +369,41 @@ export interface AgentTask {* user-facing task surfaces; older backends omit it — render conditionally.*/attribution?: TaskAttribution;+ /**+ * This run's own token consumption, one entry per (provider, model) it used.+ * Present on the issue execution-log endpoint only; the daemon claim path+ * omits it.+ *+ * `undefined` (old backend, or a surface that doesn't hydrate it) and `[]`+ * (backend hydrated, this run has no recorded usage) both mean "no number to+ * show" and must render as an em dash, never as 0 — a run that predates usage+ * reporting was not free, we just don't know what it cost.+ */+ usage?: TaskUsage[];+}++/**+ * One (provider, model) slice of a single run's token usage.+ *+ * Field names deliberately match {@link RuntimeUsage} so the same+ * `estimateCost` / `estimateCostBreakdown` / `estimateCacheSavings` helpers in+ * `packages/views/runtimes/utils.ts` price a run and a runtime-day identically+ * — there is exactly one cost formula in the product.+ *+ * `cost_usd_ticks` is the provider's own price for this slice (1e-10 USD),+ * absent when it reported none; those tokens get estimated from the rate table+ * instead. Unlike the aggregate rows there is no `uncosted_*` split here: a+ * `task_usage` row is priced or it isn't, so "uncosted" is just "all of them+ * when cost_usd_ticks is absent", which is what the estimator already assumes.+ */+export interface TaskUsage {+ provider?: string;+ model: string;+ input_tokens: number;+ output_tokens: number;+ cache_read_tokens: number;+ cache_write_tokens: number;+ cost_usd_ticks?: number;}export interface Agent {diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex ff838e2b8c..0e6974271c 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -8,6 +8,7 @@ export type {AgentInvocationTarget,AgentInvocationTargetInput,AgentTask,+ TaskUsage,TaskAttribution,AttributionUser,TaskEvidence,diff --git a/packages/views/common/task-transcript/agent-transcript-dialog.tsx b/packages/views/common/task-transcript/agent-transcript-dialog.tsxindex 2dbf0f8400..08cbd2b1bd 100644--- a/packages/views/common/task-transcript/agent-transcript-dialog.tsx+++ b/packages/views/common/task-transcript/agent-transcript-dialog.tsx@@ -19,6 +19,7 @@ import {ArrowUpNarrowWide,ListCollapse,Info,+ Coins,} from "lucide-react";import { cn } from "@multica/ui/lib/utils";import { copyText } from "@multica/ui/lib/clipboard";@@ -48,6 +49,7 @@ import {} from "@multica/core/agents/stores";import type { AgentTask, Agent, AgentRuntime } from "@multica/core/types/agent";import { runtimeDisplayName } from "@multica/core/runtimes";+import { useCustomPricingStore } from "@multica/core/runtimes/custom-pricing-store";import { redactSecrets } from "./redact";import {createNewestFirstFollow,@@ -68,6 +70,11 @@ import {import type { TraceDiffLine, TracePatchFile, TraceSummaryLabels } from "./trace-event-presenter";import { highlightBlock, highlightToLines, languageForPath } from "./diff-highlight";import { useT } from "../../i18n";+import {+ formatTokens,+ formatUsd,+ summarizeTaskUsage,+} from "../../runtimes/utils";import "../../editor/styles/code.css";import "./task-transcript.css";@@ -614,12 +621,22 @@ export function AgentTranscriptDialog({}): null;const hasTriggeredBy = !!task.attribution?.initiator;+ // This run's own spend. Present on transcripts opened from the issue+ // execution log (the endpoint that hydrates usage); absent elsewhere, where+ // the chip and the usage rows below simply don't render.+ //+ // `summarizeTaskUsage` prices through the custom-rate store, which it reads+ // imperatively — subscribing here is what makes a saved rate change reach+ // this figure, same as on the other usage surfaces.+ useCustomPricingStore((s) => s.pricings);+ const usage = summarizeTaskUsage(task.usage);const hasRunDetails =!!runtimeInfo ||!!task.relative_work_dir ||!!createdLabel ||!!startedLabel ||- !!completedLabel;+ !!completedLabel ||+ !!usage;return (<Dialog open={open} onOpenChange={onOpenChange}>@@ -669,6 +686,22 @@ export function AgentTranscriptDialog({<span className="shrink-0">{triggerLabel}</span></div>+ {/* What this run cost, in the header of the run you are reading —+ so "why was this one expensive" is answerable without going+ back to the list. The split lives one click away in the ⓘ+ popover. */}+ {usage && (+ <span+ className="flex shrink-0 items-center gap-1 rounded-full border px-2 py-0.5 text-micro tabular-nums"+ title={t(($) => $.transcript.usage_chip_title)}+ >+ <Coins aria-hidden="true" className="h-3 w-3 text-muted-foreground" />+ <span className="font-medium">{formatTokens(usage.tokens)}</span>+ <span className="text-faint-foreground">·</span>+ <span className="text-muted-foreground">{formatUsd(usage.cost)}</span>+ </span>+ )}+<div className="flex shrink-0 items-center gap-0.5">{hasRunDetails && (<Popover>@@ -721,6 +754,35 @@ export function AgentTranscriptDialog({{completedLabel && (<RunDetailRow label={t(($) => $.transcript.details_completed)} value={completedLabel} />)}+ {usage && (+ <>+ <div className="my-2 h-px bg-border" />+ <RunDetailRow+ label={t(($) => $.transcript.details_input)}+ value={formatTokens(usage.input)}+ />+ <RunDetailRow+ label={t(($) => $.transcript.details_output)}+ value={formatTokens(usage.output)}+ />+ {usage.cacheRead > 0 && (+ <RunDetailRow+ label={t(($) => $.transcript.details_cache_read)}+ value={formatTokens(usage.cacheRead)}+ />+ )}+ {usage.cacheWrite > 0 && (+ <RunDetailRow+ label={t(($) => $.transcript.details_cache_write)}+ value={formatTokens(usage.cacheWrite)}+ />+ )}+ <RunDetailRow+ label={t(($) => $.transcript.details_cost)}+ value={formatUsd(usage.cost)}+ />+ </>+ )}</div></PopoverContent></Popover>diff --git a/packages/views/issues/components/execution-log-section.test.tsx b/packages/views/issues/components/execution-log-section.test.tsxindex 286fd582e3..28bafad527 100644--- a/packages/views/issues/components/execution-log-section.test.tsx+++ b/packages/views/issues/components/execution-log-section.test.tsx@@ -27,7 +27,10 @@ vi.mock("./terminate-task-confirm-dialog", () => ({TerminateTaskConfirmDialog: () => null,}));-import { ActiveTaskRow, TaskCommentCoverage } from "./execution-log-section";+import { ActiveTaskRow, TaskCommentCoverage, IssueUsageTotal } from "./execution-log-section";+import type { TaskUsage } from "@multica/core/types";+import { act } from "@testing-library/react";+import { useCustomPricingStore } from "@multica/core/runtimes/custom-pricing-store";function makeTask(overrides: Partial<AgentTask> = {}): AgentTask {return {@@ -216,3 +219,78 @@ describe("TaskCommentCoverage", () => {expect(screen.getByText("包含 3 条评论")).toBeInTheDocument();});});++// claude-opus-5 at 5 / 25 / 0.50 / 6.25 per million.+function usageSlice(overrides: Partial<TaskUsage> = {}): TaskUsage {+ return {+ provider: "anthropic",+ model: "claude-opus-5",+ input_tokens: 96_000,+ output_tokens: 34_000,+ cache_read_tokens: 712_000,+ cache_write_tokens: 50_000,+ ...overrides,+ };+}++describe("per-run token usage", () => {+ // An active row shows only its timer. The daemon reports usage once, after+ // the run returns, and that write publishes no realtime event — so no+ // running task carries usage in production. Asserting a token figure here+ // would only prove that a hand-written fixture renders.+ it("shows a running row's timer, and no token figure even if usage exists", () => {+ renderWithI18n(+ <ActiveTaskRow+ task={makeTask({ usage: [usageSlice()] })}+ issueId="issue-1"+ />,+ );++ expect(screen.getByText("5m 04s")).toBeInTheDocument();+ expect(screen.queryByText("892K")).not.toBeInTheDocument();+ // And no em dash either — mid-run, "no figure yet" is not a claim worth+ // making next to a ticking timer.+ expect(screen.queryByText("—")).not.toBeInTheDocument();+ });+});++describe("IssueUsageTotal pricing", () => {+ afterEach(() => {+ useCustomPricingStore.setState({ pricings: {} });+ });++ it("recomputes when a custom model rate is saved", () => {+ // `estimateCost` reads the custom-rate store imperatively, so nothing+ // re-renders this on a rate change unless the component subscribes. Before+ // that subscription existed the figure stayed stale until the task list+ // happened to refetch.+ const unpriced: TaskUsage = {+ provider: "acme",+ model: "totally-made-up-model",+ input_tokens: 1_000_000,+ output_tokens: 0,+ cache_read_tokens: 0,+ cache_write_tokens: 0,+ };+ const task = makeTask({ status: "completed", usage: [unpriced] });++ renderWithI18n(+ <IssueUsageTotal tasks={[task]} alone onOpen={() => {}} />,+ );++ // No rate on file for this model yet.+ expect(screen.getByText("$0.00")).toBeInTheDocument();++ act(() => {+ useCustomPricingStore.getState().setCustomPricing("acme/totally-made-up-model", {+ input: 7,+ output: 0,+ cacheRead: 0,+ cacheWrite: 0,+ });+ });++ // 1M input tokens at $7/M, without any refetch.+ expect(screen.getByText("$7.00")).toBeInTheDocument();+ });+});diff --git a/packages/views/issues/components/execution-log-section.tsx b/packages/views/issues/components/execution-log-section.tsxindex aad4544247..179b59a8c2 100644--- a/packages/views/issues/components/execution-log-section.tsx+++ b/packages/views/issues/components/execution-log-section.tsx@@ -2,10 +2,11 @@import { useEffect, useMemo, useState } from "react";import { useQuery } from "@tanstack/react-query";-import { Ban, CheckCircle2, ChevronRight, Loader2, RotateCcw, Square, XCircle } from "lucide-react";+import { ChevronRight, Loader2, RotateCcw, Square } from "lucide-react";import { toast } from "sonner";import { api, dispatchReasonCode } from "@multica/core/api";import { issueKeys } from "@multica/core/issues/queries";+import { useCustomPricingStore } from "@multica/core/runtimes/custom-pricing-store";import type { AgentTask } from "@multica/core/types";import { useTimeAgo } from "../../i18n";import {@@ -18,7 +19,16 @@ import { formatDuration } from "../../agents/components/agent-activity-hover-conimport { TranscriptButton } from "../../common/task-transcript";import { failureReasonLabel } from "../../agents/components/tabs/task-failure";import { useT } from "../../i18n";+import {+ formatTokens,+ formatUsd,+ summarizeTaskUsage,+ summarizeTaskUsageAcross,+} from "../../runtimes/utils";import { TerminateTaskConfirmDialog } from "./terminate-task-confirm-dialog";+import { IssueUsageDialog } from "./issue-usage-dialog";+import { TaskStatusIcon } from "./task-status-icon";+import { useStatusLabel, useTriggerText } from "./task-run-labels";// Right-panel section that lists every agent run for this issue. Active// runs sit at the top (always visible when present); past runs (terminal@@ -46,6 +56,8 @@ import { TerminateTaskConfirmDialog } from "./terminate-task-confirm-dialog";interface ExecutionLogSectionProps {issueId: string;+ /** Shown in the usage dialog's subtitle so the panel names what it totals. */+ identifier?: string;}// Past-runs sort priority: newest first by timestamp. When two runs@@ -57,10 +69,11 @@ const PAST_STATUS_RANK: Record<string, number> = {completed: 2,};-export function ExecutionLogSection({ issueId }: ExecutionLogSectionProps) {+export function ExecutionLogSection({ issueId, identifier }: ExecutionLogSectionProps) {const { t } = useT("issues");const [open, setOpen] = useState(true);const [showPast, setShowPast] = useState(false);+ const [usageOpen, setUsageOpen] = useState(false);// Cache key registered in `issueKeys.tasks` (packages/core/issues/queries.ts)// so the global useRealtimeSync `task:` prefix path invalidates it via@@ -112,26 +125,37 @@ export function ExecutionLogSection({ issueId }: ExecutionLogSectionProps) {return (<div>- <button- type="button"- className={`flex w-full items-center gap-1 rounded-md px-2 py-1 text-caption font-medium transition-colors mb-2 hover:bg-accent/70 ${- open ? "" : "text-muted-foreground hover:text-foreground"- }`}- onClick={() => setOpen(!open)}- >- {t(($) => $.execution_log.section)}- <ChevronRight- className={`!size-3 shrink-0 stroke-[2.5] text-muted-foreground transition-transform ${- open ? "rotate-90" : ""+ {/* Header is two independent targets, not one: the label + chevron+ collapse the section, the total on the right opens the usage+ breakdown. Nesting a button inside a button is invalid HTML, so they+ are siblings in a flex row rather than a button wrapping a button. */}+ <div className="mb-2 flex w-full items-center gap-1">+ <button+ type="button"+ className={`flex min-w-0 items-center gap-1 rounded-md px-2 py-1 text-caption font-medium transition-colors hover:bg-accent/70 ${+ open ? "" : "text-muted-foreground hover:text-foreground"}`}- />+ onClick={() => setOpen(!open)}+ >+ {t(($) => $.execution_log.section)}+ <ChevronRight+ className={`!size-3 shrink-0 stroke-[2.5] text-muted-foreground transition-transform ${+ open ? "rotate-90" : ""+ }`}+ />+ </button>{activeTasks.length > 0 && (- <span className="ml-auto inline-flex items-center gap-1 text-info">+ <span className="ml-auto inline-flex shrink-0 items-center gap-1 text-info"><span className="h-1.5 w-1.5 rounded-full bg-info animate-pulse" />- <span className="font-mono tabular-nums">{activeTasks.length}</span>+ <span className="font-mono text-caption tabular-nums">{activeTasks.length}</span></span>)}- </button>+ <IssueUsageTotal+ tasks={tasks}+ alone={activeTasks.length === 0}+ onOpen={() => setUsageOpen(true)}+ />+ </div>{open && (<div className="space-y-0.5 pl-2">{activeTasks.map((task) => (@@ -168,26 +192,65 @@ export function ExecutionLogSection({ issueId }: ExecutionLogSectionProps) {)}</div>)}+ <IssueUsageDialog+ open={usageOpen}+ onOpenChange={setUsageOpen}+ identifier={identifier ?? ""}+ tasks={tasks}+ /></div>);}-// ─── Trigger description ────────────────────────────────────────────────────+// ─── Issue total ───────────────────────────────────────────────────────────-// Primary source: the canonical snapshot taken at task creation time-// (comment text / autopilot title). Survives source edits/deletes and-// is information-dense — far better than a structural label.-//-// Retry tasks inherit the parent's trigger_summary on the DB side (so the-// snapshot survives across attempts), but a row that just shows the-// inherited summary is indistinguishable from its parent. We prepend-// "Retry #N" when parent_task_id is set so retries are scannable as-// retries even when their summary is inherited.+// The issue's whole spend, as a header affordance: "2.1M · $4.92". Answers+// "what has this issue cost" without expanding anything, and is the entry+// point to the per-run breakdown.//-// Fallback chain for legacy tasks created before the snapshot field-// shipped, OR for sources we don't snapshot (direct assignment / chat):-// degrade to a short structural label by trigger source. New tasks-// (post-061 migration) almost always hit the snapshot path.+// Renders nothing when no run on the issue has recorded usage — an issue whose+// runs all predate usage reporting gets its old header back rather than a+// "0 · $0.00" that would read as "this was free".+export function IssueUsageTotal({+ tasks,+ alone,+ onOpen,+}: {+ tasks: AgentTask[];+ alone: boolean;+ onOpen: () => void;+}) {+ const { t } = useT("issues");+ // Custom rates are read imperatively inside `estimateCost`, so a saved rate+ // change does not re-render this on its own — subscribe and make the memo+ // depend on the snapshot, or the header total keeps quoting the old price+ // until the task list refetches.+ const pricings = useCustomPricingStore((s) => s.pricings);+ const total = useMemo(+ () => summarizeTaskUsageAcross(tasks.map((task) => task.usage)),+ [tasks, pricings],+ );+ if (!total) return null;++ return (+ <Tooltip>+ <TooltipTrigger+ render={<button type="button" onClick={onOpen} />}+ className={`flex shrink-0 items-center gap-1 rounded-md px-1.5 py-0.5 text-caption tabular-nums transition-colors hover:bg-accent/70 ${+ alone ? "ml-auto" : ""+ }`}+ >+ <span className="font-medium">{formatTokens(total.tokens)}</span>+ <span className="text-faint-foreground">·</span>+ <span className="text-muted-foreground">{formatUsd(total.cost)}</span>+ </TooltipTrigger>+ <TooltipContent>{t(($) => $.execution_log.usage_total_tooltip)}</TooltipContent>+ </Tooltip>+ );+}++// Trigger description and status labels live in ./task-run-labels so the+// usage dialog lists a run exactly the way this section does.// ─── Row visual config ─────────────────────────────────────────────────────@@ -205,48 +268,6 @@ const STATUS_TONE: Record<AgentTask["status"], string> = {// ─── Active row ────────────────────────────────────────────────────────────-import { stripMentionMarkdown } from "../utils/strip-mention-markdown";--function useTriggerText(task: AgentTask): string {- const { t } = useT("issues");- const isRetry = !!task.parent_task_id;- const retryPrefix = isRetry- ? task.attempt && task.attempt > 1- ? t(($) => $.execution_log.trigger_retry_attempt_prefix, { attempt: task.attempt })- : t(($) => $.execution_log.trigger_retry_prefix)- : "";-- if (task.trigger_summary) return retryPrefix + stripMentionMarkdown(task.trigger_summary);- if (isRetry) {- return task.attempt && task.attempt > 1- ? t(($) => $.execution_log.trigger_retry_attempt, { attempt: task.attempt })- : t(($) => $.execution_log.trigger_retry);- }- if (task.autopilot_run_id) return t(($) => $.execution_log.trigger_autopilot);- if (task.trigger_comment_id) return t(($) => $.execution_log.trigger_comment);- // Assignment-triggered run that carried a handoff note: show the note inline- // (truncated by TriggerText) the way comment triggers show their text, so the- // row reads as the handoff instead of the generic "initial run".- if (task.handoff_note) {- return retryPrefix + t(($) => $.execution_log.trigger_handoff_prefix) + stripMentionMarkdown(task.handoff_note);- }- return t(($) => $.execution_log.trigger_initial);-}--function useStatusLabel(status: AgentTask["status"]): string {- const { t } = useT("issues");- switch (status) {- case "queued": return t(($) => $.execution_log.status_queued);- case "dispatched": return t(($) => $.execution_log.status_dispatched);- case "waiting_local_directory":- return t(($) => $.execution_log.status_waiting_local_directory);- case "running": return t(($) => $.execution_log.status_running);- case "completed": return t(($) => $.execution_log.status_completed);- case "failed": return t(($) => $.execution_log.status_failed);- case "cancelled": return t(($) => $.execution_log.status_cancelled);- }-}-// One active (running / queued / dispatched / parked) task row. Running rows// keep status to a single live elapsed timer; transcript and stop stay available// as hover actions. Transcript content lazy-loads on click via TranscriptButton,@@ -304,6 +325,13 @@ export function ActiveTaskRow({setConfirmOpen(true);};+ // Deliberately no token figure on an active row: the daemon reports usage+ // once, after `runner.run` returns (server/internal/daemon/daemon.go), and+ // the write publishes no realtime event — so a running task has no usage to+ // show, and would not learn of it mid-run if it did. Rendering the branch+ // anyway would only ever be exercised by hand-written fixtures, which is a+ // test that asserts a scenario production cannot produce. Restore it in the+ // same change that adds incremental reporting + cache invalidation.return (<RowShell task={task}><TriggerText text={trigger} />@@ -375,6 +403,29 @@ function PastRow({ task, issueId }: { task: AgentTask; issueId: string }) {const failureLabel =task.status === "failed" ? failureReasonLabel(task.failure_reason) : null;+ // What this run cost, in the slot the relative timestamp used to hold.+ //+ // The sidebar is 288px and the row already carries an avatar, the trigger+ // text, and a status mark; a third column would come straight out of the+ // trigger, which is what people scan this list for. The list is sorted+ // newest-first, so "which run came first" is already expressed by position —+ // the exact "when" is the detail, and how much it cost is the new question.+ // The displaced timestamp moves into the row tooltip below, together with+ // the duration and model, which were previously not surfaced here at all.+ //+ // `null` (no usage recorded) renders an em dash, never 0: a run from before+ // usage reporting was not free, we simply have no figure for it.+ const usage = summarizeTaskUsage(task.usage);+ const rowTitle = [+ time,+ task.started_at && task.completed_at+ ? formatDuration(task.started_at, new Date(task.completed_at).getTime())+ : "",+ usage?.models.join(", ") ?? "",+ ]+ .filter(Boolean)+ .join(" · ");+// Retry only makes sense for terminal-but-not-success rows. Passing// task.id targets this specific row's agent — without it, the rerun// endpoint would fall back to the issue's current assignee and the@@ -407,13 +458,19 @@ function PastRow({ task, issueId }: { task: AgentTask; issueId: string }) {};return (- <RowShell task={task}>+ <RowShell task={task} title={rowTitle}><TriggerText text={trigger} /><TaskCommentCoverage task={task} /><RowStatus title={failureLabel ?? label}><TaskStatusIcon status={task.status} />- <span className="sr-only">{failureLabel ?? label}</span>- <span className="text-muted-foreground">{time}</span>+ <span className="sr-only">+ {[failureLabel ?? label, time].filter(Boolean).join(" · ")}+ </span>+ {usage ? (+ <span className="tabular-nums">{formatTokens(usage.tokens)}</span>+ ) : (+ <span className="text-faint-foreground">—</span>+ )}</RowStatus><RowActions><TranscriptButton task={task} agentName="" title={t(($) => $.execution_log.transcript_tooltip)} />@@ -448,13 +505,22 @@ function PastRow({ task, issueId }: { task: AgentTask; issueId: string }) {function RowShell({task,+ title,children,}: {task: AgentTask;+ /** Carries the details the right column no longer has room for (time,+ * duration, model). Lives on the row, not on RowStatus, because RowStatus+ * is swapped out for the action buttons on hover — a title there would+ * disappear at exactly the moment the pointer arrives. */+ title?: string;children: React.ReactNode;}) {return (- <div className="group/execution-log-row flex items-center gap-2 overflow-hidden rounded px-1 py-1.5 transition-colors hover:bg-accent/40">+ <div+ title={title || undefined}+ className="group/execution-log-row flex items-center gap-2 overflow-hidden rounded px-1 py-1.5 transition-colors hover:bg-accent/40"+ >{task.agent_id ? (<ActorAvataractorType="agent"@@ -534,19 +600,6 @@ function RowStatus({);}-function TaskStatusIcon({ status }: { status: AgentTask["status"] }) {- switch (status) {- case "completed":- return <CheckCircle2 aria-hidden="true" className="h-3.5 w-3.5 text-success" />;- case "failed":- return <XCircle aria-hidden="true" className="h-3.5 w-3.5 text-destructive" />;- case "cancelled":- return <Ban aria-hidden="true" className="h-3.5 w-3.5 text-muted-foreground" />;- default:- return null;- }-}-// Action slot — visible by default for touch devices. On hover-capable// surfaces, it replaces the status column in place on row hover.function RowActions({ children }: { children: React.ReactNode }) {diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex 1cf1dbc99b..0b95d14735 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -87,7 +87,7 @@ import { useWorkspacePaths } from "@multica/core/paths";import { useActorName } from "@multica/core/workspace/hooks";import { useWorkspaceId } from "@multica/core/hooks";import { useRecentContextStore } from "@multica/core/chat";-import { issueListOptions, issueDetailOptions, childIssuesOptions, childIssueProgressOptions, issueUsageOptions, issueAttachmentsOptions } from "@multica/core/issues/queries";+import { issueListOptions, issueDetailOptions, childIssuesOptions, childIssueProgressOptions, issueAttachmentsOptions } from "@multica/core/issues/queries";import { projectDetailOptions } from "@multica/core/projects/queries";import { ProjectIcon } from "../../projects/components/project-icon";import { issueLabelsOptions } from "@multica/core/labels";@@ -327,12 +327,6 @@ function formatActivity(// Helpers// ----------------------------------------------------------------------------function formatTokenCount(n: number): string {- if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;- if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`;- return String(n);-}-// Stable reference for threads with no replies. Inline `[]` would create a// new array on every render and bust React.memo on CommentCard / ResolvedThreadBar.const EMPTY_REPLIES: TimelineEntry[] = [];@@ -1107,7 +1101,6 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = trconst [parentIssueOpen, setParentIssueOpen] = useState(true);const [pullRequestsOpen, setPullRequestsOpen] = useState(true);const [metadataOpen, setMetadataOpen] = useState(false);- const [tokenUsageOpen, setTokenUsageOpen] = useState(true);const githubSettings = useGitHubSettings();// Per-issue, per-session set of optional properties currently visible in@@ -1587,9 +1580,6 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = trunsubscribeFromSubtree: handleUnsubscribeSubtree,} = useIssueSubscribers(id, user?.id);- // Token usage- const { data: usage } = useQuery(issueUsageOptions(id));-// Attachments uploaded against this issue. Drives the description// editor's click-time fresh-sign download: NodeViews match// `src`/`href` against this list to resolve an attachment id before@@ -2233,10 +2223,11 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr</div>)}- {/* Execution log — active runs + collapsed past runs. Self-contained;- owns its own collapse state and WS subscriptions. Hides itself- when there are no runs to show. */}- <ExecutionLogSection issueId={id} />+ {/* Execution log — active runs + collapsed past runs, each carrying its+ own token spend, with the issue total on the section header.+ Self-contained; owns its own collapse state and WS subscriptions.+ Hides itself when there are no runs to show. */}+ <ExecutionLogSection issueId={id} identifier={issue.identifier} />{/* Details — creator and timestamps. Sits below the execution logbecause it is the least-read block in the sidebar: the values@@ -2265,40 +2256,12 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr</div>}</div>- {/* Token usage */}- {usage && usage.task_count > 0 && (- <div>- <button- type="button"- className={`flex w-full items-center gap-1 rounded-md px-2 py-1 text-caption font-medium transition-colors mb-2 hover:bg-accent/70 ${tokenUsageOpen ? "" : "text-muted-foreground hover:text-foreground"}`}- onClick={() => setTokenUsageOpen(!tokenUsageOpen)}- >- {t(($) => $.detail.section_token_usage)}- <ChevronRight className={`!size-3 shrink-0 stroke-[2.5] text-muted-foreground transition-transform ${tokenUsageOpen ? "rotate-90" : ""}`} />- </button>- {tokenUsageOpen && <div className="grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5 pl-2">- <PropRow label={t(($) => $.detail.prop_input)}>- <span className="text-muted-foreground">{formatTokenCount(usage.total_input_tokens)}</span>- </PropRow>- <PropRow label={t(($) => $.detail.prop_output)}>- <span className="text-muted-foreground">{formatTokenCount(usage.total_output_tokens)}</span>- </PropRow>- {(usage.total_cache_read_tokens > 0 || usage.total_cache_write_tokens > 0) && (- <PropRow label={t(($) => $.detail.prop_cache)}>- <span className="text-muted-foreground">- {t(($) => $.detail.prop_cache_value, {- read: formatTokenCount(usage.total_cache_read_tokens),- write: formatTokenCount(usage.total_cache_write_tokens),- })}- </span>- </PropRow>- )}- <PropRow label={t(($) => $.detail.prop_runs)}>- <span className="text-muted-foreground">{usage.task_count}</span>- </PropRow>- </div>}- </div>- )}+ {/* The standalone "Token usage" section that used to sit here is gone:+ it showed the same issue totals the execution-log header now carries,+ minus the cost and minus any way to tell which run spent them. Its+ every field (input / output / cache / run count) lives in the usage+ dialog that header opens. The `/api/issues/:id/usage` endpoint it+ read stays — the CLI's `issue usage` command still uses it. */}{/* Metadata — agent-facing free-form KV bag. The values almostnever mean anything to humans, so the trigger row matches thediff --git a/packages/views/issues/components/issue-usage-dialog.tsx b/packages/views/issues/components/issue-usage-dialog.tsxnew file mode 100644index 0000000000..c1c68615e9--- /dev/null+++ b/packages/views/issues/components/issue-usage-dialog.tsx@@ -0,0 +1,365 @@+"use client";++import { useMemo } from "react";+import type { AgentTask } from "@multica/core/types";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+} from "@multica/ui/components/ui/dialog";+import { useActorName } from "@multica/core/workspace/hooks";+import { useCustomPricingStore } from "@multica/core/runtimes/custom-pricing-store";+import { ActorAvatar } from "../../common/actor-avatar";+import { useT } from "../../i18n";+import { formatDuration } from "../../agents/components/agent-activity-hover-content";+import {+ collectUnmappedModels,+ formatTokens,+ formatUsd,+ summarizeTaskUsage,+ summarizeTaskUsageAcross,+ type TaskUsageSummary,+} from "../../runtimes/utils";+import { KpiCard } from "../../runtimes/components/shared";+import { useStatusLabel, useTriggerText } from "./task-run-labels";+import { TaskStatusIcon } from "./task-status-icon";++// Per-run cost breakdown for one issue — the surface the execution log's+// header total opens.+//+// The execution log answers "how much did this run cost" one row at a time;+// this answers "which run cost the most, and why". That comparison needs the+// input / output / cache split side by side, which the 288px sidebar cannot+// hold, so it lives here instead of expanding the rows.+//+// Every figure comes from the same `summarizeTaskUsage` helpers the sidebar+// uses, so the total here can never disagree with the total that opened it.++export function IssueUsageDialog({+ open,+ onOpenChange,+ identifier,+ tasks,+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ identifier: string;+ tasks: AgentTask[];+}) {+ const { t } = useT("issues");+ // `estimateCost` reads custom rates imperatively out of the Zustand store,+ // so nothing re-renders this dialog when the user saves a new rate. Subscribe+ // to the snapshot and carry it into every memo that prices usage — otherwise+ // the totals, the per-run costs, and the "unmapped model" notice all keep+ // showing the old price until the task list happens to refetch. Same reason+ // the runtime usage page subscribes in usage-section.tsx.+ const pricings = useCustomPricingStore((s) => s.pricings);++ // Only runs that actually recorded usage earn a row: a run with no figure+ // contributes nothing to compare and would just add an all-em-dash line.+ // Their existence is still accounted for in the footnote below.+ const priced = useMemo(+ () => tasks.filter((task) => (task.usage?.length ?? 0) > 0),+ [tasks],+ );+ const unpricedCount = tasks.length - priced.length;++ const total = useMemo(+ () => summarizeTaskUsageAcross(priced.map((task) => task.usage)),+ [priced, pricings],+ );++ const agentIds = useMemo(+ () => Array.from(new Set(priced.map((task) => task.agent_id).filter(Boolean))),+ [priced],+ );++ // Models with no rate-table entry and no provider-reported cost: their+ // tokens are counted but their spend is not, so the totals below understate+ // reality. Saying so is the difference between an estimate and a wrong number.+ const unmapped = useMemo(+ () => collectUnmappedModels(priced.flatMap((task) => task.usage ?? [])),+ [priced, pricings],+ );++ const cacheHitRate =+ total && total.input + total.cacheRead > 0+ ? Math.round((total.cacheRead / (total.input + total.cacheRead)) * 100)+ : 0;++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ {/* DialogContent's base is `sm:max-w-sm`, which the same-specificity+ `max-w-4xl` does not beat — the table then overflows the box instead+ of the box growing. `!` wins it, matching the transcript dialog. */}+ <DialogContent className="!max-w-4xl !w-[calc(100vw-4rem)]">+ <DialogHeader>+ <DialogTitle>{t(($) => $.usage_detail.title)}</DialogTitle>+ <DialogDescription>+ {t(($) => $.usage_detail.subtitle, {+ identifier,+ count: priced.length,+ })}+ </DialogDescription>+ </DialogHeader>++ {total == null ? (+ <p className="py-8 text-center text-body text-muted-foreground">+ {t(($) => $.usage_detail.empty)}+ </p>+ ) : (+ <div className="flex flex-col gap-5">+ <div className="grid grid-cols-3 divide-x rounded-lg border bg-card">+ <KpiCard+ label={t(($) => $.usage_detail.kpi_cost)}+ value={formatUsd(total.cost)}+ hint={<CostConcentrationHint tasks={priced} total={total} />}+ />+ <KpiCard+ label={t(($) => $.usage_detail.kpi_cache)}+ value={formatUsd(total.cacheSavings)}+ accent={total.cacheSavings > 0 ? "success" : "default"}+ hint={t(($) => $.usage_detail.kpi_cache_hint, {+ pct: cacheHitRate,+ reads: formatTokens(total.cacheRead),+ })}+ />+ <KpiCard+ label={t(($) => $.usage_detail.kpi_tokens)}+ value={formatTokens(total.tokens)}+ hint={t(($) => $.usage_detail.kpi_tokens_hint, {+ input: formatTokens(total.input),+ output: formatTokens(total.output),+ })}+ />+ </div>++ {agentIds.length > 1 && (+ <CostByAgent tasks={priced} agentIds={agentIds} total={total} />+ )}++ <RunTable tasks={priced} total={total} />++ <div className="space-y-1 text-micro text-muted-foreground">+ {unpricedCount > 0 && (+ <p>{t(($) => $.usage_detail.note_unpriced, { count: unpricedCount })}</p>+ )}+ {unmapped.length > 0 && (+ <p>+ {t(($) => $.usage_detail.note_unmapped, { models: unmapped.join(", ") })}+ </p>+ )}+ <p>{t(($) => $.usage_detail.note_estimate)}</p>+ </div>+ </div>+ )}+ </DialogContent>+ </Dialog>+ );+}++// "N failed runs account for X%" — the single most useful thing the total can+// say about itself, and the reason this dialog exists. Rendered only when+// there IS a failed run with a cost, so a healthy issue gets no scolding hint.+function CostConcentrationHint({+ tasks,+ total,+}: {+ tasks: AgentTask[];+ total: TaskUsageSummary;+}) {+ const { t } = useT("issues");+ const failed = tasks.filter((task) => task.status === "failed");+ if (failed.length === 0 || total.cost <= 0) return null;++ const failedCost = failed.reduce(+ (sum, task) => sum + (summarizeTaskUsage(task.usage)?.cost ?? 0),+ 0,+ );+ if (failedCost <= 0) return null;++ return (+ <span className="text-warning">+ {t(($) => $.usage_detail.kpi_cost_hint, {+ count: failed.length,+ pct: Math.round((failedCost / total.cost) * 100),+ })}+ </span>+ );+}++// Same bar language as the runtime usage page's "Cost by agent" block: one row+// per agent, bar scaled to the biggest spender. Hidden entirely for a+// single-agent issue, where a one-bar chart says nothing the total didn't.+function CostByAgent({+ tasks,+ agentIds,+ total,+}: {+ tasks: AgentTask[];+ agentIds: string[];+ total: TaskUsageSummary;+}) {+ const { t } = useT("issues");+ const { getActorName } = useActorName();+ const pricings = useCustomPricingStore((s) => s.pricings);++ const rows = useMemo(() => {+ return agentIds+ .map((agentId) => {+ const own = tasks.filter((task) => task.agent_id === agentId);+ const summary = summarizeTaskUsageAcross(own.map((task) => task.usage));+ return { agentId, cost: summary?.cost ?? 0, tokens: summary?.tokens ?? 0 };+ })+ .toSorted((a, b) => b.cost - a.cost);+ }, [agentIds, tasks, pricings]);++ const maxCost = rows.reduce((m, r) => Math.max(m, r.cost), 0);++ return (+ <div>+ <div className="mb-2 text-caption font-medium">+ {t(($) => $.usage_detail.by_agent)}+ </div>+ <div className="space-y-2">+ {rows.map((row) => (+ <div+ key={row.agentId}+ className="grid grid-cols-[minmax(0,1fr)_minmax(0,2fr)_5rem_4rem] items-center gap-3"+ >+ <div className="flex min-w-0 items-center gap-2">+ <ActorAvatar actorType="agent" actorId={row.agentId} size="sm" enableHoverCard />+ <span className="truncate text-caption">+ {getActorName("agent", row.agentId)}+ </span>+ </div>+ <div className="relative h-2 overflow-hidden rounded-full bg-muted">+ <div+ className="h-full rounded-full bg-chart-1"+ style={{ width: `${maxCost > 0 ? (row.cost / maxCost) * 100 : 0}%` }}+ />+ </div>+ <div className="text-right text-caption tabular-nums text-muted-foreground">+ {formatTokens(row.tokens)}+ </div>+ <div className="text-right text-caption font-medium tabular-nums">+ {formatUsd(row.cost)}+ </div>+ </div>+ ))}+ </div>+ <div className="sr-only">+ {t(($) => $.usage_detail.by_agent_total, { cost: formatUsd(total.cost) })}+ </div>+ </div>+ );+}++function RunTable({ tasks, total }: { tasks: AgentTask[]; total: TaskUsageSummary }) {+ const { t } = useT("issues");+ const maxTokens = tasks.reduce(+ (m, task) => Math.max(m, summarizeTaskUsage(task.usage)?.tokens ?? 0),+ 0,+ );++ return (+ // Nine columns of numbers have a floor width; on a narrow window they+ // scroll sideways rather than squeezing the trigger text to nothing or+ // pushing the totals outside the dialog.+ <div className="max-h-[45vh] overflow-auto">+ <table className="w-full min-w-[46rem]">+ <thead className="sticky top-0 bg-popover">+ <tr className="text-micro text-muted-foreground [&>th]:whitespace-nowrap [&>th]:px-2 [&>th]:pb-1.5 [&>th]:text-right [&>th]:font-normal">+ <th className="!pl-0 !text-left">{t(($) => $.usage_detail.col_run)}</th>+ <th>{t(($) => $.usage_detail.col_model)}</th>+ <th>{t(($) => $.usage_detail.col_duration)}</th>+ <th>{t(($) => $.usage_detail.col_input)}</th>+ <th>{t(($) => $.usage_detail.col_output)}</th>+ <th>{t(($) => $.usage_detail.col_cache_read)}</th>+ <th>{t(($) => $.usage_detail.col_cache_write)}</th>+ <th className="!pr-16">{t(($) => $.usage_detail.col_tokens)}</th>+ <th className="!pr-0">{t(($) => $.usage_detail.col_cost)}</th>+ </tr>+ </thead>+ <tbody>+ {tasks.map((task) => (+ <RunRow key={task.id} task={task} maxTokens={maxTokens} />+ ))}+ </tbody>+ <tfoot>+ <tr className="text-caption font-medium tabular-nums [&>td]:whitespace-nowrap [&>td]:border-t [&>td]:border-input [&>td]:px-2 [&>td]:py-2 [&>td]:text-right">+ <td className="!pl-0 !text-left">{t(($) => $.usage_detail.total)}</td>+ <td colSpan={2} />+ <td>{formatTokens(total.input)}</td>+ <td>{formatTokens(total.output)}</td>+ <td>{formatTokens(total.cacheRead)}</td>+ <td>{formatTokens(total.cacheWrite)}</td>+ <td className="!pr-16">{formatTokens(total.tokens)}</td>+ <td className="!pr-0">{formatUsd(total.cost)}</td>+ </tr>+ </tfoot>+ </table>+ </div>+ );+}++function RunRow({ task, maxTokens }: { task: AgentTask; maxTokens: number }) {+ const { t } = useT("issues");+ const trigger = useTriggerText(task);+ const statusLabel = useStatusLabel(task.status);+ const summary = summarizeTaskUsage(task.usage);+ if (!summary) return null;++ const duration =+ task.started_at && task.completed_at+ ? formatDuration(task.started_at, new Date(task.completed_at).getTime())+ : "";++ return (+ <tr className="text-caption tabular-nums transition-colors hover:bg-accent/40 [&>td]:whitespace-nowrap [&>td]:border-t [&>td]:px-2 [&>td]:py-1.5 [&>td]:text-right">+ <td className="!pl-0 !text-left">+ <div className="flex items-center gap-2">+ <ActorAvatar actorType="agent" actorId={task.agent_id} size="sm" enableHoverCard />+ <span className="max-w-[13rem] truncate">{trigger}</span>+ {task.status === "running" ? (+ <span className="inline-flex shrink-0 items-center gap-1 text-micro text-info">+ <span className="h-1.5 w-1.5 rounded-full bg-info" />+ {t(($) => $.execution_log.status_running)}+ </span>+ ) : (+ <>+ {/* TaskStatusIcon is aria-hidden, so the glyph alone leaves a+ screen reader with no way to tell a failed run from a+ completed one. Same sr-only pairing the execution log rows+ use. */}+ <TaskStatusIcon status={task.status} />+ <span className="sr-only">{statusLabel}</span>+ </>+ )}+ </div>+ </td>+ <td className="text-micro text-muted-foreground">+ {summary.models.join(", ") || "—"}+ </td>+ <td className="text-muted-foreground">{duration || "—"}</td>+ <td>{formatTokens(summary.input)}</td>+ <td>{formatTokens(summary.output)}</td>+ <td>{formatTokens(summary.cacheRead)}</td>+ <td>{formatTokens(summary.cacheWrite)}</td>+ <td className="!pr-2">+ <div className="flex items-center justify-end gap-2">+ <span>{formatTokens(summary.tokens)}</span>+ <span className="relative h-1 w-14 overflow-hidden rounded-full bg-muted">+ <span+ className="absolute inset-y-0 left-0 rounded-full bg-chart-1"+ style={{ width: `${maxTokens > 0 ? (summary.tokens / maxTokens) * 100 : 0}%` }}+ />+ </span>+ </div>+ </td>+ <td className="!pr-0 font-medium">{formatUsd(summary.cost)}</td>+ </tr>+ );+}diff --git a/packages/views/issues/components/task-run-labels.ts b/packages/views/issues/components/task-run-labels.tsnew file mode 100644index 0000000000..d978634137--- /dev/null+++ b/packages/views/issues/components/task-run-labels.ts@@ -0,0 +1,82 @@+import type { AgentTask } from "@multica/core/types";+import { useT } from "../../i18n";+import { stripMentionMarkdown } from "../utils/strip-mention-markdown";++// Display labels shared by every surface that lists an issue's agent runs:+// the execution log rows and the usage-detail dialog. They live here rather+// than in either component so the two can't drift — a run must read the same+// in the sidebar and in the table it opens.++/**+ * Human label for what caused this run.+ *+ * Primary source: the canonical snapshot taken at task creation time+ * (comment text / autopilot title). Survives source edits/deletes and is+ * information-dense — far better than a structural label.+ *+ * Retry tasks inherit the parent's trigger_summary on the DB side (so the+ * snapshot survives across attempts), but a row that just shows the inherited+ * summary is indistinguishable from its parent. We prepend "Retry #N" when+ * parent_task_id is set so retries are scannable as retries even when their+ * summary is inherited.+ *+ * Fallback chain for legacy tasks created before the snapshot field shipped,+ * OR for sources we don't snapshot (direct assignment / chat): degrade to a+ * short structural label by trigger source. New tasks (post-061 migration)+ * almost always hit the snapshot path.+ */+export function useTriggerText(task: AgentTask): string {+ const { t } = useT("issues");+ const isRetry = !!task.parent_task_id;+ const retryPrefix = isRetry+ ? task.attempt && task.attempt > 1+ ? t(($) => $.execution_log.trigger_retry_attempt_prefix, { attempt: task.attempt })+ : t(($) => $.execution_log.trigger_retry_prefix)+ : "";++ if (task.trigger_summary) return retryPrefix + stripMentionMarkdown(task.trigger_summary);+ if (isRetry) {+ return task.attempt && task.attempt > 1+ ? t(($) => $.execution_log.trigger_retry_attempt, { attempt: task.attempt })+ : t(($) => $.execution_log.trigger_retry);+ }+ if (task.autopilot_run_id) return t(($) => $.execution_log.trigger_autopilot);+ if (task.trigger_comment_id) return t(($) => $.execution_log.trigger_comment);+ // Assignment-triggered run that carried a handoff note: show the note inline+ // (truncated by the caller) the way comment triggers show their text, so the+ // row reads as the handoff instead of the generic "initial run".+ if (task.handoff_note) {+ return retryPrefix + t(($) => $.execution_log.trigger_handoff_prefix) + stripMentionMarkdown(task.handoff_note);+ }+ return t(($) => $.execution_log.trigger_initial);+}++export function useStatusLabel(status: AgentTask["status"]): string {+ const { t } = useT("issues");+ switch (status) {+ case "queued": return t(($) => $.execution_log.status_queued);+ case "dispatched": return t(($) => $.execution_log.status_dispatched);+ case "waiting_local_directory":+ return t(($) => $.execution_log.status_waiting_local_directory);+ case "running": return t(($) => $.execution_log.status_running);+ case "completed": return t(($) => $.execution_log.status_completed);+ case "failed": return t(($) => $.execution_log.status_failed);+ case "cancelled": return t(($) => $.execution_log.status_cancelled);+ default: return status;+ }+}++/**+ * Wall-clock duration of a finished run, or "" when the task never started or+ * never finished. Deliberately not computed for running tasks: the execution+ * log already ticks a live elapsed timer for those, and a second, frozen+ * figure next to it would contradict it.+ */+export function taskDurationMs(task: AgentTask): number | null {+ const startIso = task.started_at ?? task.dispatched_at;+ if (!startIso || !task.completed_at) return null;+ const start = new Date(startIso).getTime();+ const end = new Date(task.completed_at).getTime();+ if (!Number.isFinite(start) || !Number.isFinite(end) || end < start) return null;+ return end - start;+}diff --git a/packages/views/issues/components/task-status-icon.tsx b/packages/views/issues/components/task-status-icon.tsxnew file mode 100644index 0000000000..a45f119874--- /dev/null+++ b/packages/views/issues/components/task-status-icon.tsx@@ -0,0 +1,20 @@+import { Ban, CheckCircle2, XCircle } from "lucide-react";+import type { AgentTask } from "@multica/core/types";++// Terminal-status glyph for one agent run. Shared by the execution log rows+// and the usage-detail dialog so a failed run carries the same mark wherever+// it is listed. Non-terminal statuses render nothing: those rows carry a live+// timer or a status word instead, and a glyph next to either reads as a+// second, contradictory status.+export function TaskStatusIcon({ status }: { status: AgentTask["status"] }) {+ switch (status) {+ case "completed":+ return <CheckCircle2 aria-hidden="true" className="h-3.5 w-3.5 shrink-0 text-success" />;+ case "failed":+ return <XCircle aria-hidden="true" className="h-3.5 w-3.5 shrink-0 text-destructive" />;+ case "cancelled":+ return <Ban aria-hidden="true" className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />;+ default:+ return null;+ }+}diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.jsonindex 30ccad9c95..accbd0a45e 100644--- a/packages/views/locales/en/agents.json+++ b/packages/views/locales/en/agents.json@@ -817,7 +817,13 @@"copy_workdir": "Copy working directory","close": "Close","fact_created": "Created {{time}}",- "fact_took": "Took {{duration}}"+ "fact_took": "Took {{duration}}",+ "details_input": "Input",+ "details_output": "Output",+ "details_cache_read": "Cache read",+ "details_cache_write": "Cache write",+ "details_cost": "Cost",+ "usage_chip_title": "Tokens and estimated cost for this run"},"task_failure": {"agent_error": "Agent execution error",diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex 78787344f5..6ffc577330 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -246,7 +246,6 @@"section_pull_requests": "Pull requests","section_metadata": "Metadata","section_details": "Details",- "section_token_usage": "Token usage","section_quick_actions": "Quick Actions","quick_actions_more": "Show {{count}} more","quick_action_runs_as": "Runs as {{name}}",@@ -295,11 +294,6 @@"prop_created_by": "Created by","prop_created": "Created","prop_updated": "Updated",- "prop_input": "Input",- "prop_output": "Output",- "prop_cache": "Cache",- "prop_cache_value": "{{read}} read / {{write}} write",- "prop_runs": "Runs","activity_section": "Activity","subscribe": "Subscribe","unsubscribe": "Unsubscribe",@@ -543,7 +537,37 @@"source_owner_fallback": "No precise owner — attributed to the agent owner","source_backfill": "Backfilled attribution","source_unattributed": "No responsible member resolved"- }+ },+ "usage_total_tooltip": "Token usage for this issue — click for the per-run breakdown"+ },+ "usage_detail": {+ "title": "Usage breakdown",+ "subtitle_one": "{{identifier}} · {{count}} run",+ "subtitle_other": "{{identifier}} · {{count}} runs",+ "empty": "No run on this issue has recorded token usage yet.",+ "kpi_cost": "Cost",+ "kpi_cost_hint_one": "{{count}} failed run accounts for {{pct}}%",+ "kpi_cost_hint_other": "{{count}} failed runs account for {{pct}}%",+ "kpi_cache": "Cache savings",+ "kpi_cache_hint": "{{pct}}% hit rate · {{reads}} read",+ "kpi_tokens": "Tokens",+ "kpi_tokens_hint": "{{input}} in · {{output}} out",+ "by_agent": "By agent",+ "by_agent_total": "Total {{cost}}",+ "col_run": "Run",+ "col_model": "Model",+ "col_duration": "Duration",+ "col_input": "In",+ "col_output": "Out",+ "col_cache_read": "Cache R",+ "col_cache_write": "Cache W",+ "col_tokens": "Tokens",+ "col_cost": "Cost",+ "total": "Total",+ "note_unpriced_one": "{{count}} run has no recorded usage and is not counted in the total.",+ "note_unpriced_other": "{{count}} runs have no recorded usage and are not counted in the total.",+ "note_unmapped": "No price on file for {{models}}; their tokens are counted but their cost is not.",+ "note_estimate": "Cost is estimated from published model rates, except where the provider reported its own figure."},"terminate_dialog": {"title": "Stop this task?",diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.jsonindex 9fadb25fd8..0e8e323a73 100644--- a/packages/views/locales/ja/agents.json+++ b/packages/views/locales/ja/agents.json@@ -695,7 +695,13 @@"copy_workdir": "作業ディレクトリをコピー","close": "閉じる","fact_created": "作成 {{time}}",- "fact_took": "所要 {{duration}}"+ "fact_took": "所要 {{duration}}",+ "details_input": "入力",+ "details_output": "出力",+ "details_cache_read": "キャッシュ読み取り",+ "details_cache_write": "キャッシュ書き込み",+ "details_cost": "費用",+ "usage_chip_title": "この実行のトークンと推定費用"},"task_failure": {"agent_error": "エージェント実行エラー",diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.jsonindex f4ac0ca8a2..daf6e2e464 100644--- a/packages/views/locales/ja/issues.json+++ b/packages/views/locales/ja/issues.json@@ -244,7 +244,6 @@"section_pull_requests": "Pull requests","section_metadata": "メタデータ","section_details": "詳細",- "section_token_usage": "トークン使用量","section_quick_actions": "クイックアクション","quick_actions_more": "残り {{count}} 件を表示","quick_action_runs_as": "{{name}} が実行します",@@ -292,11 +291,6 @@"prop_created_by": "作成者","prop_created": "作成日","prop_updated": "更新日",- "prop_input": "入力",- "prop_output": "出力",- "prop_cache": "キャッシュ",- "prop_cache_value": "読み取り {{read}} / 書き込み {{write}}",- "prop_runs": "実行","activity_section": "アクティビティ","subscribe": "購読","unsubscribe": "購読解除",@@ -520,7 +514,34 @@"source_owner_fallback": "正確な責任者なし — エージェント所有者に帰属","source_backfill": "バックフィルされた帰属","source_unattributed": "責任メンバーを解決できません"- }+ },+ "usage_total_tooltip": "この課題のトークン使用量 — クリックで実行ごとの内訳"+ },+ "usage_detail": {+ "title": "使用量の内訳",+ "subtitle_other": "{{identifier}} · {{count}} 回の実行",+ "empty": "この課題では、まだトークン使用量が記録された実行はありません。",+ "kpi_cost": "費用",+ "kpi_cost_hint_other": "失敗した {{count}} 回の実行が {{pct}}% を占めます",+ "kpi_cache": "キャッシュ削減",+ "kpi_cache_hint": "ヒット率 {{pct}}% · 読み取り {{reads}}",+ "kpi_tokens": "トークン",+ "kpi_tokens_hint": "入力 {{input}} · 出力 {{output}}",+ "by_agent": "エージェント別",+ "by_agent_total": "合計 {{cost}}",+ "col_run": "実行",+ "col_model": "モデル",+ "col_duration": "所要時間",+ "col_input": "入力",+ "col_output": "出力",+ "col_cache_read": "キャッシュ読",+ "col_cache_write": "キャッシュ書",+ "col_tokens": "トークン",+ "col_cost": "費用",+ "total": "合計",+ "note_unpriced_other": "{{count}} 回の実行は使用量が記録されておらず、合計に含まれません。",+ "note_unmapped": "{{models}} は価格が未登録です。トークンは集計されますが費用は含まれません。",+ "note_estimate": "費用は公開モデル料金からの概算です(プロバイダーが独自の費用を返した分を除く)。"},"terminate_dialog": {"title": "この作業を停止しますか?",diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.jsonindex aadb73e2b0..c59ae578be 100644--- a/packages/views/locales/ko/agents.json+++ b/packages/views/locales/ko/agents.json@@ -703,7 +703,13 @@"copy_workdir": "작업 디렉터리 복사","close": "닫기","fact_created": "생성 {{time}}",- "fact_took": "소요 {{duration}}"+ "fact_took": "소요 {{duration}}",+ "details_input": "입력",+ "details_output": "출력",+ "details_cache_read": "캐시 읽기",+ "details_cache_write": "캐시 쓰기",+ "details_cost": "비용",+ "usage_chip_title": "이 실행의 토큰 및 예상 비용"},"task_failure": {"agent_error": "에이전트 실행 오류",diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.jsonindex c1f8d0ab2f..2772b49854 100644--- a/packages/views/locales/ko/issues.json+++ b/packages/views/locales/ko/issues.json@@ -244,7 +244,6 @@"section_pull_requests": "Pull requests","section_metadata": "메타데이터","section_details": "세부 정보",- "section_token_usage": "토큰 사용량","section_quick_actions": "퀵 액션","quick_actions_more": "{{count}}개 더 보기","quick_action_runs_as": "{{name}}이(가) 실행합니다",@@ -292,11 +291,6 @@"prop_created_by": "생성자","prop_created": "생성일","prop_updated": "수정일",- "prop_input": "입력",- "prop_output": "출력",- "prop_cache": "캐시",- "prop_cache_value": "읽기 {{read}} / 쓰기 {{write}}",- "prop_runs": "실행","activity_section": "활동","subscribe": "구독","unsubscribe": "구독 해제",@@ -520,7 +514,34 @@"source_owner_fallback": "정확한 담당자 없음 — 에이전트 소유자에게 귀속","source_backfill": "백필된 귀속","source_unattributed": "책임 멤버를 확인할 수 없음"- }+ },+ "usage_total_tooltip": "이 이슈의 토큰 사용량 — 클릭하면 실행별 내역"+ },+ "usage_detail": {+ "title": "사용량 내역",+ "subtitle_other": "{{identifier}} · 실행 {{count}}회",+ "empty": "이 이슈에서 토큰 사용량이 기록된 실행이 아직 없습니다.",+ "kpi_cost": "비용",+ "kpi_cost_hint_other": "실패한 실행 {{count}}회가 {{pct}}%를 차지합니다",+ "kpi_cache": "캐시 절감",+ "kpi_cache_hint": "적중률 {{pct}}% · 읽기 {{reads}}",+ "kpi_tokens": "토큰",+ "kpi_tokens_hint": "입력 {{input}} · 출력 {{output}}",+ "by_agent": "에이전트별",+ "by_agent_total": "합계 {{cost}}",+ "col_run": "실행",+ "col_model": "모델",+ "col_duration": "소요 시간",+ "col_input": "입력",+ "col_output": "출력",+ "col_cache_read": "캐시 읽기",+ "col_cache_write": "캐시 쓰기",+ "col_tokens": "토큰",+ "col_cost": "비용",+ "total": "합계",+ "note_unpriced_other": "실행 {{count}}회는 사용량 기록이 없어 합계에 포함되지 않습니다.",+ "note_unmapped": "{{models}}의 가격 정보가 없어 토큰은 집계되지만 비용은 포함되지 않습니다.",+ "note_estimate": "비용은 공개된 모델 요금 기준 추정치이며, 제공자가 자체 비용을 보고한 경우는 그 값을 사용합니다."},"terminate_dialog": {"title": "이 작업을 중지할까요?",diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.jsonindex bab10abb9e..7fd39199b7 100644--- a/packages/views/locales/zh-Hans/agents.json+++ b/packages/views/locales/zh-Hans/agents.json@@ -802,7 +802,13 @@"copy_workdir": "复制工作目录","close": "关闭","fact_created": "创建于 {{time}}",- "fact_took": "用时 {{duration}}"+ "fact_took": "用时 {{duration}}",+ "details_input": "输入",+ "details_output": "输出",+ "details_cache_read": "缓存读",+ "details_cache_write": "缓存写",+ "details_cost": "费用",+ "usage_chip_title": "这次运行消耗的 token 与估算费用"},"task_failure": {"agent_error": "智能体执行出错",diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.jsonindex 292eb24a59..aa3f3f059d 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -244,7 +244,6 @@"section_pull_requests": "Pull Request","section_metadata": "元数据","section_details": "详情",- "section_token_usage": "Token 用量","section_quick_actions": "快捷操作","quick_actions_more": "显示其余 {{count}} 条","quick_action_runs_as": "由 {{name}} 执行",@@ -292,11 +291,6 @@"prop_created_by": "创建者","prop_created": "创建时间","prop_updated": "更新时间",- "prop_input": "输入",- "prop_output": "输出",- "prop_cache": "缓存",- "prop_cache_value": "{{read}} 读 / {{write}} 写",- "prop_runs": "运行次数","activity_section": "动态","subscribe": "订阅","unsubscribe": "取消订阅",@@ -520,7 +514,34 @@"source_owner_fallback": "无精确责任人 —— 归到 agent 所有者","source_backfill": "回填的归因","source_unattributed": "未解析到责任成员"- }+ },+ "usage_total_tooltip": "这个任务的 token 用量——点击查看每次运行的明细"+ },+ "usage_detail": {+ "title": "用量明细",+ "subtitle_other": "{{identifier}} · {{count}} 次运行",+ "empty": "这个任务还没有任何一次运行记录到 token 用量。",+ "kpi_cost": "费用",+ "kpi_cost_hint_other": "{{count}} 次失败运行占 {{pct}}%",+ "kpi_cache": "缓存节省",+ "kpi_cache_hint": "命中率 {{pct}}% · 读取 {{reads}}",+ "kpi_tokens": "Token",+ "kpi_tokens_hint": "输入 {{input}} · 输出 {{output}}",+ "by_agent": "按智能体分摊",+ "by_agent_total": "合计 {{cost}}",+ "col_run": "运行",+ "col_model": "模型",+ "col_duration": "时长",+ "col_input": "输入",+ "col_output": "输出",+ "col_cache_read": "缓存读",+ "col_cache_write": "缓存写",+ "col_tokens": "Token",+ "col_cost": "费用",+ "total": "合计",+ "note_unpriced_other": "有 {{count}} 次运行没有用量记录,不计入合计。",+ "note_unmapped": "{{models}} 没有维护价格,token 已计入,费用未计入。",+ "note_estimate": "费用按各模型公开价目估算;供应商回报实际费用时以回报值为准。"},"terminate_dialog": {"title": "确定停止该 task?",diff --git a/packages/views/runtimes/components/charts/activity-heatmap.tsx b/packages/views/runtimes/components/charts/activity-heatmap.tsxindex d9e6867cf8..69b6a4243e 100644--- a/packages/views/runtimes/components/charts/activity-heatmap.tsx+++ b/packages/views/runtimes/components/charts/activity-heatmap.tsx@@ -1,7 +1,7 @@import { useMemo } from "react";import type { RuntimeUsage } from "@multica/core/types";import { useCustomPricingStore } from "@multica/core/runtimes/custom-pricing-store";-import { addDaysIso, estimateCost, todayIso, weekStartIso } from "../../utils";+import { addDaysIso, estimateCost, formatUsd, todayIso, weekStartIso } from "../../utils";import { useT } from "../../../i18n";// 26 weeks (~6 months) gives the heatmap real presence in the wider chart@@ -28,11 +28,6 @@ function getHeatmapColor(level: number): string {return `color-mix(in oklch, var(--color-chart-1) ${opacities[level - 1]}, transparent)`;}-function fmtMoney(n: number): string {- if (n >= 100) return `$${n.toFixed(0)}`;- return `$${n.toFixed(2)}`;-}-function fmtDate(iso: string): string {return new Date(iso + "T00:00:00").toLocaleString("en", {month: "short",@@ -284,19 +279,19 @@ function InsightsRow({ insights }: { insights: Insights }) {<Insightlabel="Busiest day"value={busiestDay ? fmtDate(busiestDay.date) : "—"}- sub={busiestDay ? fmtMoney(busiestDay.cost) : null}+ sub={busiestDay ? formatUsd(busiestDay.cost) : null}/><Insightlabel="Most active weekday"value={busyDayName ?? "—"}- sub={busyDayName ? `avg ${fmtMoney(busyDayAvg)}` : null}+ sub={busyDayName ? `avg ${formatUsd(busyDayAvg)}` : null}/><Insightlabel="Quietest weekday"value={quietDayName ?? "—"}- sub={quietDayName ? `avg ${fmtMoney(quietDayAvg)}` : null}+ sub={quietDayName ? `avg ${formatUsd(quietDayAvg)}` : null}/>- <Insight label={`${windowDays}-day total`} value={fmtMoney(totalCost)} />+ <Insight label={`${windowDays}-day total`} value={formatUsd(totalCost)} /></dl>);}diff --git a/packages/views/runtimes/components/usage-section.tsx b/packages/views/runtimes/components/usage-section.tsxindex adc56f1c1a..bb1e4c783d 100644--- a/packages/views/runtimes/components/usage-section.tsx+++ b/packages/views/runtimes/components/usage-section.tsx@@ -21,6 +21,7 @@ import { useCustomPricingStore } from "@multica/core/runtimes/custom-pricing-stoimport { useViewingTimezone } from "../../common/use-viewing-timezone";import {formatTokens,+ formatUsd,estimateCost,estimateCacheSavings,aggregateByDate,@@ -116,11 +117,6 @@ function Segmented<T extends string | number>({);}-function fmtMoney(n: number): string {- if (n >= 100) return `$${n.toFixed(0)}`;- return `$${n.toFixed(2)}`;-}-// ---------------------------------------------------------------------------// Top-level orchestrator. Owns the time window, fetches a 180-day usage// cache once, slices it into "current" / "prior" windows for delta math,@@ -235,7 +231,7 @@ export function UsageSection({ runtime }: { runtime: AgentRuntime }) {<CurrencyNumberFlowvalue={totals.cost}locales={locales}- aria-label={fmtMoney(totals.cost)}+ aria-label={formatUsd(totals.cost)}/>}hint={@@ -263,7 +259,7 @@ export function UsageSection({ runtime }: { runtime: AgentRuntime }) {<CurrencyNumberFlowvalue={totals.cacheSavings}locales={locales}- aria-label={fmtMoney(totals.cacheSavings)}+ aria-label={formatUsd(totals.cacheSavings)}/>}accent={totals.cacheSavings > 0 ? "success" : "default"}diff --git a/packages/views/runtimes/utils.test.ts b/packages/views/runtimes/utils.test.tsindex e9e9a979b2..9e98fbdf14 100644--- a/packages/views/runtimes/utils.test.ts+++ b/packages/views/runtimes/utils.test.ts@@ -13,6 +13,8 @@ import {isModelPriced,isSelfHealingRuntime,sliceWindow,+ summarizeTaskUsage,+ summarizeTaskUsageAcross,todayIso,weekStartIso,} from "./utils";@@ -1307,3 +1309,87 @@ describe("computeCostInWindow", () => {expect(computeCostInWindow([], 7, "UTC")).toBe(0);});});++describe("summarizeTaskUsage", () => {+ // claude-opus-5: 5 / 25 / 0.50 / 6.25 per million.+ const opus = {+ provider: "anthropic",+ model: "claude-opus-5",+ input_tokens: 96_000,+ output_tokens: 34_000,+ cache_read_tokens: 712_000,+ cache_write_tokens: 50_000,+ };+ // gpt-5.6-terra: 2.50 / 15 / 0.25 / 3.125 per million.+ const terra = {+ provider: "openai",+ model: "gpt-5.6-terra",+ input_tokens: 31_000,+ output_tokens: 12_000,+ cache_read_tokens: 158_000,+ cache_write_tokens: 11_000,+ };++ it("sums every token bucket into the headline figure", () => {+ const s = summarizeTaskUsage([opus]);+ expect(s?.tokens).toBe(96_000 + 34_000 + 712_000 + 50_000);+ expect(s?.input).toBe(96_000);+ expect(s?.cacheWrite).toBe(50_000);+ expect(s?.models).toEqual(["claude-opus-5"]);+ });++ it("prices each model slice at its own rate, not the combined total", () => {+ // Priced separately: 1.9985 (opus) + 0.331375 (terra).+ // Priced as one blob at either rate, the answer would be wrong.+ const s = summarizeTaskUsage([opus, terra]);+ expect(s?.cost).toBeCloseTo(1.9985 + 0.331375, 5);+ expect(s?.models).toEqual(["claude-opus-5", "gpt-5.6-terra"]);+ });++ it("prefers the provider's own cost over the rate table", () => {+ // 3e10 ticks = $3.00, well above what the rate table would charge, so a+ // rate-table result would be visibly different.+ const s = summarizeTaskUsage([{ ...opus, cost_usd_ticks: 30_000_000_000 }]);+ expect(s?.cost).toBeCloseTo(3, 5);+ });++ it("returns null for no usage rather than a zeroed summary", () => {+ // Both must be null: a run with no recorded usage was not free, and a+ // 0 here would render as "$0.00" and assert that it was.+ expect(summarizeTaskUsage(undefined)).toBeNull();+ expect(summarizeTaskUsage([])).toBeNull();+ });++ it("counts tokens for an unpriced model but leaves its cost at 0", () => {+ const s = summarizeTaskUsage([{ ...opus, model: "totally-made-up-model" }]);+ expect(s?.tokens).toBe(892_000);+ expect(s?.cost).toBe(0);+ });++ it("reports cache savings against full input pricing", () => {+ // 712K cache reads at opus: would have cost 5/M, actually cost 0.50/M.+ const s = summarizeTaskUsage([opus]);+ expect(s?.cacheSavings).toBeCloseTo((712_000 * (5 - 0.5)) / 1_000_000, 5);+ });+});++describe("summarizeTaskUsageAcross", () => {+ const slice = {+ model: "claude-opus-5",+ input_tokens: 1_000_000,+ output_tokens: 0,+ cache_read_tokens: 0,+ cache_write_tokens: 0,+ };++ it("skips runs with no usage instead of nulling the whole total", () => {+ const total = summarizeTaskUsageAcross([[slice], undefined, [], [slice]]);+ expect(total?.tokens).toBe(2_000_000);+ expect(total?.cost).toBeCloseTo(10, 5);+ });++ it("is null only when no run has any usage", () => {+ expect(summarizeTaskUsageAcross([undefined, [], undefined])).toBeNull();+ expect(summarizeTaskUsageAcross([])).toBeNull();+ });+});diff --git a/packages/views/runtimes/utils.ts b/packages/views/runtimes/utils.tsindex 3529fd1be8..be6444ca11 100644--- a/packages/views/runtimes/utils.ts+++ b/packages/views/runtimes/utils.ts@@ -119,6 +119,13 @@ export function formatTokens(n: number): string {return n.toLocaleString();}+// Cents below $100, whole dollars above — two decimals on a four-figure spend+// is noise, and dropping them below $100 would round most single runs to $0.+export function formatUsd(n: number): string {+ if (n >= 100) return `$${n.toFixed(0)}`;+ return `$${n.toFixed(2)}`;+}+// ---------------------------------------------------------------------------// Cost estimation// ---------------------------------------------------------------------------@@ -502,7 +509,7 @@ export function collectUnmappedModels(rows: readonly Priceable[]): string[] {// test fixtures) still type-check; when present it disambiguates generic// model ids during pricing. RuntimeUsage / RuntimeUsageByAgent /// DashboardUsageDaily / DashboardUsageByAgent all carry it on the wire.-type Priceable = Pick<+export type Priceable = Pick<RuntimeUsage,| "model"| "input_tokens"@@ -649,6 +656,75 @@ export function estimateCostBreakdown(usage: Priceable): CostBreakdown {};}+// ---------------------------------------------------------------------------+// Per-run usage+// ---------------------------------------------------------------------------++/** Collapsed usage for one agent run, or for a set of runs. */+export interface TaskUsageSummary {+ /** input + output + cacheRead + cacheWrite, matching the usage page's headline. */+ tokens: number;+ cost: number;+ cacheSavings: number;+ input: number;+ output: number;+ cacheRead: number;+ cacheWrite: number;+ /** Distinct models this run touched, in first-seen order. Usually one. */+ models: string[];+}++/**+ * Collapse a run's per-model usage slices into one summary.+ *+ * Cost is summed per slice rather than computed from the totals, because each+ * slice may be priced by a different rate — a run that spilled from Sonnet to+ * Opus has two rows and pricing their sum at either rate would be wrong. This+ * is the same reason the wire format keeps the model dimension at all.+ *+ * Returns `null` for both `undefined` and `[]`: neither means "this run was+ * free", they mean "we have no figure", and the UI must render an em dash. A+ * caller that summed to 0 instead would silently claim a run cost nothing.+ */+export function summarizeTaskUsage(+ usage: readonly Priceable[] | undefined,+): TaskUsageSummary | null {+ if (!usage || usage.length === 0) return null;++ const models: string[] = [];+ const summary: TaskUsageSummary = {+ tokens: 0, cost: 0, cacheSavings: 0,+ input: 0, output: 0, cacheRead: 0, cacheWrite: 0,+ models,+ };++ for (const slice of usage) {+ summary.input += slice.input_tokens;+ summary.output += slice.output_tokens;+ summary.cacheRead += slice.cache_read_tokens;+ summary.cacheWrite += slice.cache_write_tokens;+ summary.cost += estimateCost(slice);+ summary.cacheSavings += estimateCacheSavings(slice);+ if (slice.model && !models.includes(slice.model)) models.push(slice.model);+ }+ summary.tokens =+ summary.input + summary.output + summary.cacheRead + summary.cacheWrite;++ return summary;+}++/**+ * Sum many runs' usage into one figure — the issue-level total shown on the+ * execution-log header. Runs with no recorded usage contribute nothing and do+ * not make the total null; the total is null only when NO run has usage, i.e.+ * when there is genuinely nothing to show.+ */+export function summarizeTaskUsageAcross(+ runs: readonly (readonly Priceable[] | undefined)[],+): TaskUsageSummary | null {+ return summarizeTaskUsage(runs.flatMap((u) => u ?? []));+}+// Cache savings: what cache *reads* would have cost at full input pricing// minus what they actually cost at the discounted cache-hit rate. This is a// reconstruction of "money the cache saved you", not real-world spend.diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex ee2541a649..36026dbd38 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -398,6 +398,17 @@ type AgentTaskResponse struct {// pure taskToResponse builds the labels + raw ids); initiator/originator names// are hydrated from the global user table only on user-facing surfaces.Attribution *TaskAttribution `json:"attribution,omitempty"`+ // Usage is this run's own token consumption, one entry per (provider, model)+ // it used — the same grain `task_usage` stores and the same grain the client+ // prices at. Hydrated only on the issue-facing execution-log endpoint+ // (ListTasksByIssue); the daemon claim path leaves it nil so the claim+ // payload does not carry accounting the agent has no use for.+ //+ // nil and [] are both "no usage recorded" and the UI renders an em dash for+ // them — a run that predates usage reporting, or one that died before any+ // model call, genuinely has no number, and showing 0 would assert it was+ // free. omitempty keeps both off the wire.+ Usage []TaskUsageData `json:"usage,omitempty"`// AuthToken is the task-scoped `mat_` token the daemon must inject as// MULTICA_TOKEN in the agent process environment. The server binds it to// this (agent_id, task_id) pair at claim time and treats any request@@ -576,6 +587,26 @@ type CoalescedCommentData struct {CreatedAt string `json:"created_at,omitempty"`}+// TaskUsageData is one (provider, model) slice of a single run's token usage.+// Field names match the runtime/dashboard usage rows exactly so the client can+// feed it to the same `estimateCost` / `estimateCacheSavings` helpers without+// an adapter.+//+// CostUsdTicks is the provider's own price for these tokens (1e-10 USD) and is+// nil when the provider reported none — the client then estimates that slice+// from its rate table. A pointer, not a zero value: 0 ticks is a real answer+// ("the provider says this was free") and must stay distinguishable from+// "the provider said nothing".+type TaskUsageData struct {+ Provider string `json:"provider,omitempty"`+ Model string `json:"model"`+ InputTokens int64 `json:"input_tokens"`+ OutputTokens int64 `json:"output_tokens"`+ CacheReadTokens int64 `json:"cache_read_tokens"`+ CacheWriteTokens int64 `json:"cache_write_tokens"`+ CostUsdTicks *int64 `json:"cost_usd_ticks,omitempty"`+}+// TaskAgentData holds agent info included in claim responses so the daemon// can set up the execution environment (branch naming, skill files, instructions).type TaskAgentData struct {diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 84f4721395..d08238222d 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -3961,10 +3961,54 @@ func (h *Handler) ListTasksByIssue(w http.ResponseWriter, r *http.Request) {// issue-facing surface must resolve initiator/originator names (departed-safe,// one batch) — otherwise the badge falls back to "someone" on issue detail.h.hydrateTaskAttributions(r.Context(), attributionsOf(resp))+ h.hydrateTaskUsage(r.Context(), issue.ID, resp)writeJSON(w, http.StatusOK, resp)}+// hydrateTaskUsage attaches each run's own token usage to the execution-log+// rows. One query for the whole issue, then a map join — not one query per+// task, which would be an N+1 over a list the UI always renders in full.+//+// Usage is display metadata: a failure here must not take the execution log+// down with it, so the error is swallowed and every row keeps its nil Usage,+// which the UI already renders as "no usage recorded".+func (h *Handler) hydrateTaskUsage(ctx context.Context, issueID pgtype.UUID, resp []AgentTaskResponse) {+ if len(resp) == 0 {+ return+ }++ rows, err := h.Queries.ListIssueTaskUsage(ctx, issueID)+ if err != nil || len(rows) == 0 {+ return+ }++ byTask := make(map[string][]TaskUsageData, len(resp))+ for _, row := range rows {+ var cost *int64+ if row.CostUsdTicks.Valid {+ v := row.CostUsdTicks.Int64+ cost = &v+ }+ taskID := uuidToString(row.TaskID)+ byTask[taskID] = append(byTask[taskID], TaskUsageData{+ Provider: row.Provider,+ Model: row.Model,+ InputTokens: row.InputTokens,+ OutputTokens: row.OutputTokens,+ CacheReadTokens: row.CacheReadTokens,+ CacheWriteTokens: row.CacheWriteTokens,+ CostUsdTicks: cost,+ })+ }++ for i := range resp {+ if usage, ok := byTask[resp[i].ID]; ok {+ resp[i].Usage = usage+ }+ }+}+// ListTaskMessagesByUser returns task messages for a task.// Used by the frontend under regular user auth (not daemon auth).// Verifies the task belongs to the caller's workspace.diff --git a/server/internal/handler/task_usage_response_test.go b/server/internal/handler/task_usage_response_test.gonew file mode 100644index 0000000000..40cc3475ce--- /dev/null+++ b/server/internal/handler/task_usage_response_test.go@@ -0,0 +1,144 @@+package handler++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"+)++// TestListTasksByIssueHydratesUsage guards the per-run token figure on the+// execution log: the sidebar row, its header total, and the usage dialog all+// read `usage` off this endpoint, so a task that recorded usage must come back+// carrying it — at the (provider, model) grain, because cost is priced+// per-model on the client and a collapsed row cannot be priced at all.+//+// It also pins the distinction the whole feature rests on: a run with no+// recorded usage returns NO usage field, not a zeroed one. The UI renders the+// former as an em dash and the latter as "0 tokens / $0.00", and a run from+// before usage reporting was not free.+func TestListTasksByIssueHydratesUsage(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ agentID := createHandlerTestAgent(t, "UsageListAgent", []byte("[]"))++ var issueID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)+ VALUES ($1, 'usage-list-issue', 'todo', 'medium', $2, 'member', 92778, 0)+ RETURNING id+ `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {+ t.Fatalf("create issue: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID) })++ newTask := func(status string) string {+ var id string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, issue_id)+ VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), $2, 0, $3)+ RETURNING id+ `, agentID, status, issueID).Scan(&id); err != nil {+ t.Fatalf("create task: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, id) })+ return id+ }++ // A run that spilled across two models — the case the per-model grain+ // exists for.+ pricedTask := newTask("completed")+ // A run that predates usage reporting.+ unpricedTask := newTask("completed")++ if _, err := testPool.Exec(ctx, `+ INSERT INTO task_usage (task_id, provider, model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, cost_usd_ticks)+ VALUES ($1, 'anthropic', 'claude-opus-5', 96000, 34000, 712000, 50000, NULL),+ ($1, 'openai', 'gpt-5.6-terra', 31000, 12000, 158000, 11000, 3310000000)+ `, pricedTask); err != nil {+ t.Fatalf("insert task usage: %v", err)+ }++ req := newRequest("GET", "/api/issues/"+issueID+"/task-runs", nil)+ req = withURLParam(req, "id", issueID)+ w := httptest.NewRecorder()+ testHandler.ListTasksByIssue(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }++ var resp []AgentTaskResponse+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode task list: %v", err)+ }++ byID := make(map[string]AgentTaskResponse, len(resp))+ for _, task := range resp {+ byID[task.ID] = task+ }++ priced, ok := byID[pricedTask]+ if !ok {+ t.Fatalf("priced task %s missing from response: %s", pricedTask, w.Body.String())+ }+ if len(priced.Usage) != 2 {+ t.Fatalf("usage rows = %d, want 2 (one per model): %+v", len(priced.Usage), priced.Usage)+ }++ byModel := make(map[string]TaskUsageData, len(priced.Usage))+ for _, u := range priced.Usage {+ byModel[u.Model] = u+ }++ opus, ok := byModel["claude-opus-5"]+ if !ok {+ t.Fatalf("claude-opus-5 row missing: %+v", priced.Usage)+ }+ if opus.Provider != "anthropic" {+ t.Errorf("opus provider = %q, want anthropic", opus.Provider)+ }+ if opus.InputTokens != 96000 || opus.OutputTokens != 34000 ||+ opus.CacheReadTokens != 712000 || opus.CacheWriteTokens != 50000 {+ t.Errorf("opus token counts = %+v, want 96000/34000/712000/50000", opus)+ }+ // The provider reported no cost for this row, so the client must estimate+ // it — a 0 here would tell the client the provider said "free".+ if opus.CostUsdTicks != nil {+ t.Errorf("opus cost_usd_ticks = %d, want nil (provider reported none)", *opus.CostUsdTicks)+ }++ terra, ok := byModel["gpt-5.6-terra"]+ if !ok {+ t.Fatalf("gpt-5.6-terra row missing: %+v", priced.Usage)+ }+ if terra.CostUsdTicks == nil || *terra.CostUsdTicks != 3310000000 {+ t.Errorf("terra cost_usd_ticks = %v, want 3310000000", terra.CostUsdTicks)+ }++ unpriced, ok := byID[unpricedTask]+ if !ok {+ t.Fatalf("unpriced task %s missing from response", unpricedTask)+ }+ if len(unpriced.Usage) != 0 {+ t.Errorf("task with no recorded usage carries %d usage rows, want none: %+v",+ len(unpriced.Usage), unpriced.Usage)+ }+ // omitempty must keep the key off the wire entirely, so the client sees+ // `undefined` rather than an empty array it might read as "hydrated, zero".+ var raw []map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &raw); err != nil {+ t.Fatalf("decode raw task list: %v", err)+ }+ for _, task := range raw {+ if task["id"] != unpricedTask {+ continue+ }+ if _, present := task["usage"]; present {+ t.Errorf("unpriced task serialises a `usage` key; want it omitted: %v", task["usage"])+ }+ }+}diff --git a/server/pkg/db/generated/task_usage.sql.go b/server/pkg/db/generated/task_usage.sql.goindex 7636ff6946..9295a8af97 100644--- a/server/pkg/db/generated/task_usage.sql.go+++ b/server/pkg/db/generated/task_usage.sql.go@@ -581,6 +581,74 @@ func (q *Queries) ListDashboardUsageDaily(ctx context.Context, arg ListDashboardreturn items, nil}+const listIssueTaskUsage = `-- name: ListIssueTaskUsage :many+SELECT+ tu.task_id,+ tu.provider,+ tu.model,+ tu.input_tokens,+ tu.output_tokens,+ tu.cache_read_tokens,+ tu.cache_write_tokens,+ tu.cost_usd_ticks+FROM task_usage tu+JOIN agent_task_queue atq ON atq.id = tu.task_id+WHERE atq.issue_id = $1+ORDER BY tu.task_id, tu.model+`++type ListIssueTaskUsageRow struct {+ TaskID pgtype.UUID `json:"task_id"`+ Provider string `json:"provider"`+ Model string `json:"model"`+ InputTokens int64 `json:"input_tokens"`+ OutputTokens int64 `json:"output_tokens"`+ CacheReadTokens int64 `json:"cache_read_tokens"`+ CacheWriteTokens int64 `json:"cache_write_tokens"`+ CostUsdTicks pgtype.Int8 `json:"cost_usd_ticks"`+}++// Per-(task, provider, model) usage rows for every task on one issue — the+// per-run half of GetIssueUsageSummary's issue-wide total.+//+// The model dimension stays on the wire for the same reason the runtime and+// dashboard usage rows keep it: cost is priced client-side from a per-model+// rate table, and a row that has collapsed two models into one sum can no+// longer be priced at all. The execution log sums the rows per task; the usage+// panel shows them split.+//+// Ordering is by task then model so the client can group by task_id in one+// pass. Uses idx_agent_task_queue_issue_id (migration 035) + the task_usage+// task_id index (migration 032).+func (q *Queries) ListIssueTaskUsage(ctx context.Context, issueID pgtype.UUID) ([]ListIssueTaskUsageRow, error) {+ rows, err := q.db.Query(ctx, listIssueTaskUsage, issueID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListIssueTaskUsageRow{}+ for rows.Next() {+ var i ListIssueTaskUsageRow+ if err := rows.Scan(+ &i.TaskID,+ &i.Provider,+ &i.Model,+ &i.InputTokens,+ &i.OutputTokens,+ &i.CacheReadTokens,+ &i.CacheWriteTokens,+ &i.CostUsdTicks,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const upsertTaskUsage = `-- name: UpsertTaskUsage :execINSERT INTO task_usage (task_id, provider, model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, cost_usd_ticks, updated_at)VALUES ($1, $2, $3, $4, $5, $6, $7, $8, now())diff --git a/server/pkg/db/queries/task_usage.sql b/server/pkg/db/queries/task_usage.sqlindex 2d1531e044..b2bbaa076b 100644--- a/server/pkg/db/queries/task_usage.sql+++ b/server/pkg/db/queries/task_usage.sql@@ -22,6 +22,33 @@ SELECT * FROM task_usageWHERE task_id = $1ORDER BY model;+-- name: ListIssueTaskUsage :many+-- Per-(task, provider, model) usage rows for every task on one issue — the+-- per-run half of GetIssueUsageSummary's issue-wide total.+--+-- The model dimension stays on the wire for the same reason the runtime and+-- dashboard usage rows keep it: cost is priced client-side from a per-model+-- rate table, and a row that has collapsed two models into one sum can no+-- longer be priced at all. The execution log sums the rows per task; the usage+-- panel shows them split.+--+-- Ordering is by task then model so the client can group by task_id in one+-- pass. Uses idx_agent_task_queue_issue_id (migration 035) + the task_usage+-- task_id index (migration 032).+SELECT+ tu.task_id,+ tu.provider,+ tu.model,+ tu.input_tokens,+ tu.output_tokens,+ tu.cache_read_tokens,+ tu.cache_write_tokens,+ tu.cost_usd_ticks+FROM task_usage tu+JOIN agent_task_queue atq ON atq.id = tu.task_id+WHERE atq.issue_id = $1+ORDER BY tu.task_id, tu.model;+-- name: GetIssueUsageSummary :oneSELECTCOALESCE(SUM(tu.input_tokens), 0)::bigint AS total_input_tokens,