Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-8046: feat(issues): per-run cost bars and token detail in the run log (#9288)

Jiayuan Zhange6031902e686
diff --git a/packages/views/issues/components/execution-log-section.test.tsx b/packages/views/issues/components/execution-log-section.test.tsx
index 19153506ea..c6ee0299e3 100644
--- a/packages/views/issues/components/execution-log-section.test.tsx
+++ b/packages/views/issues/components/execution-log-section.test.tsx
@@ -439,41 +439,57 @@ describe("execution log past runs", () => {
expect(screen.getByText("MUL-1 · Wakeups")).toBeInTheDocument();
});
- it("shows each past run's cost, not its token count", () => {
+ it("shows each past run's cost, and who ran it with what on a second line", () => {
renderSection([past(1)]);
- const row = screen.getByText("Past run 1").closest("div")!;
+ const row = screen.getByText("Past run 1").closest("[title]") as HTMLElement;
expect(within(row).getByText("$2.00")).toBeInTheDocument();
- expect(within(row).queryByText("892K")).not.toBeInTheDocument();
+ expect(row).toHaveTextContent("Lambda · 10m · 892K tokens · Opus 5");
+ // The exact model id stays one hover away.
+ expect(row.getAttribute("title")).toContain("claude-opus-5");
});
- it("draws the spend sparkline over a track of every run and sums the agent time", () => {
+ it("puts a failed run's reason where its duration would be", () => {
+ renderSection([past(1, { status: "failed", failure_reason: "agent_error.provider_quota_limit" })]);
+
+ const row = screen.getByText("Past run 1").closest("[title]") as HTMLElement;
+ expect(row).toHaveTextContent("Lambda · Provider quota exhausted · 892K tokens");
+ expect(row).not.toHaveTextContent("10m");
+ });
+
+ it("totals the spend, tokens and agent time", () => {
renderSection([past(1), past(2), past(3, { status: "failed", usage: [] })]);
- const chart = screen.getByRole("button", {
- name: "Cumulative cost over time — open the run timeline",
- });
- expect(chart.querySelectorAll("[data-run]")).toHaveLength(3);
- expect(screen.getByText(/30m agent time/)).toBeInTheDocument();
+ const term = (label: string) => screen.getByText(label, { selector: "dt" }).parentElement!;
+ expect(term("Spent")).toHaveTextContent("$4.00");
+ expect(term("Tokens")).toHaveTextContent("1.8M");
+ expect(term("Agent time")).toHaveTextContent("30m");
+ });
+
+ it("draws one bar per run and opens the Runs dialog from it", () => {
+ renderSection([past(1), past(2), past(3, { status: "failed", usage: [] })]);
+
+ const bars = screen.getByRole("button", { name: "Cost per run — open the run timeline" });
+ expect(Array.from(bars.querySelectorAll("[data-run]"), (el) => el.getAttribute("data-run"))).toEqual([
+ "past-1",
+ "past-2",
+ "past-3",
+ ]);
+ // The run without usage is a stub, not a bar sized like a cheap run.
+ expect((bars.querySelector('[data-run="past-3"]') as HTMLElement).className).toContain("bg-destructive");
- fireEvent.click(chart);
+ fireEvent.click(bars);
expect(screen.getByRole("heading", { name: "Runs" })).toBeInTheDocument();
});
- it("draws the sparkline from the first priced run", () => {
- // Review repro (MUL-7780): the old bar strip waited for two runs and then
- // drew them as two 12px bars in the corner of an empty strip.
+ it("draws the bars from the first priced run", () => {
renderSection([past(1)]);
- expect(
- screen.getByRole("button", { name: /Cumulative cost over time/ }),
- ).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: /Cost per run/ })).toBeInTheDocument();
});
- it("skips the sparkline when no run recorded usage — there is no curve to draw", () => {
+ it("skips the bars when no run recorded usage — there is no cost to compare", () => {
renderSection([past(1, { usage: [] }), past(2, { usage: [] })]);
- expect(
- screen.queryByRole("button", { name: /Cumulative cost over time/ }),
- ).not.toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: /Cost per run/ })).not.toBeInTheDocument();
});
});
diff --git a/packages/views/issues/components/execution-log-section.tsx b/packages/views/issues/components/execution-log-section.tsx
index 30d91c6890..b686c7b55a 100644
--- a/packages/views/issues/components/execution-log-section.tsx
+++ b/packages/views/issues/components/execution-log-section.tsx
@@ -1,11 +1,12 @@
"use client";
-import { useEffect, useMemo, useState } from "react";
+import { Fragment, useEffect, useMemo, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { ChevronRight, Loader2, Maximize2, Square } from "lucide-react";
import { toast } from "sonner";
import { api } from "@multica/core/api";
import { issueTasksOptions } from "@multica/core/issues/queries";
+import { useActorName } from "@multica/core/workspace/hooks";
import { useCustomPricingStore } from "@multica/core/runtimes/custom-pricing-store";
import type { AgentTask } from "@multica/core/types";
import { cn } from "@multica/ui/lib/utils";
@@ -29,13 +30,11 @@ import {
summarizeTaskUsageAcross,
} from "../../runtimes/utils";
import { TerminateTaskConfirmDialog } from "./terminate-task-confirm-dialog";
-import { IssueRunsDialog, RunTriggerLabel, runBarTone } from "./issue-runs-dialog";
+import { IssueRunsDialog } from "./issue-runs-dialog";
+import { RunTriggerLabel } from "./run-trigger-label";
import {
buildRunTimeline,
- cumulativeCostAt,
- idleSpanAround,
- runIndexAt,
- stepCurvePath,
+ shortModelName,
type RunTimeline,
type TimelineRun,
} from "./issue-run-timeline";
@@ -45,11 +44,11 @@ import { useStatusLabel, useTriggerText } from "./task-run-labels";
import { WakeupRunLabel } from "./wakeup-source-chip";
// Right-panel section that lists every agent run for this issue. Active
-// runs sit at the top (always visible when present); below them a spend
-// sparkline (the issue's cumulative cost over time, above a track of its runs)
-// and the latest few past runs. The full history lives in the Runs dialog the
-// header total, the sparkline and the "Open timeline" row open — 21 rows do not
-// belong in a 320px column, and the dialog can lay them out in time.
+// runs sit at the top (always visible when present); below them the issue's
+// totals, one cost bar per recent run, and the latest few past runs. The full
+// history lives in the Runs dialog the header total, the bars and the "Open
+// timeline" row open — 21 rows do not belong in a 320px column, and the dialog
+// can lay them out in time.
//
// Replaces:
// - the click-to-expand timeline that used to live inside the in-body live
@@ -137,9 +136,9 @@ export function ExecutionLogSection({ issueId, identifier, issueTitle }: Executi
});
}, [tasks]);
- // Sidebar-only figures: the sparkline and the agent-time line. Priced
- // with the same helpers as the dialog, and re-derived on a saved custom rate
- // for the same reason IssueRunsTotal subscribes.
+ // Sidebar-only figures: the totals and the cost bars. Priced with the same
+ // helpers as the dialog, and re-derived on a saved custom rate for the same
+ // reason IssueRunsTotal subscribes.
const timeline = useMemo(
() => buildRunTimeline(tasks, Date.now()),
// eslint-disable-next-line react-hooks/exhaustive-deps -- `pricings` re-prices on a saved custom rate
@@ -206,18 +205,8 @@ export function ExecutionLogSection({ issueId, identifier, issueTitle }: Executi
<div className="my-1.5 border-t border-border/60" />
)}
- {timeline.pricedCount > 0 && <RunSpendSparkline timeline={timeline} onOpen={openRuns} />}
- {timeline.agentMs > 0 && (
- <p className="truncate px-1 pb-1 text-caption text-muted-foreground">
- {t(($) => $.execution_log.agent_time, {
- duration: formatAgentTime(timeline.agentMs / 1000, "0s"),
- })}
- <span className="text-faint-foreground"> · </span>
- {t(($) => $.execution_log.elapsed, {
- duration: formatAgentTime(timeline.elapsedMs / 1000, "0s"),
- })}
- </p>
- )}
+ {(timeline.pricedCount > 0 || timeline.agentMs > 0) && <RunTotals timeline={timeline} />}
+ {timeline.pricedCount > 0 && <RunCostBars timeline={timeline} onOpen={openRuns} />}
{latest.length > 0 && (
<>
@@ -256,74 +245,91 @@ export function ExecutionLogSection({ issueId, identifier, issueTitle }: Executi
);
}
-// ─── Spend sparkline ───────────────────────────────────────────────────────
-
-const SPARK_HEIGHT = 34;
-// The curve tops out a little below the box, so the dot at its end has room.
-const SPARK_HEADROOM = 0.9;
-// Same idea as the Runs dialog's slop: a run a few seconds long is a 3px
-// sliver here, and the pointer only has to come near it.
-const SPARK_SLOP_PX = 6;
-
-// The Runs dialog's chart in miniature: the issue's cumulative cost as a step
-// curve over a track of its runs, on one time axis. Whatever the run count it
-// spans the column — the one-bar-per-run strip it replaced drew 12px bars from
-// the left, so an issue with three runs showed three bars in a corner of an
-// empty strip (MUL-7780) — and clicking it opens the same chart full size.
-// Hovering works like the dialog: a crosshair that follows the pointer, and a
-// tooltip naming the run under it or, between runs, the quiet stretch and what
-// the issue had spent by then.
-function RunSpendSparkline({ timeline, onOpen }: { timeline: RunTimeline; onOpen: () => void }) {
+// ─── Totals ────────────────────────────────────────────────────────────────
+
+// The issue's spend, tokens and agent time at a glance. "—" for a figure no
+// run reported, never 0.
+function RunTotals({ timeline }: { timeline: RunTimeline }) {
+ const { t } = useT("issues");
+ const priced = timeline.pricedCount > 0;
+ const stats = [
+ [t(($) => $.runs_timeline.stat_spent), priced ? formatUsd(timeline.totalCost) : "—"],
+ [t(($) => $.runs_timeline.stat_tokens), priced ? formatTokens(timeline.tokens.total) : "—"],
+ [t(($) => $.runs_timeline.stat_agent_time), formatAgentTime(timeline.agentMs / 1000, "0s")],
+ ] as const;
+ return (
+ <dl className="grid grid-cols-3 gap-2 px-1 pb-2">
+ {stats.map(([label, value]) => (
+ <div key={label} className="flex min-w-0 flex-col-reverse">
+ <dt className="truncate text-micro text-muted-foreground">{label}</dt>
+ <dd className="truncate text-label font-medium tabular-nums">{value}</dd>
+ </div>
+ ))}
+ </dl>
+ );
+}
+
+// ─── Cost bars ─────────────────────────────────────────────────────────────
+
+// How many runs the strip holds. A short history leaves the older slots
+// empty, so it sits at the "Now" end instead of stretching two runs into
+// slabs; past the minimum the slots narrow to fit, up to the maximum.
+const MIN_BAR_SLOTS = 20;
+const MAX_BAR_SLOTS = 30;
+const MIN_START_LABEL_RUNS = 6;
+const BAR_HEIGHT = 40;
+// A run that reported no cost still gets a mark, short enough to never read
+// as a cheap run.
+const STUB_HEIGHT = 4;
+
+function costBarTone(run: TimelineRun): string {
+ if (run.active) return "bg-info animate-pulse";
+ if (run.task.status === "failed") return "bg-destructive";
+ if (run.task.status === "cancelled") return "bg-faint-foreground";
+ if (!run.usage) return "border border-b-0 border-dashed border-faint-foreground";
+ return "bg-chart-2";
+}
+
+// One bar per recent run, oldest on the left: height is what the run cost
+// against the most expensive one shown, colour is how it ended. It answers
+// "which run was expensive, and which failed" at a glance; when it happened
+// is the Runs dialog's job, which clicking the strip opens.
+function RunCostBars({ timeline, onOpen }: { timeline: RunTimeline; onOpen: () => void }) {
const { t } = useT("issues");
const locale = useLocale();
- const [hover, setHover] = useState<{ t: number; width: number } | null>(null);
- const [d0, d1] = timeline.domain;
- const [e0, e1] = timeline.extent;
- const xPct = (ms: number) => ((ms - d0) / (d1 - d0)) * 100;
- const yMax = timeline.totalCost / SPARK_HEADROOM;
- const yPct = (cost: number) => (1 - cost / yMax) * 100;
- const { line, area } = stepCurvePath(timeline.cumulative, timeline.domain, yMax);
- const last = timeline.cumulative[timeline.cumulative.length - 1];
+ const [hoverSlot, setHoverSlot] = useState<number | null>(null);
+ const shown = timeline.runs.slice(-MAX_BAR_SLOTS);
+ const slots = Math.max(MIN_BAR_SLOTS, shown.length);
+ const emptySlots = slots - shown.length;
+ const maxCost = Math.max(0, ...shown.map((run) => run.usage?.cost ?? 0));
+ const hovered = hoverSlot != null && hoverSlot >= emptySlots ? shown[hoverSlot - emptySlots] : undefined;
const trackPointer = (event: React.PointerEvent<HTMLElement>) => {
const rect = event.currentTarget.getBoundingClientRect();
if (rect.width <= 0) return;
- const at = d0 + ((event.clientX - rect.left) / rect.width) * (d1 - d0);
- setHover({ t: Math.min(Math.max(at, e0), e1), width: rect.width });
+ const slot = Math.floor(((event.clientX - rect.left) / rect.width) * slots);
+ setHoverSlot(Math.min(Math.max(slot, 0), slots - 1));
};
- const hoverIndex = hover
- ? runIndexAt(timeline.runs, hover.t, (SPARK_SLOP_PX / hover.width) * (d1 - d0))
- : -1;
- const hovered = hoverIndex >= 0 ? timeline.runs[hoverIndex] : undefined;
- // One dot, on whatever the pointer is about: the hovered run's step, the
- // curve under the crosshair between runs, or at rest, where the curve ends.
- const dot = hover
- ? hovered
- ? hovered.usage
- ? { t: hovered.endMs, cost: hovered.costSoFar }
- : null
- : { t: hover.t, cost: cumulativeCostAt(timeline.cumulative, hover.t) }
- : last
- ? { t: last.t, cost: last.cost }
- : null;
-
- // The axis ends: clock times while the whole issue is today's, days once it
- // spans more; "Now" while a run is still going.
+
+ // The axis ends: clock times while every shown run is today's, days once
+ // they span more; "Now" while a run is still going.
+ const first = shown[0]?.startMs ?? 0;
+ const last = shown.reduce((m, run) => Math.max(m, run.endMs), first);
const [startLabel, endLabel] = useMemo(() => {
const today = new Date().toDateString();
const hour = new Intl.DateTimeFormat(locale, { hour: "2-digit", minute: "2-digit", hour12: false });
const day = new Intl.DateTimeFormat(locale, { month: "short", day: "numeric" });
- const allToday = new Date(e0).toDateString() === today;
+ const allToday = new Date(first).toDateString() === today;
const end =
timeline.activeCount > 0
? t(($) => $.execution_log.sparkline_now)
: allToday
- ? hour.format(e1)
- : new Date(e1).toDateString() === today
+ ? hour.format(last)
+ : new Date(last).toDateString() === today
? t(($) => $.runs_timeline.day_today)
- : day.format(e1);
- return [allToday ? hour.format(e0) : day.format(e0), end];
- }, [e0, e1, timeline.activeCount, locale, t]);
+ : day.format(last);
+ return [allToday ? hour.format(first) : day.format(first), end];
+ }, [first, last, timeline.activeCount, locale, t]);
return (
<div className="px-1 pb-1">
@@ -335,83 +341,57 @@ function RunSpendSparkline({ timeline, onOpen }: { timeline: RunTimeline; onOpen
onClick={onOpen}
onPointerMove={trackPointer}
onPointerDown={trackPointer}
- onPointerLeave={() => setHover(null)}
+ onPointerLeave={() => setHoverSlot(null)}
aria-label={t(($) => $.execution_log.strip_aria)}
/>
}
className="relative block w-full rounded-xs text-left"
>
- <span aria-hidden className="relative block" style={{ height: SPARK_HEIGHT }}>
- <svg
- className="absolute inset-0 size-full overflow-visible"
- viewBox="0 0 1000 100"
- preserveAspectRatio="none"
- >
- <path d={area} fill="var(--chart-1)" fillOpacity={0.1} />
- <path
- d={line}
- fill="none"
- stroke="var(--chart-1)"
- strokeWidth={1.5}
- strokeLinejoin="round"
- vectorEffect="non-scaling-stroke"
- />
- </svg>
- {dot && (
- <span
- className="absolute size-1.5 -translate-x-1/2 -translate-y-1/2 rounded-full bg-chart-1 ring-2 ring-background"
- style={{ left: `${xPct(dot.t)}%`, top: `${yPct(dot.cost)}%` }}
- />
- )}
- </span>
- <span aria-hidden className="relative mt-1 block h-2 rounded-full bg-muted">
- {timeline.runs.map((run) => (
- <span
- key={run.task.id}
- data-run={run.task.id}
- className={cn(
- "absolute inset-y-0 min-w-[3px] rounded-full transition-opacity",
- runBarTone(run, run === timeline.peak),
- hovered && run !== hovered && "opacity-35",
- )}
- style={{
- left: `${xPct(run.startMs)}%`,
- width: `${xPct(run.endMs) - xPct(run.startMs)}%`,
- }}
- />
+ <span aria-hidden className="flex items-end gap-0.5" style={{ height: BAR_HEIGHT }}>
+ {Array.from({ length: emptySlots }, (_, i) => (
+ <span key={`empty-${i}`} className="h-0.5 flex-1 rounded-full bg-border" />
))}
+ {shown.map((run) => {
+ const height = run.usage && maxCost > 0
+ ? Math.max(3, (run.usage.cost / maxCost) * BAR_HEIGHT)
+ : STUB_HEIGHT;
+ return (
+ <span
+ key={run.task.id}
+ data-run={run.task.id}
+ className={cn(
+ "flex-1 rounded-t-xs transition-opacity",
+ costBarTone(run),
+ hovered && run !== hovered && "opacity-35",
+ )}
+ style={{ height }}
+ />
+ );
+ })}
</span>
- {hover && (
- <span
- aria-hidden
- className="pointer-events-none absolute top-0 w-px bg-foreground/30"
- style={{ left: `${xPct(hover.t)}%`, height: SPARK_HEIGHT + 12 }}
- />
- )}
- <span aria-hidden className="mt-0.5 flex justify-between text-micro tabular-nums text-muted-foreground">
- <span>{startLabel}</span>
+ <span aria-hidden className="mt-1 flex justify-between text-micro tabular-nums text-muted-foreground">
+ {/* Under the oldest run, not the empty slots before it — and only
+ with runs enough to keep it clear of the end label. */}
+ {shown.length >= MIN_START_LABEL_RUNS ? (
+ <span style={{ marginLeft: `${(emptySlots / slots) * 100}%` }}>{startLabel}</span>
+ ) : (
+ <span />
+ )}
<span>{endLabel}</span>
</span>
</TooltipTrigger>
<TooltipContent className="max-w-64 flex-col items-start gap-0">
- {hovered ? (
- <SparklineRunSummary run={hovered} />
- ) : hover ? (
- <SparklineIdleSummary timeline={timeline} at={hover.t} />
- ) : (
- t(($) => $.execution_log.usage_total_tooltip)
- )}
+ {hovered ? <RunBarSummary run={hovered} /> : t(($) => $.execution_log.usage_total_tooltip)}
</TooltipContent>
</Tooltip>
</div>
);
}
-function SparklineRunSummary({ run }: { run: TimelineRun }) {
+function RunBarSummary({ run }: { run: TimelineRun }) {
const { t } = useT("issues");
const trigger = useTriggerText(run.task);
const status = useStatusLabel(run.task.status);
- const cost = run.usage?.cost;
return (
<>
<RunTriggerLabel task={run.task} fallback={trigger}>
@@ -420,7 +400,10 @@ function SparklineRunSummary({ run }: { run: TimelineRun }) {
<span className="text-micro text-muted-foreground">
{[
// A run still going has not reported usage yet — that is not "none".
- cost != null ? formatUsd(cost) : run.active ? null : t(($) => $.execution_log.strip_no_usage),
+ run.usage ? formatUsd(run.usage.cost) : run.active ? null : t(($) => $.execution_log.strip_no_usage),
+ run.usage
+ ? t(($) => $.runs_timeline.tokens_count, { tokens: formatTokens(run.usage.tokens) })
+ : null,
run.durationMs != null ? formatAgentTime(run.durationMs / 1000, "0s") : null,
run.task.status === "completed" ? null : status,
]
@@ -431,28 +414,6 @@ function SparklineRunSummary({ run }: { run: TimelineRun }) {
);
}
-function SparklineIdleSummary({ timeline, at }: { timeline: RunTimeline; at: number }) {
- const { t } = useT("issues");
- const { fromMs, toMs } = idleSpanAround(timeline.runs, at);
- return (
- <>
- <span>{t(($) => $.runs_timeline.hover_no_run)}</span>
- <span className="text-micro text-muted-foreground">
- {[
- fromMs != null && toMs != null
- ? t(($) => $.runs_timeline.hover_idle, { duration: formatAgentTime((toMs - fromMs) / 1000, "0s") })
- : null,
- t(($) => $.runs_timeline.tooltip_total, {
- cost: formatUsd(cumulativeCostAt(timeline.cumulative, at)),
- }),
- ]
- .filter(Boolean)
- .join(" · ")}
- </span>
- </>
- );
-}
-
// ─── Issue total ───────────────────────────────────────────────────────────
// The issue's run count and whole spend, as a header affordance: "21 runs ·
@@ -682,6 +643,7 @@ export function ActiveTaskRow({
function PastRow({ task, issueId }: { task: AgentTask; issueId: string }) {
const { t } = useT("issues");
const { t: tAgents } = useT("agents");
+ const { getActorName } = useActorName();
const timeAgo = useTimeAgo();
const label = useStatusLabel(task.status);
const trigger = useTriggerText(task);
@@ -705,53 +667,70 @@ function PastRow({ task, issueId }: { task: AgentTask; issueId: string }) {
? [cancellationLabel, failureLabel].filter(Boolean).join(" · ")
: failureLabel ?? label;
- // 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, token count and model — the split lives in the Runs dialog.
+ // What this run cost sits on the first line, beside the trigger people scan
+ // the list for; the second line says who ran it and how — the reason it
+ // stopped, or how long it took, then its tokens and model. The list is
+ // sorted newest-first, so the exact "when" is the detail: it lives in the
+ // row tooltip, with the full model ids.
//
// `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 ? formatTokens(usage.tokens) : "",
- usage?.models.join(", ") ?? "",
- ]
- .filter(Boolean)
- .join(" · ");
+ const reason = cancellationLabel
+ ? [cancellationLabel, failureLabel].filter(Boolean).join(" · ")
+ : failureLabel;
+ const rowTitle = [time, usage?.models.join(", ") ?? ""].filter(Boolean).join(" · ");
+ const meta: { key: string; node: React.ReactNode }[] = [];
+ if (task.agent_id) meta.push({ key: "agent", node: getActorName("agent", task.agent_id) });
+ if (reason) {
+ meta.push({
+ key: "reason",
+ node: <span className={task.status === "failed" ? "text-destructive" : undefined}>{reason}</span>,
+ });
+ } else if (task.started_at && task.completed_at) {
+ const seconds = (new Date(task.completed_at).getTime() - new Date(task.started_at).getTime()) / 1000;
+ meta.push({ key: "duration", node: formatAgentTime(seconds, "0s") });
+ }
+ if (usage) {
+ meta.push({ key: "tokens", node: t(($) => $.runs_timeline.tokens_count, { tokens: formatTokens(usage.tokens) }) });
+ if (usage.models[0]) meta.push({ key: "model", node: shortModelName(usage.models[0]) });
+ }
return (
- <RowShell task={task} title={rowTitle}>
- {task.wakeup_id ? (
- <WakeupRunLabel task={task} fallback={trigger} render={(label) => <TriggerText text={label} />} />
- ) : (
- <TriggerText text={trigger} />
- )}
- <TaskCommentCoverage task={task} />
- <RowStatus title={statusTitle}>
- <TaskStatusIcon status={task.status} />
- <span className="sr-only">
- {[statusTitle, time].filter(Boolean).join(" · ")}
- </span>
- {usage ? (
- <span className="tabular-nums">{formatUsd(usage.cost)}</span>
- ) : (
- <span className="text-faint-foreground">—</span>
+ <RowShell task={task} title={rowTitle} multiline>
+ <div className="min-w-0 flex-1">
+ <div className="flex min-w-0 items-center gap-2">
+ {task.wakeup_id ? (
+ <WakeupRunLabel task={task} fallback={trigger} render={(label) => <TriggerText text={label} emphasis />} />
+ ) : (
+ <TriggerText text={trigger} emphasis />
+ )}
+ <TaskCommentCoverage task={task} />
+ <RowStatus title={statusTitle}>
+ <TaskStatusIcon status={task.status} />
+ <span className="sr-only">{[label, time].filter(Boolean).join(" · ")}</span>
+ {usage ? (
+ <span className="tabular-nums">{formatUsd(usage.cost)}</span>
+ ) : (
+ <span className="text-faint-foreground">—</span>
+ )}
+ </RowStatus>
+ <RowActions>
+ <TranscriptButton task={task} agentName="" title={t(($) => $.execution_log.transcript_tooltip)} />
+ {canRetryRun(task) && <RetryRunButton task={task} issueId={issueId} />}
+ </RowActions>
+ </div>
+ {meta.length > 0 && (
+ <p className="-mt-1 truncate text-micro text-muted-foreground">
+ {meta.map((part, i) => (
+ <Fragment key={part.key}>
+ {i > 0 && <span className="text-faint-foreground"> · </span>}
+ {part.node}
+ </Fragment>
+ ))}
+ </p>
)}
- </RowStatus>
- <RowActions>
- <TranscriptButton task={task} agentName="" title={t(($) => $.execution_log.transcript_tooltip)} />
- {canRetryRun(task) && <RetryRunButton task={task} issueId={issueId} />}
- </RowActions>
+ </div>
</RowShell>
);
}
@@ -761,6 +740,7 @@ function PastRow({ task, issueId }: { task: AgentTask; issueId: string }) {
function RowShell({
task,
title,
+ multiline = false,
children,
}: {
task: AgentTask;
@@ -769,30 +749,41 @@ function RowShell({
* is swapped out for the action buttons on hover — a title there would
* disappear at exactly the moment the pointer arrives. */
title?: string;
+ /** Top-aligns the avatar with the first of several lines. */
+ multiline?: boolean;
children: React.ReactNode;
}) {
return (
<div
title={title || undefined}
- className="group/execution-log-row flex items-center gap-2 overflow-hidden rounded-xs px-1 py-1.5 transition-colors hover:bg-accent/40"
- >
- {task.agent_id ? (
- <ActorAvatar
- actorType="agent"
- actorId={task.agent_id}
- size="sm"
- enableHoverCard
- />
- ) : (
- <span className="inline-block h-5 w-5 shrink-0 rounded-full bg-muted" />
+ className={cn(
+ "group/execution-log-row flex gap-2 overflow-hidden rounded-xs px-1 py-1.5 transition-colors hover:bg-accent/40",
+ multiline ? "items-start" : "items-center",
)}
+ >
+ <span className={cn("flex shrink-0", multiline && "mt-1")}>
+ {task.agent_id ? (
+ <ActorAvatar
+ actorType="agent"
+ actorId={task.agent_id}
+ size="sm"
+ enableHoverCard
+ />
+ ) : (
+ <span className="inline-block h-5 w-5 rounded-full bg-muted" />
+ )}
+ </span>
{children}
</div>
);
}
-function TriggerText({ text }: { text: string }) {
- return <span className="min-w-0 flex-1 truncate text-caption text-muted-foreground">{text}</span>;
+function TriggerText({ text, emphasis = false }: { text: string; emphasis?: boolean }) {
+ return (
+ <span className={cn("min-w-0 flex-1 truncate text-caption", emphasis ? "text-foreground" : "text-muted-foreground")}>
+ {text}
+ </span>
+ );
}
function supportsCommentCoverage(status: AgentTask["status"]): boolean {
diff --git a/packages/views/issues/components/issue-run-timeline.test.ts b/packages/views/issues/components/issue-run-timeline.test.ts
index 5ddf748cc4..1027bb5843 100644
--- a/packages/views/issues/components/issue-run-timeline.test.ts
+++ b/packages/views/issues/components/issue-run-timeline.test.ts
@@ -3,11 +3,13 @@ import { describe, expect, it } from "vitest";
import type { AgentTask, TaskUsage } from "@multica/core/types";
import {
buildRunTimeline,
+ cacheHitRate,
cumulativeCostAt,
groupRunsByDay,
idleSpanAround,
niceTicks,
runIndexAt,
+ shortModelName,
stepCurvePath,
timeTicks,
} from "./issue-run-timeline";
@@ -86,7 +88,6 @@ describe("buildRunTimeline", () => {
expect(timeline.agentMs).toBe(30 * 60 * 1000);
// Elapsed runs from the first start to now, while a run is still going.
expect(timeline.elapsedMs).toBe(NOW - new Date("2026-09-24T10:00:00").getTime());
- expect(timeline.extent).toEqual([new Date("2026-09-24T10:00:00").getTime(), NOW]);
});
it("ignores deferred runs, which the execution log does not list", () => {
@@ -115,6 +116,51 @@ describe("buildRunTimeline", () => {
expect(timeline.maxRunCost).toBe(10);
});
+ it("totals cost, tokens and the priciest run over priced runs only", () => {
+ const timeline = buildRunTimeline(
+ [
+ makeTask({ id: "a", usage: usage(400_000) }),
+ makeTask({ id: "b", started_at: "2026-09-24T11:00:00", completed_at: "2026-09-24T11:30:00", usage: usage(200_000) }),
+ makeTask({ id: "unpriced", started_at: "2026-09-24T13:00:00", completed_at: "2026-09-24T13:05:00" }),
+ ],
+ NOW,
+ );
+
+ expect(timeline.totalCost).toBe(15);
+ expect(timeline.pricedCount).toBe(2);
+ expect(timeline.maxRunCost).toBe(10);
+ expect(timeline.tokens).toEqual({ input: 0, output: 600_000, cacheRead: 0, cacheWrite: 0, total: 600_000 });
+ });
+
+ it("splits the spend by agent and by model, largest first", () => {
+ const timeline = buildRunTimeline(
+ [
+ makeTask({ id: "a", agent_id: "agent-a", usage: usage(200_000) }),
+ makeTask({
+ id: "b",
+ agent_id: "agent-b",
+ started_at: "2026-09-24T11:00:00",
+ usage: [
+ ...usage(400_000),
+ // claude-sonnet-5 at 2 / 10: 2M output = $20.
+ { provider: "anthropic", model: "claude-sonnet-5", input_tokens: 0, output_tokens: 2_000_000, cache_read_tokens: 0, cache_write_tokens: 0 },
+ ],
+ }),
+ ],
+ NOW,
+ );
+
+ expect(timeline.costByAgent).toEqual([
+ { key: "agent-b", cost: 30 },
+ { key: "agent-a", cost: 5 },
+ ]);
+ // A run that used two models counts toward each at its own rate.
+ expect(timeline.costByModel).toEqual([
+ { key: "claude-sonnet-5", cost: 20 },
+ { key: "claude-opus-5", cost: 15 },
+ ]);
+ });
+
it("keeps a run without usage at no figure, not $0", () => {
const timeline = buildRunTimeline([makeTask({ usage: [] })], NOW);
expect(timeline.runs[0]!.usage).toBeNull();
@@ -347,6 +393,16 @@ describe("stepCurvePath", () => {
});
});
+describe("cacheHitRate", () => {
+ it("is the share of prompt tokens served from cache", () => {
+ expect(cacheHitRate({ input: 100, cacheRead: 800, cacheWrite: 100 })).toBe(0.8);
+ });
+
+ it("has no rate without prompt tokens", () => {
+ expect(cacheHitRate({ input: 0, cacheRead: 0, cacheWrite: 0 })).toBeNull();
+ });
+});
+
describe("niceTicks", () => {
it("steps in clean values and tops out at or above the max", () => {
expect(niceTicks(166)).toEqual([50, 100, 150, 200]);
@@ -406,3 +462,17 @@ describe("groupRunsByDay", () => {
expect(groups[1]!.agentMs).toBe(40 * 60 * 1000);
});
});
+
+describe("shortModelName", () => {
+ it("shortens the families it knows", () => {
+ expect(shortModelName("claude-opus-5-5-high")).toBe("Opus 5.5 high");
+ expect(shortModelName("claude-sonnet-4-5-20250929")).toBe("Sonnet 4.5");
+ expect(shortModelName("anthropic/claude-opus-5[1m]")).toBe("Opus 5");
+ expect(shortModelName("gpt-6.1-sol")).toBe("GPT-6.1 Sol");
+ expect(shortModelName("gemini-2.5-pro")).toBe("Gemini 2.5 Pro");
+ });
+
+ it("leaves an unfamiliar id as it is", () => {
+ expect(shortModelName("kimi-k2")).toBe("kimi-k2");
+ });
+});
diff --git a/packages/views/issues/components/issue-run-timeline.ts b/packages/views/issues/components/issue-run-timeline.ts
index 1064161a41..b71e1cab03 100644
--- a/packages/views/issues/components/issue-run-timeline.ts
+++ b/packages/views/issues/components/issue-run-timeline.ts
@@ -1,5 +1,6 @@
import type { AgentTask } from "@multica/core/types";
import {
+ estimateCost,
estimateCostBreakdown,
summarizeTaskUsage,
type CostBreakdown,
@@ -7,10 +8,11 @@ import {
} from "../../runtimes/utils";
import { taskDurationMs } from "./task-run-labels";
-// Pure data for the issue's run timeline: the sidebar's spend strip and the
-// Runs dialog it opens. Everything the two surfaces draw — bar positions, the
-// cumulative cost curve, day groups — is derived here, so the rendering code
-// only maps numbers to pixels and the arithmetic has one place to be tested.
+// Pure data for the issue's run timeline: the sidebar's per-run cost bars and
+// the Runs dialog they open. Everything the two surfaces draw — bar heights,
+// the cumulative cost curve, shares, day groups, totals — is derived here, so the rendering
+// code only maps numbers to pixels and the arithmetic has one place to be
+// tested.
const ACTIVE_STATUSES = new Set<AgentTask["status"]>([
"queued",
@@ -24,9 +26,9 @@ const TERMINAL_STATUSES = new Set<AgentTask["status"]>([
"cancelled",
]);
-// A run has to cost at least this share of the issue before the chart calls it
-// out. Below it no single run explains the curve, and labelling the biggest of
-// many similar steps would point at noise.
+// A run has to cost at least this share of the issue before the cumulative
+// chart calls it out. Below it no single run explains the curve, and labelling
+// the biggest of many similar steps would point at noise.
const PEAK_MIN_SHARE = 0.15;
export interface TimelineRun {
@@ -55,11 +57,28 @@ export interface TimelineLane {
runs: TimelineRun[];
}
+export interface TokenTotals {
+ input: number;
+ output: number;
+ cacheRead: number;
+ cacheWrite: number;
+ total: number;
+}
+
+export interface CostShare {
+ /** An agent id or a model id, depending on the split. */
+ key: string;
+ cost: number;
+}
+
export interface RunTimeline {
/** Oldest first. */
runs: TimelineRun[];
totalCost: number;
pricedCount: number;
+ tokens: TokenTotals;
+ /** What cache reads saved against paying the input rate for them. */
+ cacheSavings: number;
/** Sum of finished runs' wall time. */
agentMs: number;
/** First start to last end (or now, while a run is active). */
@@ -67,15 +86,20 @@ export interface RunTimeline {
failedCount: number;
cancelledCount: number;
activeCount: number;
+ /** The cumulative chart's x axis: the extent, padded. */
domain: [number, number];
/** First start to last end — the stretch of the axis that holds runs. */
extent: [number, number];
/** The running total after each priced run, in completion order. */
cumulative: CumulativeStep[];
- /** One lane per agent, in order of first appearance. */
- lanes: TimelineLane[];
/** The run that moved the total most, when it moved it enough to name. */
peak: TimelineRun | null;
+ /** One lane per agent, in order of first appearance. */
+ lanes: TimelineLane[];
+ /** Spend per agent, most expensive first. */
+ costByAgent: CostShare[];
+ /** Spend per model, most expensive first. */
+ costByModel: CostShare[];
/** Highest single-run cost, for scaling per-run bars. */
maxRunCost: number;
}
@@ -99,6 +123,22 @@ function sumBreakdown(task: AgentTask): CostBreakdown | null {
return total;
}
+function emptyTokens(): TokenTotals {
+ return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 };
+}
+
+function addTokens(into: TokenTotals, usage: TaskUsageSummary): void {
+ into.input += usage.input;
+ into.output += usage.output;
+ into.cacheRead += usage.cacheRead;
+ into.cacheWrite += usage.cacheWrite;
+ into.total += usage.tokens;
+}
+
+function sortedShares(map: Map<string, number>): CostShare[] {
+ return Array.from(map, ([key, cost]) => ({ key, cost })).toSorted((a, b) => b.cost - a.cost);
+}
+
export function toTimelineRun(task: AgentTask, nowMs: number): TimelineRun | null {
const active = ACTIVE_STATUSES.has(task.status);
if (!active && !TERMINAL_STATUSES.has(task.status)) return null;
@@ -130,18 +170,31 @@ export function buildRunTimeline(tasks: readonly AgentTask[], nowMs: number): Ru
let totalCost = 0;
let pricedCount = 0;
+ let cacheSavings = 0;
let agentMs = 0;
let failedCount = 0;
let cancelledCount = 0;
let activeCount = 0;
let maxRunCost = 0;
+ const tokens = emptyTokens();
const laneMap = new Map<string, TimelineRun[]>();
+ const agentCost = new Map<string, number>();
+ const modelCost = new Map<string, number>();
for (const run of runs) {
if (run.usage) {
totalCost += run.usage.cost;
pricedCount += 1;
+ cacheSavings += run.usage.cacheSavings;
maxRunCost = Math.max(maxRunCost, run.usage.cost);
+ addTokens(tokens, run.usage);
+ agentCost.set(run.task.agent_id, (agentCost.get(run.task.agent_id) ?? 0) + run.usage.cost);
+ // Per slice, not per run: a run that spilled from one model to another
+ // has a row for each, priced at its own rate.
+ for (const slice of run.task.usage ?? []) {
+ if (!slice.model) continue;
+ modelCost.set(slice.model, (modelCost.get(slice.model) ?? 0) + estimateCost(slice));
+ }
}
if (run.durationMs != null) agentMs += run.durationMs;
if (run.task.status === "failed") failedCount += 1;
@@ -178,6 +231,8 @@ export function buildRunTimeline(tasks: readonly AgentTask[], nowMs: number): Ru
runs,
totalCost,
pricedCount,
+ tokens,
+ cacheSavings,
agentMs,
elapsedMs,
failedCount,
@@ -186,12 +241,20 @@ export function buildRunTimeline(tasks: readonly AgentTask[], nowMs: number): Ru
domain: paddedDomain(first?.startMs ?? nowMs, lastEnd),
extent: [first?.startMs ?? nowMs, lastEnd],
cumulative,
- lanes: Array.from(laneMap, ([agentId, laneRuns]) => ({ agentId, runs: laneRuns })),
peak,
+ lanes: Array.from(laneMap, ([agentId, laneRuns]) => ({ agentId, runs: laneRuns })),
+ costByAgent: sortedShares(agentCost),
+ costByModel: sortedShares(modelCost),
maxRunCost,
};
}
+/** Share of the tokens that were served from cache, 0–1. Null with no input side. */
+export function cacheHitRate(tokens: Pick<TokenTotals, "input" | "cacheRead" | "cacheWrite">): number | null {
+ const prompt = tokens.input + tokens.cacheRead + tokens.cacheWrite;
+ return prompt > 0 ? tokens.cacheRead / prompt : null;
+}
+
// A little air on both ends so the first and last bars never sit on the frame,
// and a floor on the span so a single short run doesn't fill the whole axis.
const MIN_SPAN_MS = 60 * 60 * 1000;
@@ -369,6 +432,7 @@ export interface RunDayGroup {
/** Newest first within the day. */
runs: TimelineRun[];
cost: number;
+ tokens: number;
agentMs: number;
}
@@ -381,12 +445,48 @@ export function groupRunsByDay(runs: readonly TimelineRun[]): RunDayGroup[] {
const key = day.getTime();
let group = groups.get(key);
if (!group) {
- group = { dayMs: key, runs: [], cost: 0, agentMs: 0 };
+ group = { dayMs: key, runs: [], cost: 0, tokens: 0, agentMs: 0 };
groups.set(key, group);
}
group.runs.push(run);
group.cost += run.usage?.cost ?? 0;
+ group.tokens += run.usage?.tokens ?? 0;
group.agentMs += run.durationMs ?? 0;
}
return Array.from(groups.values());
}
+
+// ─── Model names ───────────────────────────────────────────────────────────
+
+function capitalize(word: string): string {
+ return word.charAt(0).toUpperCase() + word.slice(1);
+}
+
+/**
+ * A model id as a compact label: "claude-opus-5-5-high" → "Opus 5.5 high",
+ * "gpt-6.1-sol" → "GPT-6.1 Sol". Provider prefixes and context-window tags
+ * ("[1m]") are dropped. Ids from families it does not know come back as-is,
+ * so an unfamiliar model is never renamed into something misleading.
+ */
+export function shortModelName(model: string): string {
+ const id = model
+ .replace(/^[^/]+\//, "")
+ .replace(/\[[^\]]*\]$/, "")
+ .replace(/-\d{8}$/, "");
+ // claude-<tier>-<major>[-<minor>]-<variant…>
+ const claude = id.match(/^claude-([a-z]+)((?:-\d{1,2})+)(?:-(.+))?$/);
+ if (claude) {
+ const [, tier, version, variant] = claude;
+ return [capitalize(tier!), version!.slice(1).replaceAll("-", "."), variant?.replaceAll("-", " ")]
+ .filter(Boolean)
+ .join(" ");
+ }
+ // gpt-<version>-<variant…>, gemini-<version>-<variant…>
+ const generic = id.match(/^(gpt|gemini)-([^-]+)(?:-(.+))?$/);
+ if (generic) {
+ const [, family, version, variant] = generic;
+ const head = family === "gpt" ? `GPT-${version}` : `Gemini ${version}`;
+ return [head, ...(variant?.split("-").map(capitalize) ?? [])].join(" ");
+ }
+ return model;
+}
diff --git a/packages/views/issues/components/issue-runs-cumulative-chart.tsx b/packages/views/issues/components/issue-runs-cumulative-chart.tsx
new file mode 100644
index 0000000000..0ee0627233
--- /dev/null
+++ b/packages/views/issues/components/issue-runs-cumulative-chart.tsx
@@ -0,0 +1,495 @@
+"use client";
+
+import { useMemo, useRef, useState } from "react";
+import { cn } from "@multica/ui/lib/utils";
+import { useActorName } from "@multica/core/workspace/hooks";
+import { ActorAvatar } from "../../common/actor-avatar";
+import { formatDuration } from "../../dashboard/utils";
+import { useLocale, useT } from "../../i18n";
+import { formatUsd } from "../../runtimes/utils";
+import {
+ cumulativeCostAt,
+ idleSpanAround,
+ niceTicks,
+ runIndexAt,
+ stepCurvePath,
+ timeTicks,
+ type RunTimeline,
+ type TimelineRun,
+} from "./issue-run-timeline";
+import { RunTriggerLabel } from "./run-trigger-label";
+import { useStatusLabel, useTriggerText } from "./task-run-labels";
+
+// The Runs dialog's "over time" view: the issue's cumulative cost as a step
+// curve over per-agent run lanes, on one time axis. Where the per-run bars
+// answer "which run was expensive", this answers "when did the money go" —
+// the bursts, the quiet stretches between them, and the run that moved the
+// total most.
+
+// `formatDuration` falls back to this label only below one second.
+const UNDER_A_SECOND = "0s";
+
+const PLOT_HEIGHT = 112;
+// How far the pointer can miss a bar and still be on it: a run a few seconds
+// long draws as a 3px sliver, which nobody lands on exactly.
+const HOVER_SLOP_PX = 8;
+// The hover card's `max-w-72` plus its gap from the crosshair. With less room
+// than this to the right of the crosshair, the card opens on its left.
+const HOVER_CARD_ROOM_PX = 298;
+// Half the widest pointer-time tag ("Sep 27, 14:44"): nearer the plot's edge
+// than this, the tag aligns to the edge instead of centring on the crosshair,
+// and tick labels this close to it step aside.
+const TIME_TAG_HALF_PX = 48;
+
+function laneTone(run: TimelineRun, isPeak: boolean): string {
+ if (run.active) return "bg-info animate-pulse";
+ if (run.task.status === "failed") return "bg-destructive";
+ if (run.task.status === "cancelled") return "bg-faint-foreground";
+ return isPeak ? "bg-chart-1" : "bg-chart-2";
+}
+
+interface ChartHover {
+ /** The moment under the pointer, clamped to the stretch that holds runs. */
+ t: number;
+ /** The lane the pointer is over, if any. */
+ lane?: string;
+ /** The plot's rendered width, which turns pixels into time. */
+ width: number;
+}
+
+export function RunCumulativeChart({
+ timeline,
+ viewSwitch,
+}: {
+ timeline: RunTimeline;
+ /** The dialog's chart switch, placed first in this chart's toolbar. */
+ viewSwitch: React.ReactNode;
+}) {
+ const { t } = useT("issues");
+ const locale = useLocale();
+ const { getActorName } = useActorName();
+ const [d0, d1] = timeline.domain;
+ // Without any usage there is no curve to draw; the lanes still show when
+ // each run happened.
+ const plotHeight = timeline.pricedCount > 0 ? PLOT_HEIGHT : 0;
+ const xPct = (ms: number) => ((ms - d0) / (d1 - d0)) * 100;
+
+ const yTicks = niceTicks(timeline.totalCost);
+ const yMax = yTicks[yTicks.length - 1] ?? 1;
+ const yPct = (cost: number) => (1 - cost / yMax) * 100;
+
+ const ticks = timeTicks(timeline.domain);
+ const multiDay = d1 - d0 > 36 * 60 * 60 * 1000;
+ const [tickFormat, pointerFormat] = useMemo(() => {
+ const day = new Intl.DateTimeFormat(locale, { weekday: "short", month: "short", day: "numeric" });
+ const hour = new Intl.DateTimeFormat(locale, { hour: "2-digit", minute: "2-digit", hour12: false });
+ const dayHour = new Intl.DateTimeFormat(locale, {
+ month: "short",
+ day: "numeric",
+ hour: "2-digit",
+ minute: "2-digit",
+ hour12: false,
+ });
+ return [
+ (tick: (typeof ticks)[number]) => (tick.kind === "day" ? day.format(tick.t) : hour.format(tick.t)),
+ (ms: number) => (multiDay ? dayHour.format(ms) : hour.format(ms)),
+ ] as const;
+ }, [locale, multiDay]);
+
+ // Step curve in a 1000×100 box stretched over the plot; the stroke keeps its
+ // 2px via non-scaling-stroke however wide the dialog is.
+ const steps = timeline.cumulative;
+ const { line, area } = stepCurvePath(steps, timeline.domain, yMax);
+ const last = steps[steps.length - 1];
+
+ // Label the one run that moved the curve most. Left of its step the curve is
+ // lower (it only ever rises), so a label ending at the step's top-left
+ // corner never sits on the line. Near the left edge there is no room for
+ // that; right of the step the curve can still rise into anything above it,
+ // so the label drops just below the line instead, into the area wash.
+ const peak = timeline.peak;
+ const peakStep = peak ? steps.find((s) => s.t === peak.endMs) : undefined;
+ const peakX = peakStep ? xPct(peakStep.t) : 0;
+
+ // Hover layer. The crosshair is the pointer: it follows it across the whole
+ // chart row — lane labels and y scale included, so drifting a few pixels
+ // off the plot does not drop the hover — clamped to the stretch that holds
+ // runs. Whatever is under it answers: the run whose bar spans that moment,
+ // or between runs, the quiet stretch and what the curve reads there. It used
+ // to snap to the nearest run's end instead, which moved it hundreds of
+ // pixels for a few pixels of pointer travel (MUL-7780). The list below
+ // carries the same figures for keyboard and screen-reader users.
+ const plotRef = useRef<HTMLDivElement>(null);
+ const [hover, setHover] = useState<ChartHover | null>(null);
+ const trackPointer = (event: React.PointerEvent<HTMLDivElement>) => {
+ const rect = plotRef.current?.getBoundingClientRect();
+ if (!rect || rect.width <= 0) return;
+ const [e0, e1] = timeline.extent;
+ const at = d0 + ((event.clientX - rect.left) / rect.width) * (d1 - d0);
+ // Over a lane, only that lane's runs are candidates — the pointer is on a
+ // specific agent's row. Over the curve, any agent's run can answer.
+ const lane = (event.target as Element).closest?.("[data-lane]")?.getAttribute("data-lane");
+ setHover({ t: Math.min(Math.max(at, e0), e1), lane: lane ?? undefined, width: rect.width });
+ };
+
+ const hoverIndex = hover
+ ? runIndexAt(timeline.runs, hover.t, (HOVER_SLOP_PX / hover.width) * (d1 - d0), hover.lane)
+ : -1;
+ const hovered = hoverIndex >= 0 ? timeline.runs[hoverIndex] : undefined;
+ const hoverX = hover ? xPct(hover.t) : 0;
+ const hoverPx = hover ? (hoverX / 100) * hover.width : 0;
+ // The point the card is about: the hovered run's step on the curve, or
+ // between runs, the curve's reading under the crosshair. A run that has not
+ // reported usage has no step to point at.
+ const dot =
+ !hover || plotHeight === 0
+ ? null
+ : hovered
+ ? hovered.usage
+ ? { x: xPct(hovered.endMs), cost: hovered.costSoFar }
+ : null
+ : { x: hoverX, cost: cumulativeCostAt(steps, hover.t) };
+ // The card sits in whichever half of the plot its dot is not in, so it never
+ // covers the point it describes.
+ const cardTop = dot && yPct(dot.cost) < 50 ? Math.round(plotHeight * 0.4) : 0;
+ const cardOnLeft = hover ? hoverPx + HOVER_CARD_ROOM_PX > hover.width : false;
+ const tagTransform = !hover
+ ? undefined
+ : hoverPx < TIME_TAG_HALF_PX
+ ? "none"
+ : hoverPx > hover.width - TIME_TAG_HALF_PX
+ ? "translateX(-100%)"
+ : "translateX(-50%)";
+
+ return (
+ <div className="mt-5 border-b px-6 pb-3">
+ <div className="mb-3 flex flex-wrap items-center gap-x-3 gap-y-2">
+ {viewSwitch}
+ <div className="ml-auto flex items-center gap-4 text-caption text-muted-foreground">
+ {timeline.pricedCount > 0 && (
+ <span className="flex items-center gap-1.5">
+ <span aria-hidden className="h-0.5 w-3.5 rounded-full bg-chart-1" />
+ {t(($) => $.runs_timeline.legend_cumulative)}
+ </span>
+ )}
+ <span className="flex items-center gap-1.5">
+ <span aria-hidden className="h-2 w-3 rounded-xs bg-chart-2" />
+ {t(($) => $.runs_timeline.legend_run)}
+ </span>
+ </div>
+ </div>
+ <div
+ role="img"
+ aria-label={t(($) => $.runs_timeline.cumulative_aria, {
+ count: timeline.runs.length,
+ cost: formatUsd(timeline.totalCost),
+ })}
+ className="flex gap-3"
+ onPointerMove={trackPointer}
+ onPointerDown={trackPointer}
+ onPointerLeave={() => setHover(null)}
+ >
+ {/* Lane labels, aligned with the lanes in the plot column. */}
+ <div className="w-24 shrink-0" aria-hidden>
+ <div style={{ height: plotHeight }} />
+ <div className={cn(plotHeight > 0 && "mt-[9px]")}>
+ {timeline.lanes.map((lane) => (
+ <div key={lane.agentId} className="flex h-5 min-w-0 items-center gap-1.5">
+ <ActorAvatar actorType="agent" actorId={lane.agentId} size="xs" />
+ <span className="truncate text-micro text-muted-foreground">
+ {getActorName("agent", lane.agentId)}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+
+ <div ref={plotRef} className="relative min-w-0 flex-1">
+ {/* Time gridlines run through the curve and the lanes alike. */}
+ {ticks.map((tick) => (
+ <span
+ key={tick.t}
+ aria-hidden
+ className="absolute top-0 bottom-5 w-px bg-border"
+ style={{ left: `${xPct(tick.t)}%` }}
+ />
+ ))}
+
+ <div className="relative" style={{ height: plotHeight }} aria-hidden>
+ {yTicks.map((v) => (
+ <span
+ key={v}
+ className="absolute inset-x-0 h-px bg-border"
+ style={{ top: `${yPct(v)}%` }}
+ />
+ ))}
+ {steps.length > 0 && (
+ <svg
+ className="absolute inset-0 size-full overflow-visible"
+ viewBox="0 0 1000 100"
+ preserveAspectRatio="none"
+ >
+ <path d={area} fill="var(--chart-1)" fillOpacity={0.1} />
+ <path
+ d={line}
+ fill="none"
+ stroke="var(--chart-1)"
+ strokeWidth={2}
+ strokeLinejoin="round"
+ vectorEffect="non-scaling-stroke"
+ />
+ </svg>
+ )}
+ {last && (
+ <span
+ className="absolute size-2 -translate-x-1/2 -translate-y-1/2 rounded-full bg-chart-1 ring-2 ring-popover"
+ style={{ left: `${xPct(last.t)}%`, top: `${yPct(last.cost)}%` }}
+ />
+ )}
+ {dot && (
+ <span
+ className="pointer-events-none absolute z-10 size-2.5 -translate-x-1/2 -translate-y-1/2 rounded-full bg-chart-1 ring-2 ring-popover"
+ style={{ left: `${dot.x}%`, top: `${yPct(dot.cost)}%` }}
+ />
+ )}
+ {/* Fades rather than unmounts under the hover card, so entering and
+ leaving the chart does not blink it. */}
+ {peak && peakStep && (
+ <PeakLabel
+ run={peak}
+ className={cn("transition-opacity duration-150", hover && "opacity-0")}
+ style={{
+ left: `${peakX}%`,
+ top: `${yPct(peakStep.cost)}%`,
+ transform:
+ peakX >= 30
+ ? "translate(calc(-100% - 6px), calc(-100% - 2px))"
+ : "translate(6px, 4px)",
+ }}
+ />
+ )}
+ </div>
+
+ {/* Rows, not tracks, carry `data-lane`, and they touch: moving from one
+ lane to the next never crosses a gap that belongs to no lane, which
+ would briefly hand the hover to every agent's runs. */}
+ <div className={cn(plotHeight > 0 && "mt-[9px]")}>
+ {timeline.lanes.map((lane) => (
+ <div key={lane.agentId} data-lane={lane.agentId} className="py-[3px]">
+ <div className="relative h-3.5 rounded-xs bg-muted/60">
+ {lane.runs.map((run) => (
+ <span
+ key={run.task.id}
+ className={cn(
+ "absolute inset-y-0.5 min-w-[3px] rounded-xs transition-opacity",
+ laneTone(run, run === peak),
+ hovered && run !== hovered && "opacity-35",
+ )}
+ style={{
+ left: `${xPct(run.startMs)}%`,
+ width: `${xPct(run.endMs) - xPct(run.startMs)}%`,
+ }}
+ />
+ ))}
+ </div>
+ </div>
+ ))}
+ </div>
+
+ {hover && (
+ <>
+ <span
+ aria-hidden
+ className="pointer-events-none absolute top-0 bottom-5 w-px bg-foreground/30"
+ style={{ left: `${hoverX}%` }}
+ />
+ {/* Beside the crosshair, on whichever side has room. */}
+ <div
+ aria-hidden
+ data-hover-card
+ className="pointer-events-none absolute z-20 w-max max-w-72 rounded-lg border bg-popover px-2.5 py-1.5 text-caption text-popover-foreground shadow-[var(--menu-shadow)]"
+ style={{
+ left: `${hoverX}%`,
+ top: cardTop,
+ transform: cardOnLeft ? "translateX(calc(-100% - 10px))" : "translateX(10px)",
+ }}
+ >
+ {hovered ? (
+ <CumulativeRunCard run={hovered} />
+ ) : (
+ <IdleHoverCard
+ {...idleSpanAround(timeline.runs, hover.t, hover.lane)}
+ total={timeline.pricedCount > 0 ? cumulativeCostAt(steps, hover.t) : null}
+ />
+ )}
+ </div>
+ </>
+ )}
+
+ <div className="relative mt-px h-5" aria-hidden>
+ {ticks.map((tick) => {
+ const x = xPct(tick.t);
+ // The pointer's own time tag takes the axis where it stands.
+ if (hover && Math.abs(((x - hoverX) / 100) * hover.width) < TIME_TAG_HALF_PX) return null;
+ return (
+ <span
+ key={tick.t}
+ className="absolute top-1 whitespace-nowrap px-1 text-micro text-muted-foreground"
+ style={{ left: `${x}%`, transform: x > 92 ? "translateX(-100%)" : undefined }}
+ >
+ {tickFormat(tick)}
+ </span>
+ );
+ })}
+ {hover && (
+ <span
+ className="pointer-events-none absolute top-0.5 z-20 whitespace-nowrap rounded-xs bg-foreground px-1 text-micro font-medium tabular-nums text-background"
+ style={{ left: `${hoverX}%`, transform: tagTransform }}
+ >
+ {pointerFormat(hover.t)}
+ </span>
+ )}
+ </div>
+ </div>
+
+ {/* Y scale on the right, where the curve ends; the end value is the
+ one figure labelled in full. */}
+ <div className="relative w-12 shrink-0 text-micro tabular-nums" style={{ height: plotHeight }} aria-hidden>
+ {yTicks.map((v) =>
+ last && Math.abs(yPct(v) - yPct(last.cost)) < 12 ? null : (
+ <span
+ key={v}
+ className="absolute left-1 -translate-y-1/2 text-muted-foreground"
+ style={{ top: `${yPct(v)}%` }}
+ >
+ {formatTick(v)}
+ </span>
+ ),
+ )}
+ {last && (
+ <span
+ className="absolute left-1 -translate-y-1/2 font-medium text-foreground"
+ style={{ top: `${yPct(last.cost)}%` }}
+ >
+ {formatUsd(last.cost)}
+ </span>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
+// Axis steps are round numbers; "$50.00" would print noise the curve's end
+// label, which keeps full precision, does not need.
+function formatTick(v: number): string {
+ return Number.isInteger(v) ? `$${v}` : formatUsd(v);
+}
+
+function PeakLabel({
+ run,
+ className,
+ style,
+}: {
+ run: TimelineRun;
+ className?: string;
+ style: React.CSSProperties;
+}) {
+ const trigger = useTriggerText(run.task);
+ return (
+ <span
+ className={cn("absolute flex max-w-60 items-baseline gap-1 whitespace-nowrap text-micro", className)}
+ style={style}
+ >
+ <span className="font-medium text-foreground">+{formatUsd(run.usage?.cost ?? 0)}</span>
+ <RunTriggerLabel task={run.task} fallback={trigger}>
+ {(label) => <span className="truncate text-muted-foreground">{label}</span>}
+ </RunTriggerLabel>
+ </span>
+ );
+}
+
+function CumulativeRunCard({ run }: { run: TimelineRun }) {
+ const { t } = useT("issues");
+ const { getActorName } = useActorName();
+ const trigger = useTriggerText(run.task);
+ const status = useStatusLabel(run.task.status);
+ const locale = useLocale();
+ const when = new Intl.DateTimeFormat(locale, {
+ month: "short",
+ day: "numeric",
+ hour: "2-digit",
+ minute: "2-digit",
+ hour12: false,
+ }).format(run.startMs);
+ const facts = [
+ when,
+ run.task.status === "completed" && run.durationMs != null
+ ? formatDuration(run.durationMs / 1000, UNDER_A_SECOND)
+ : status,
+ ];
+ return (
+ <div className="flex min-w-0 flex-col gap-1">
+ <RunTriggerLabel task={run.task} fallback={trigger}>
+ {(label) => <span className="truncate font-medium">{label}</span>}
+ </RunTriggerLabel>
+ <span className="flex min-w-0 items-center gap-1.5 text-micro text-muted-foreground">
+ <ActorAvatar actorType="agent" actorId={run.task.agent_id} size="xs" />
+ <span className="truncate">{[getActorName("agent", run.task.agent_id), ...facts].join(" · ")}</span>
+ </span>
+ <span className="text-micro tabular-nums">
+ <span className="font-medium">
+ {run.usage ? formatUsd(run.usage.cost) : t(($) => $.runs_timeline.no_usage)}
+ </span>
+ <span className="text-muted-foreground">
+ {" · "}
+ {t(($) => $.runs_timeline.tooltip_total, { cost: formatUsd(run.costSoFar) })}
+ </span>
+ </span>
+ </div>
+ );
+}
+
+// Between runs: nothing ran here. Says so, with how long the quiet lasted and
+// what the issue had spent by then — the curve's reading under the crosshair.
+function IdleHoverCard({
+ fromMs,
+ toMs,
+ total,
+}: {
+ fromMs: number | null;
+ toMs: number | null;
+ /** Null when no run reported usage — there is no total to quote. */
+ total: number | null;
+}) {
+ const { t } = useT("issues");
+ const locale = useLocale();
+ const span = useMemo(() => {
+ if (fromMs == null || toMs == null) return null;
+ const sameDay = new Date(fromMs).toDateString() === new Date(toMs).toDateString();
+ const fmt = new Intl.DateTimeFormat(locale, {
+ ...(sameDay ? {} : { month: "short", day: "numeric" }),
+ hour: "2-digit",
+ minute: "2-digit",
+ hour12: false,
+ });
+ return `${fmt.format(fromMs)} → ${fmt.format(toMs)}`;
+ }, [fromMs, toMs, locale]);
+ return (
+ <div className="flex min-w-0 flex-col gap-1">
+ <span className="font-medium">{t(($) => $.runs_timeline.hover_no_run)}</span>
+ {span && fromMs != null && toMs != null && (
+ <span className="truncate text-micro tabular-nums text-muted-foreground">
+ {span} ·{" "}
+ {t(($) => $.runs_timeline.hover_idle, {
+ duration: formatDuration((toMs - fromMs) / 1000, UNDER_A_SECOND),
+ })}
+ </span>
+ )}
+ {total != null && (
+ <span className="text-micro tabular-nums text-muted-foreground">
+ {t(($) => $.runs_timeline.tooltip_total, { cost: formatUsd(total) })}
+ </span>
+ )}
+ </div>
+ );
+}
diff --git a/packages/views/issues/components/issue-runs-dialog.test.tsx b/packages/views/issues/components/issue-runs-dialog.test.tsx
index 6007a86f72..a06038ad91 100644
--- a/packages/views/issues/components/issue-runs-dialog.test.tsx
+++ b/packages/views/issues/components/issue-runs-dialog.test.tsx
@@ -101,17 +101,27 @@ describe("IssueRunsDialog", () => {
expect(screen.getByRole("heading", { name: "Runs" })).toBeInTheDocument();
expect(screen.getByText("MUL-7680 · Issue wakeups v2")).toBeInTheDocument();
- // $25 + $5, 30m + 15m of agent time, first start to last end.
- const stat = (label: string) => screen.getByText(label).parentElement!;
+ // $25 + $5, 1.2M output tokens, 30m + 15m of agent time over 23h 30m.
+ const stat = (label: string) => screen.getByRole("group", { name: label });
expect(stat("Spent")).toHaveTextContent("$30.00");
- expect(stat("Agent time")).toHaveTextContent("45m");
- expect(stat("Elapsed")).toHaveTextContent("23h 30m");
+ expect(stat("Tokens")).toHaveTextContent("1.2M");
+ expect(stat("Output")).toHaveTextContent("1.2M");
+ expect(stat("Agent time")).toHaveTextContent("45m· 23h 30m elapsed");
expect(screen.getByText(/1 failed/)).toBeInTheDocument();
expect(
- screen.getByRole("img", { name: "Cumulative cost over time: $30.00 across 2 runs" }),
+ screen.getByRole("img", { name: "Run activity: $30.00 across 2 runs" }),
).toBeInTheDocument();
});
+ it("splits the spend by agent and by model", () => {
+ open([makeTask({ usage: [usage()] })]);
+
+ const byModel = screen.getByRole("region", { name: "By model" });
+ expect(within(byModel).getByText("Opus 5")).toBeInTheDocument();
+ expect(within(byModel).getByTitle("claude-opus-5")).toBeInTheDocument();
+ expect(within(screen.getByRole("region", { name: "By agent" })).getByText("Lambda")).toBeInTheDocument();
+ });
+
it("groups runs by day, newest first, with each day's total", () => {
open([
makeTask({ id: "old", trigger_summary: "Older run", started_at: "2026-09-26T10:00:00", completed_at: "2026-09-26T10:15:00", usage: [usage({ output_tokens: 200_000 })] }),
@@ -121,7 +131,7 @@ describe("IssueRunsDialog", () => {
const today = screen.getByRole("region", { name: "Today" });
const yesterday = screen.getByRole("region", { name: "Yesterday" });
expect(within(today).getByText("Newer run")).toBeInTheDocument();
- expect(within(today).getByText("1 run · 30m · $25.00")).toBeInTheDocument();
+ expect(within(today).getByText("1 run · 30m · 1M tokens · $25.00")).toBeInTheDocument();
expect(within(yesterday).getByText("Older run")).toBeInTheDocument();
expect(
today.compareDocumentPosition(yesterday) & Node.DOCUMENT_POSITION_FOLLOWING,
@@ -190,23 +200,129 @@ describe("IssueRunsDialog", () => {
expect(screen.getAllByText("$7.00").length).toBeGreaterThan(0);
});
- // The plot column sits beside the lane labels; give it a width, which jsdom
- // does not lay out. Returns the x of a moment on the chart's padded domain.
- function layOut(plot: HTMLElement, first: string, last: string) {
+ // jsdom does not lay out; give the plot a width so pointer x maps to a run.
+ function layOut(plot: HTMLElement) {
plot.getBoundingClientRect = () => ({ left: 0, width: 1000, top: 0, height: 200, right: 1000, bottom: 200, x: 0, y: 0, toJSON: () => ({}) });
+ }
+ const plotOf = () => screen.getByRole("img").children[0] as HTMLElement;
+ const hoverCard = (plot: HTMLElement) => plot.querySelector("[data-hover-card]") as HTMLElement | null;
+ const twoRuns = () => [
+ makeTask({ id: "early", trigger_summary: "Early run", started_at: "2026-09-26T09:00:00", completed_at: "2026-09-26T09:30:00", usage: [usage()] }),
+ makeTask({ id: "late", trigger_summary: "Late run", started_at: "2026-09-27T15:00:00", completed_at: "2026-09-27T15:10:00", usage: [usage({ output_tokens: 200_000 })] }),
+ ];
+
+ it("draws one bar per run, oldest first, with days as dividers", () => {
+ open([
+ ...twoRuns(),
+ makeTask({ id: "failed", status: "failed", started_at: "2026-09-27T16:00:00", completed_at: "2026-09-27T16:05:00" }),
+ ]);
+ const plot = plotOf();
+
+ expect(Array.from(plot.querySelectorAll("[data-run]"), (el) => el.getAttribute("data-run"))).toEqual([
+ "early",
+ "late",
+ "failed",
+ ]);
+ // $25 against $5: heights follow cost, and a run with no usage is a stub.
+ const height = (id: string) => (plot.querySelector(`[data-run="${id}"]`) as HTMLElement).style.height;
+ expect(parseFloat(height("early"))).toBeGreaterThan(parseFloat(height("late")));
+ expect(height("failed")).toBe("4px");
+ expect(within(plot).getByText("Sep 26")).toBeInTheDocument();
+ expect(within(plot).getByText("Today")).toBeInTheDocument();
+ });
+
+ it("names the run under the pointer, anywhere in the chart row", () => {
+ open(twoRuns());
+ const chart = screen.getByRole("img");
+ const plot = plotOf();
+ layOut(plot);
+
+ fireEvent.pointerMove(plot, { clientX: 750 });
+ expect(within(hoverCard(plot)!).getByText("Late run")).toBeInTheDocument();
+ expect(within(hoverCard(plot)!).getByText("$5.00")).toBeInTheDocument();
+
+ fireEvent.pointerMove(plot, { clientX: 250 });
+ expect(within(hoverCard(plot)!).getByText("Early run")).toBeInTheDocument();
+
+ // Drifting onto the y scale clamps to the newest run instead of dropping the hover.
+ fireEvent.pointerMove(chart.children[1] as HTMLElement, { clientX: 1030 });
+ expect(within(hoverCard(plot)!).getByText("Late run")).toBeInTheDocument();
+
+ fireEvent.pointerLeave(chart);
+ expect(hoverCard(plot)).not.toBeInTheDocument();
+ });
+
+ it("switches the chart between cost, tokens and agent time", () => {
+ open(twoRuns());
+ const plot = plotOf();
+ layOut(plot);
+
+ fireEvent.click(screen.getByRole("button", { name: "Tokens" }));
+ expect(screen.getByText("per run · by token type")).toBeInTheDocument();
+ // In the token view the hover splits the run's tokens by type.
+ fireEvent.pointerMove(plot, { clientX: 750 });
+ expect(within(hoverCard(plot)!).getByText("Output")).toBeInTheDocument();
+ expect(within(hoverCard(plot)!).getByText("200K")).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole("button", { name: "Agent time" }));
+ expect(screen.getByText("per run · by agent")).toBeInTheDocument();
+ });
+
+ // Review repro (PR #9288): segments used dollar amounts as flex-grow, and
+ // grow factors summing below 1 leave free space unfilled — a $0.10 bar drew
+ // a tenth of its height. jsdom does not lay out, so pin the factors instead.
+ it("splits bars by share, so costs under $1 still fill them", () => {
+ open([
+ makeTask({ id: "a", agent_id: "agent-a", usage: [usage({ output_tokens: 4_000 })] }),
+ makeTask({ id: "b", agent_id: "agent-b", started_at: "2026-09-27T11:00:00", usage: [usage({ output_tokens: 16_000 })] }),
+ ]);
+ const grow = (el: Element) => Number((el as HTMLElement).style.flexGrow);
+
+ const bar = screen.getByRole("img").querySelector('[data-run="a"]')!;
+ expect(Array.from(bar.children, grow)).toEqual([1]);
+
+ // $0.40 and $0.10 of $0.50.
+ const band = within(screen.getByRole("region", { name: "By agent" })).getByText("By agent").nextElementSibling!;
+ expect(Array.from(band.children, grow)).toEqual([0.8, 0.2]);
+
+ const toggle = screen.getAllByRole("button", { name: "Run details" })[0]!;
+ fireEvent.click(toggle);
+ const details = document.getElementById(toggle.getAttribute("aria-controls")!)!;
+ const split = details.querySelector('[aria-hidden="true"]')!;
+ expect(Array.from(split.children, grow)).toEqual([1]);
+ });
+
+ // The cumulative view's x axis is time over the runs' padded span.
+ function layOutTime(plot: HTMLElement, first: string, last: string) {
+ layOut(plot);
const [d0, d1] = [new Date(first).getTime(), new Date(last).getTime()];
const pad = (d1 - d0) * 0.02;
return (iso: string) => ((new Date(iso).getTime() - (d0 - pad)) / (d1 - d0 + 2 * pad)) * 1000;
}
- const hoverCard = (plot: HTMLElement) => plot.querySelector("[data-hover-card]") as HTMLElement | null;
+ const showCumulative = () => fireEvent.click(screen.getByRole("button", { name: "Cumulative" }));
+
+ it("keeps the cumulative cost curve as a second view", () => {
+ open(twoRuns());
+ expect(screen.getByRole("button", { name: "Per run" })).toHaveAttribute("aria-pressed", "true");
+
+ showCumulative();
+ expect(screen.getByRole("img", { name: "Cumulative cost over time: $30.00 across 2 runs" })).toBeInTheDocument();
+ expect(screen.getByText("Cumulative cost")).toBeInTheDocument();
+ // The metric switch belongs to the per-run bars.
+ expect(screen.queryByRole("button", { name: "Tokens" })).not.toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole("button", { name: "Per run" }));
+ expect(screen.getByRole("button", { name: "Tokens" })).toBeInTheDocument();
+ });
it("follows the pointer: the run under it answers, a gap says so", () => {
open([
makeTask({ id: "early", trigger_summary: "Early run", started_at: "2026-09-27T09:00:00", completed_at: "2026-09-27T09:30:00", usage: [usage()] }),
makeTask({ id: "late", trigger_summary: "Late run", started_at: "2026-09-27T15:00:00", completed_at: "2026-09-27T15:10:00", usage: [usage({ output_tokens: 200_000 })] }),
]);
+ showCumulative();
const plot = screen.getByRole("img").children[1] as HTMLElement;
- const x = layOut(plot, "2026-09-27T09:00:00", "2026-09-27T15:10:00");
+ const x = layOutTime(plot, "2026-09-27T09:00:00", "2026-09-27T15:10:00");
fireEvent.pointerMove(plot, { clientX: x("2026-09-27T15:05:00") });
expect(within(hoverCard(plot)!).getByText("Late run")).toBeInTheDocument();
@@ -234,9 +350,10 @@ describe("IssueRunsDialog", () => {
makeTask({ id: "early", trigger_summary: "Early run", started_at: "2026-09-27T09:00:00", completed_at: "2026-09-27T09:30:00", usage: [usage()] }),
makeTask({ id: "late", trigger_summary: "Late run", started_at: "2026-09-27T15:00:00", completed_at: "2026-09-27T15:10:00", usage: [usage()] }),
]);
+ showCumulative();
const chart = screen.getByRole("img");
const plot = chart.children[1] as HTMLElement;
- layOut(plot, "2026-09-27T09:00:00", "2026-09-27T15:10:00");
+ layOutTime(plot, "2026-09-27T09:00:00", "2026-09-27T15:10:00");
// Left of the plot: clamped to where the runs begin.
fireEvent.pointerMove(chart.children[0] as HTMLElement, { clientX: -40 });
@@ -249,8 +366,9 @@ describe("IssueRunsDialog", () => {
makeTask({ id: "long", agent_id: "agent-lambda", trigger_summary: "Long run", started_at: "2026-09-27T09:00:00", completed_at: "2026-09-27T12:00:00", usage: [usage()] }),
makeTask({ id: "short", agent_id: "agent-emacs", trigger_summary: "Short run", started_at: "2026-09-27T10:00:00", completed_at: "2026-09-27T11:00:00", usage: [usage({ output_tokens: 200_000 })] }),
]);
+ showCumulative();
const plot = screen.getByRole("img").children[1] as HTMLElement;
- const x = layOut(plot, "2026-09-27T09:00:00", "2026-09-27T12:00:00");
+ const x = layOutTime(plot, "2026-09-27T09:00:00", "2026-09-27T12:00:00");
const lane = (agentId: string) => plot.querySelector(`[data-lane="${agentId}"]`) as HTMLElement;
fireEvent.pointerMove(lane("agent-lambda"), { clientX: x("2026-09-27T10:30:00") });
@@ -260,17 +378,18 @@ describe("IssueRunsDialog", () => {
expect(within(hoverCard(plot)!).getByText("Short run")).toBeInTheDocument();
});
- it("opens a run's cost split from a real button, not hover alone", () => {
+ it("expands a run's details from a real button", () => {
open([makeTask({ usage: [usage()] })]);
- // Focusable (keyboard) and clickable (touch); the review found a span.
- const button = screen.getByRole("button", { name: "Cost breakdown: $25.00" });
- expect(button).not.toHaveAttribute("tabindex", "-1");
- expect(screen.queryByText("claude-opus-5")).not.toBeInTheDocument();
+ const toggle = screen.getByRole("button", { name: "Run details" });
+ expect(toggle).toHaveAttribute("aria-expanded", "false");
+ expect(document.getElementById(toggle.getAttribute("aria-controls")!)).toBeNull();
- fireEvent.click(button);
- expect(screen.getByText("claude-opus-5")).toBeInTheDocument();
- expect(screen.getByText("1M")).toBeInTheDocument();
+ fireEvent.click(toggle);
+ expect(toggle).toHaveAttribute("aria-expanded", "true");
+ const details = document.getElementById(toggle.getAttribute("aria-controls")!)!;
+ expect(within(details).getByText("claude-opus-5")).toBeInTheDocument();
+ expect(within(details).getByText("Total")).toBeInTheDocument();
});
it("names a wakeup run by its rule, not as a quote", () => {
diff --git a/packages/views/issues/components/issue-runs-dialog.tsx b/packages/views/issues/components/issue-runs-dialog.tsx
index f966db44a6..35c76d6243 100644
--- a/packages/views/issues/components/issue-runs-dialog.tsx
+++ b/packages/views/issues/components/issue-runs-dialog.tsx
@@ -1,7 +1,7 @@
"use client";
import { useMemo, useRef, useState } from "react";
-import { ArrowRight, Ban, XCircle } from "lucide-react";
+import { ArrowRight, Ban, ChevronRight, XCircle } from "lucide-react";
import type { AgentTask } from "@multica/core/types";
import { cn } from "@multica/ui/lib/utils";
import {
@@ -11,16 +11,12 @@ import {
DialogHeader,
DialogTitle,
} from "@multica/ui/components/ui/dialog";
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@multica/ui/components/ui/popover";
import { useActorName } from "@multica/core/workspace/hooks";
import { useCustomPricingStore } from "@multica/core/runtimes/custom-pricing-store";
import { ActorAvatar } from "../../common/actor-avatar";
import { TranscriptButton } from "../../common/task-transcript";
import { cancellationActorLabel, cancelReasonLabel, failureReasonLabel } from "../../agents/components/tabs/task-failure";
+import { Segmented } from "../../dashboard/components/dashboard-shared";
import { formatDuration } from "../../dashboard/utils";
import { useLocale, useT } from "../../i18n";
import {
@@ -32,36 +28,35 @@ import {
import { AttributionBadge } from "./attribution-badge";
import {
buildRunTimeline,
- cumulativeCostAt,
+ cacheHitRate,
groupRunsByDay,
- idleSpanAround,
niceTicks,
- runIndexAt,
- stepCurvePath,
- timeTicks,
+ shortModelName,
+ type CostShare,
type RunTimeline,
type TimelineRun,
} from "./issue-run-timeline";
+import { RunCumulativeChart } from "./issue-runs-cumulative-chart";
import { canRetryRun, RetryRunButton } from "./retry-run-button";
+import { RunTriggerLabel } from "./run-trigger-label";
import { useStatusLabel, useTriggerText } from "./task-run-labels";
-import { WakeupRunLabel } from "./wakeup-source-chip";
// The issue's runs laid out in time — the surface the execution log's header
-// and spend strip open.
+// and cost bars open.
//
// The sidebar answers "what is running and what just ran"; this answers "how
-// did this issue get here": when each run happened, how long it took, who asked
-// for it, and which ones moved the total. The chart on top is the shape of the
-// issue (a cumulative cost curve over per-agent run lanes on one time axis);
-// the list below is the same runs as rows, newest first — it is also the
-// chart's accessible, exact-value view.
+// did this issue get here": what it spent and on what, when, who asked for
+// each run, and which ones were expensive. The chart on top is one bar per
+// run (cost, tokens or agent time); the list below is the same runs as rows,
+// newest first — it is also the chart's accessible, exact-value view. The
+// cumulative cost curve over time is the chart's second view.
//
// Every figure comes from the same `summarizeTaskUsage` helpers the sidebar
// uses, so the total here can never disagree with the total that opened it.
// Cost categories in the order and colours the runtime usage charts stack them
// (`costStackConfig` in runtimes/components/charts/daily-cost-chart.tsx), so a
-// run's cost bar reads the same as a day's bar on the usage page.
+// run's split reads the same as a day's bar on the usage page.
const COST_PARTS = [
{ key: "input", swatch: "bg-chart-1" },
{ key: "output", swatch: "bg-chart-2" },
@@ -71,6 +66,24 @@ const COST_PARTS = [
type CostPartKey = (typeof COST_PARTS)[number]["key"];
+// Agents and models stack in the chart palette's order, most expensive first.
+// The palette is one hue in steps of lightness, so past four the steps stop
+// being tellable apart; the rest share the last step as "Others".
+const SERIES_SWATCHES = ["bg-chart-1", "bg-chart-2", "bg-chart-3", "bg-chart-4"] as const;
+const OTHERS_SWATCH = "bg-chart-5";
+const OTHERS_KEY = "__others__";
+
+// Flex grow factors that sum below 1 fill only that fraction of the free
+// space (CSS Flexbox §7.1), so splitting a bar by raw dollar amounts under $1
+// would draw it short. As shares of the total they always sum to 1.
+function shareStyle(value: number, total: number): React.CSSProperties {
+ return { flexGrow: total > 0 ? value / total : 0, flexBasis: 0 };
+}
+
+function sumOf(values: readonly number[]): number {
+ return values.reduce((sum, v) => sum + v, 0);
+}
+
function useCostPartLabel(): (key: CostPartKey) => string {
const { t } = useT("issues");
return (key) => {
@@ -83,6 +96,15 @@ function useCostPartLabel(): (key: CostPartKey) => string {
};
}
+function usePercent(): (share: number) => string {
+ const locale = useLocale();
+ const fmt = useMemo(
+ () => new Intl.NumberFormat(locale, { style: "percent", maximumFractionDigits: 0 }),
+ [locale],
+ );
+ return (share) => fmt.format(share);
+}
+
export function IssueRunsDialog({
open,
onOpenChange,
@@ -137,7 +159,8 @@ export function IssueRunsDialog({
{timeline.runs.length > 0 && (
<>
<RunStats timeline={timeline} />
- <RunTimelineChart timeline={timeline} />
+ <RunCharts timeline={timeline} />
+ {timeline.pricedCount > 0 && <CostSplit timeline={timeline} />}
{/* `min-h-0`: the dialog is a flex column; without it this flex
item sizes to its content and the list never scrolls. */}
<div className="min-h-0 flex-1 overflow-y-auto px-6 pb-5">
@@ -166,8 +189,8 @@ function Stat({
children: React.ReactNode;
}) {
return (
- <div className="min-w-0">
- <div className="text-micro font-medium uppercase tracking-wider text-muted-foreground">
+ <div role="group" aria-label={label} className="min-w-0">
+ <div aria-hidden className="text-micro font-medium uppercase tracking-wider text-muted-foreground">
{label}
</div>
<div className="mt-1">{children}</div>
@@ -180,6 +203,9 @@ const UNDER_A_SECOND = "0s";
function RunStats({ timeline }: { timeline: RunTimeline }) {
const { t } = useT("issues");
+ const percent = usePercent();
+ const priced = timeline.pricedCount > 0;
+ const hit = cacheHitRate(timeline.tokens);
const breakdown = [
timeline.failedCount > 0 &&
t(($) => $.runs_timeline.count_failed, { count: timeline.failedCount }),
@@ -195,17 +221,34 @@ function RunStats({ timeline }: { timeline: RunTimeline }) {
{/* Proportional figures: a standalone hero number set in tabular
digits reads loose. "—" when nothing reported usage — never $0. */}
<span className="text-display-sm font-semibold">
- {timeline.pricedCount > 0 ? formatUsd(timeline.totalCost) : "—"}
+ {priced ? formatUsd(timeline.totalCost) : "—"}
+ </span>
+ </Stat>
+ <Stat label={t(($) => $.runs_timeline.stat_tokens)}>
+ <span className="text-title-sm font-medium tabular-nums">
+ {priced ? formatTokens(timeline.tokens.total) : "—"}
+ </span>
+ {/* Cache reads are most of an agent's tokens; without the share the
+ total reads as far more fresh work than it was. */}
+ {priced && hit != null && (
+ <span className="ml-1.5 text-caption text-muted-foreground">
+ · {t(($) => $.runs_timeline.tokens_cached, { percent: percent(hit) })}
+ </span>
+ )}
+ </Stat>
+ <Stat label={t(($) => $.runs_timeline.stat_output)}>
+ <span className="text-title-sm font-medium tabular-nums">
+ {priced ? formatTokens(timeline.tokens.output) : "—"}
</span>
</Stat>
<Stat label={t(($) => $.runs_timeline.stat_agent_time)}>
<span className="text-title-sm font-medium">
{formatDuration(timeline.agentMs / 1000, UNDER_A_SECOND)}
</span>
- </Stat>
- <Stat label={t(($) => $.runs_timeline.stat_elapsed)}>
- <span className="text-title-sm font-medium">
- {formatDuration(timeline.elapsedMs / 1000, UNDER_A_SECOND)}
+ <span className="ml-1.5 text-caption text-muted-foreground">
+ · {t(($) => $.runs_timeline.elapsed_note, {
+ duration: formatDuration(timeline.elapsedMs / 1000, UNDER_A_SECOND),
+ })}
</span>
</Stat>
<Stat label={t(($) => $.runs_timeline.stat_runs)}>
@@ -216,400 +259,336 @@ function RunStats({ timeline }: { timeline: RunTimeline }) {
</span>
)}
</Stat>
- <div className="ml-auto flex items-center gap-4 pb-0.5 text-caption text-muted-foreground">
- {timeline.pricedCount > 0 && (
- <span className="flex items-center gap-1.5">
- <span aria-hidden className="h-0.5 w-3.5 rounded-full bg-chart-1" />
- {t(($) => $.runs_timeline.legend_cumulative)}
- </span>
- )}
- <span className="flex items-center gap-1.5">
- <span aria-hidden className="h-2 w-3 rounded-xs bg-chart-2" />
- {t(($) => $.runs_timeline.legend_run)}
- </span>
- </div>
</div>
);
}
// ─── Chart ─────────────────────────────────────────────────────────────────
-const PLOT_HEIGHT = 112;
-// How far the pointer can miss a bar and still be on it: a run a few seconds
-// long draws as a 3px sliver, which nobody lands on exactly.
-const HOVER_SLOP_PX = 8;
-// The hover card's `max-w-72` plus its gap from the crosshair. With less room
-// than this to the right of the crosshair, the card opens on its left.
-const HOVER_CARD_ROOM_PX = 298;
-// Half the widest pointer-time tag ("Sep 27, 14:44"): nearer the plot's edge
-// than this, the tag aligns to the edge instead of centring on the crosshair,
-// and tick labels this close to it step aside.
-const TIME_TAG_HALF_PX = 48;
-
-export function runBarTone(run: TimelineRun, isPeak: boolean): string {
- if (run.active) return "bg-info animate-pulse";
- if (run.task.status === "failed") return "bg-destructive";
- if (run.task.status === "cancelled") return "bg-faint-foreground";
- return isPeak ? "bg-chart-1" : "bg-chart-2";
+type ChartView = "runs" | "cumulative";
+
+function RunCharts({ timeline }: { timeline: RunTimeline }) {
+ const { t } = useT("issues");
+ const [view, setView] = useState<ChartView>("runs");
+ const viewSwitch = (
+ <Segmented
+ label={t(($) => $.runs_timeline.view_label)}
+ value={view}
+ onChange={setView}
+ options={[
+ { value: "runs", label: t(($) => $.runs_timeline.view_runs) },
+ { value: "cumulative", label: t(($) => $.runs_timeline.view_cumulative) },
+ ]}
+ />
+ );
+ return view === "runs" ? (
+ <RunActivityChart timeline={timeline} viewSwitch={viewSwitch} />
+ ) : (
+ <RunCumulativeChart timeline={timeline} viewSwitch={viewSwitch} />
+ );
+}
+
+type Metric = "cost" | "tokens" | "time";
+
+interface Series {
+ key: string;
+ label: string;
+ swatch: string;
}
-interface ChartHover {
- /** The moment under the pointer, clamped to the stretch that holds runs. */
- t: number;
- /** The lane the pointer is over, if any. */
- lane?: string;
- /** The plot's rendered width, which turns pixels into time. */
- width: number;
+const PLOT_HEIGHT = 128;
+// A run that reported nothing for the metric still gets a mark, short enough
+// to never read as a small figure.
+const STUB_HEIGHT = 4;
+// The hover card's `max-w-72` plus its gap from the bar. With less room than
+// this to the right, the card opens on its left.
+const HOVER_CARD_ROOM_PX = 298;
+// Day labels closer than this share of the plot would collide; the later
+// day keeps its divider but drops its label.
+const MIN_DAY_LABEL_GAP = 0.1;
+const HOUR_MS = 60 * 60 * 1000;
+
+function swatchFor(index: number): string {
+ return SERIES_SWATCHES[index] ?? OTHERS_SWATCH;
}
-function RunTimelineChart({ timeline }: { timeline: RunTimeline }) {
+// One bar per run, oldest on the left, the same reading as the sidebar's
+// strip: the height is what the run cost, used or took, the colour who ran it
+// (or, for tokens, what kind they were), and a tick under the bar marks a run
+// that failed or was cancelled. Days are dividers rather than an axis — runs
+// cluster in bursts, and a time axis spends most of its width on the hours in
+// between where nothing ran.
+function RunActivityChart({
+ timeline,
+ viewSwitch,
+}: {
+ timeline: RunTimeline;
+ /** The dialog's chart switch, placed first in this chart's toolbar. */
+ viewSwitch: React.ReactNode;
+}) {
const { t } = useT("issues");
const locale = useLocale();
const { getActorName } = useActorName();
- const [d0, d1] = timeline.domain;
- // Without any usage there is no curve to draw; the lanes still show when
- // each run happened.
- const plotHeight = timeline.pricedCount > 0 ? PLOT_HEIGHT : 0;
- const xPct = (ms: number) => ((ms - d0) / (d1 - d0)) * 100;
+ const partLabel = useCostPartLabel();
+ const [metric, setMetric] = useState<Metric>("cost");
+ const runs = timeline.runs;
+ const n = runs.length;
+
+ // Agents in cost order, then any that ran without reporting usage.
+ const agentSwatch = useMemo(() => {
+ const keys = timeline.costByAgent.map((s) => s.key);
+ for (const lane of timeline.lanes) {
+ if (!keys.includes(lane.agentId)) keys.push(lane.agentId);
+ }
+ return new Map(keys.map((key, i) => [key, swatchFor(i)]));
+ }, [timeline]);
+
+ const series: Series[] = useMemo(() => {
+ if (metric === "tokens") {
+ return COST_PARTS.map((part) => ({ key: part.key, label: partLabel(part.key), swatch: part.swatch }));
+ }
+ const list: Series[] = [];
+ let others = false;
+ for (const [agentId, swatch] of agentSwatch) {
+ if (swatch === OTHERS_SWATCH) others = true;
+ else list.push({ key: agentId, label: getActorName("agent", agentId), swatch });
+ }
+ if (others) list.push({ key: OTHERS_KEY, label: t(($) => $.runs_timeline.others), swatch: OTHERS_SWATCH });
+ return list;
+ }, [metric, agentSwatch, getActorName, partLabel, t]);
- const yTicks = niceTicks(timeline.totalCost);
+ const valueOf = (run: TimelineRun) =>
+ metric === "cost" ? (run.usage?.cost ?? 0) : metric === "tokens" ? (run.usage?.tokens ?? 0) : (run.durationMs ?? 0);
+ const segmentsOf = (run: TimelineRun) =>
+ metric === "tokens"
+ ? COST_PARTS.map((part) => ({ key: part.key, swatch: part.swatch, value: run.usage?.[part.key] ?? 0 }))
+ : [{ key: "run", swatch: agentSwatch.get(run.task.agent_id) ?? OTHERS_SWATCH, value: valueOf(run) }];
+
+ const maxValue = Math.max(0, ...runs.map(valueOf));
+ // Agent time ticks in whole hours once a run takes an hour, else minutes.
+ const timeUnitMs = metric === "time" && maxValue < HOUR_MS ? 60_000 : HOUR_MS;
+ const yTicks =
+ metric === "time"
+ ? niceTicks(maxValue / timeUnitMs).map((v) => v * timeUnitMs)
+ : niceTicks(maxValue);
const yMax = yTicks[yTicks.length - 1] ?? 1;
- const yPct = (cost: number) => (1 - cost / yMax) * 100;
-
- const ticks = timeTicks(timeline.domain);
- const multiDay = d1 - d0 > 36 * 60 * 60 * 1000;
- const [tickFormat, pointerFormat] = useMemo(() => {
- const day = new Intl.DateTimeFormat(locale, { weekday: "short", month: "short", day: "numeric" });
- const hour = new Intl.DateTimeFormat(locale, { hour: "2-digit", minute: "2-digit", hour12: false });
- const dayHour = new Intl.DateTimeFormat(locale, {
- month: "short",
- day: "numeric",
- hour: "2-digit",
- minute: "2-digit",
- hour12: false,
+ const formatValue = (v: number) =>
+ metric === "cost"
+ ? formatTick(v)
+ : metric === "tokens"
+ ? formatTokens(v)
+ : `${Number((v / timeUnitMs).toPrecision(3))}${timeUnitMs === HOUR_MS ? "h" : "m"}`;
+
+ // Where each local day starts in the run sequence.
+ const dayMarks = useMemo(() => {
+ const today = new Date().toDateString();
+ const fmt = new Intl.DateTimeFormat(locale, { month: "short", day: "numeric" });
+ const marks: { index: number; label: string | null }[] = [];
+ let lastLabelled = -Infinity;
+ runs.forEach((run, i) => {
+ const day = new Date(run.startMs).toDateString();
+ if (i > 0 && day === new Date(runs[i - 1]!.startMs).toDateString()) return;
+ const labelled = (i - lastLabelled) / runs.length >= MIN_DAY_LABEL_GAP;
+ if (labelled) lastLabelled = i;
+ marks.push({
+ index: i,
+ label: labelled ? (day === today ? t(($) => $.runs_timeline.day_today) : fmt.format(run.startMs)) : null,
+ });
});
- return [
- (tick: (typeof ticks)[number]) => (tick.kind === "day" ? day.format(tick.t) : hour.format(tick.t)),
- (ms: number) => (multiDay ? dayHour.format(ms) : hour.format(ms)),
- ] as const;
- }, [locale, multiDay]);
-
- // Step curve in a 1000×100 box stretched over the plot; the stroke keeps its
- // 2px via non-scaling-stroke however wide the dialog is.
- const steps = timeline.cumulative;
- const { line, area } = stepCurvePath(steps, timeline.domain, yMax);
- const last = steps[steps.length - 1];
-
- // Label the one run that moved the curve most. Left of its step the curve is
- // lower (it only ever rises), so a label ending at the step's top-left
- // corner never sits on the line. Near the left edge there is no room for
- // that; right of the step the curve can still rise into anything above it,
- // so the label drops just below the line instead, into the area wash.
- const peak = timeline.peak;
- const peakStep = peak ? steps.find((s) => s.t === peak.endMs) : undefined;
- const peakX = peakStep ? xPct(peakStep.t) : 0;
-
- // Hover layer. The crosshair is the pointer: it follows it across the whole
- // chart row — lane labels and y scale included, so drifting a few pixels
- // off the plot does not drop the hover — clamped to the stretch that holds
- // runs. Whatever is under it answers: the run whose bar spans that moment,
- // or between runs, the quiet stretch and what the curve reads there. It used
- // to snap to the nearest run's end instead, which moved it hundreds of
- // pixels for a few pixels of pointer travel (MUL-7780). The list below
- // carries the same figures for keyboard and screen-reader users.
+ return marks;
+ }, [runs, locale, t]);
+
+ // Hover layer: the pointer picks the run whose slot it is over, anywhere in
+ // the chart row, so a run with no bar to aim at is still reachable. The
+ // list below carries the same figures for keyboard and screen-reader users.
const plotRef = useRef<HTMLDivElement>(null);
- const [hover, setHover] = useState<ChartHover | null>(null);
+ const [hover, setHover] = useState<{ index: number; width: number } | null>(null);
const trackPointer = (event: React.PointerEvent<HTMLDivElement>) => {
const rect = plotRef.current?.getBoundingClientRect();
if (!rect || rect.width <= 0) return;
- const [e0, e1] = timeline.extent;
- const at = d0 + ((event.clientX - rect.left) / rect.width) * (d1 - d0);
- // Over a lane, only that lane's runs are candidates — the pointer is on a
- // specific agent's row. Over the curve, any agent's run can answer.
- const lane = (event.target as Element).closest?.("[data-lane]")?.getAttribute("data-lane");
- setHover({ t: Math.min(Math.max(at, e0), e1), lane: lane ?? undefined, width: rect.width });
+ const index = Math.floor(((event.clientX - rect.left) / rect.width) * n);
+ setHover({ index: Math.min(Math.max(index, 0), n - 1), width: rect.width });
};
+ const hovered = hover ? runs[hover.index] : undefined;
+ const cardOnLeft = hover ? ((hover.index + 1) / n) * hover.width + HOVER_CARD_ROOM_PX > hover.width : false;
+ const slot = (i: number) => ({ left: `${(i / n) * 100}%`, width: `${100 / n}%` });
- const hoverIndex = hover
- ? runIndexAt(timeline.runs, hover.t, (HOVER_SLOP_PX / hover.width) * (d1 - d0), hover.lane)
- : -1;
- const hovered = hoverIndex >= 0 ? timeline.runs[hoverIndex] : undefined;
- const hoverX = hover ? xPct(hover.t) : 0;
- const hoverPx = hover ? (hoverX / 100) * hover.width : 0;
- // The point the card is about: the hovered run's step on the curve, or
- // between runs, the curve's reading under the crosshair. A run that has not
- // reported usage has no step to point at.
- const dot =
- !hover || plotHeight === 0
- ? null
- : hovered
- ? hovered.usage
- ? { x: xPct(hovered.endMs), cost: hovered.costSoFar }
- : null
- : { x: hoverX, cost: cumulativeCostAt(steps, hover.t) };
- // The card sits in whichever half of the plot its dot is not in, so it never
- // covers the point it describes.
- const cardTop = dot && yPct(dot.cost) < 50 ? Math.round(plotHeight * 0.4) : 0;
- const cardOnLeft = hover ? hoverPx + HOVER_CARD_ROOM_PX > hover.width : false;
- const tagTransform = !hover
- ? undefined
- : hoverPx < TIME_TAG_HALF_PX
- ? "none"
- : hoverPx > hover.width - TIME_TAG_HALF_PX
- ? "translateX(-100%)"
- : "translateX(-50%)";
+ const stackLabel =
+ metric === "tokens" ? t(($) => $.runs_timeline.stack_type) : t(($) => $.runs_timeline.stack_agent);
return (
- <div
- role="img"
- aria-label={t(($) => $.runs_timeline.chart_aria, {
- count: timeline.runs.length,
- cost: formatUsd(timeline.totalCost),
- })}
- className="mt-5 flex gap-3 border-b px-6 pb-3"
- onPointerMove={trackPointer}
- onPointerDown={trackPointer}
- onPointerLeave={() => setHover(null)}
- >
- {/* Lane labels, aligned with the lanes in the plot column. */}
- <div className="w-24 shrink-0" aria-hidden>
- <div style={{ height: plotHeight }} />
- <div className={cn(plotHeight > 0 && "mt-[9px]")}>
- {timeline.lanes.map((lane) => (
- <div key={lane.agentId} className="flex h-5 min-w-0 items-center gap-1.5">
- <ActorAvatar actorType="agent" actorId={lane.agentId} size="xs" />
- <span className="truncate text-micro text-muted-foreground">
- {getActorName("agent", lane.agentId)}
- </span>
- </div>
+ <div className="mt-5 border-b px-6 pb-3">
+ <div className="mb-3 flex flex-wrap items-center gap-x-3 gap-y-2">
+ {viewSwitch}
+ <Segmented
+ label={t(($) => $.runs_timeline.metric_label)}
+ value={metric}
+ onChange={setMetric}
+ options={[
+ { value: "cost", label: t(($) => $.runs_timeline.metric_cost) },
+ { value: "tokens", label: t(($) => $.runs_timeline.metric_tokens) },
+ { value: "time", label: t(($) => $.runs_timeline.metric_time) },
+ ]}
+ />
+ <span className="text-caption text-muted-foreground">
+ {t(($) => $.runs_timeline.unit_run)} · {stackLabel}
+ </span>
+ <div className="ml-auto flex flex-wrap items-center gap-x-3 gap-y-1 text-caption text-muted-foreground">
+ {series.map((s) => (
+ <span key={s.key} className="flex items-center gap-1.5">
+ <span aria-hidden className={cn("size-2 rounded-xs", s.swatch)} />
+ {s.label}
+ </span>
))}
</div>
</div>
- <div ref={plotRef} className="relative min-w-0 flex-1">
- {/* Time gridlines run through the curve and the lanes alike. */}
- {ticks.map((tick) => (
- <span
- key={tick.t}
- aria-hidden
- className="absolute top-0 bottom-5 w-px bg-border"
- style={{ left: `${xPct(tick.t)}%` }}
- />
- ))}
+ <div
+ role="img"
+ aria-label={t(($) => $.runs_timeline.chart_aria, {
+ count: n,
+ cost: formatUsd(timeline.totalCost),
+ })}
+ className="flex gap-3"
+ onPointerMove={trackPointer}
+ onPointerDown={trackPointer}
+ onPointerLeave={() => setHover(null)}
+ >
+ <div ref={plotRef} className="relative min-w-0 flex-1">
+ {/* Day dividers run through the bars and the status ticks alike. */}
+ {dayMarks
+ .filter((mark) => mark.index > 0)
+ .map((mark) => (
+ <span
+ key={mark.index}
+ aria-hidden
+ className="absolute top-0 bottom-5 w-px bg-border"
+ style={{ left: `${(mark.index / n) * 100}%` }}
+ />
+ ))}
- <div className="relative" style={{ height: plotHeight }} aria-hidden>
- {yTicks.map((v) => (
- <span
- key={v}
- className="absolute inset-x-0 h-px bg-border"
- style={{ top: `${yPct(v)}%` }}
- />
- ))}
- {steps.length > 0 && (
- <svg
- className="absolute inset-0 size-full overflow-visible"
- viewBox="0 0 1000 100"
- preserveAspectRatio="none"
- >
- <path d={area} fill="var(--chart-1)" fillOpacity={0.1} />
- <path
- d={line}
- fill="none"
- stroke="var(--chart-1)"
- strokeWidth={2}
- strokeLinejoin="round"
- vectorEffect="non-scaling-stroke"
+ <div className="relative" style={{ height: PLOT_HEIGHT }} aria-hidden>
+ {yTicks.map((v) => (
+ <span
+ key={v}
+ className="absolute inset-x-0 h-px bg-border"
+ style={{ top: `${(1 - v / yMax) * 100}%` }}
/>
- </svg>
- )}
- {last && (
- <span
- className="absolute size-2 -translate-x-1/2 -translate-y-1/2 rounded-full bg-chart-1 ring-2 ring-popover"
- style={{ left: `${xPct(last.t)}%`, top: `${yPct(last.cost)}%` }}
- />
- )}
- {dot && (
- <span
- className="pointer-events-none absolute z-10 size-2.5 -translate-x-1/2 -translate-y-1/2 rounded-full bg-chart-1 ring-2 ring-popover"
- style={{ left: `${dot.x}%`, top: `${yPct(dot.cost)}%` }}
- />
- )}
- {/* Fades rather than unmounts under the hover card, so entering and
- leaving the chart does not blink it. */}
- {peak && peakStep && (
- <PeakLabel
- run={peak}
- className={cn("transition-opacity duration-150", hover && "opacity-0")}
- style={{
- left: `${peakX}%`,
- top: `${yPct(peakStep.cost)}%`,
- transform:
- peakX >= 30
- ? "translate(calc(-100% - 6px), calc(-100% - 2px))"
- : "translate(6px, 4px)",
- }}
- />
- )}
- </div>
+ ))}
+ {runs.map((run, i) => {
+ const total = valueOf(run);
+ const dimmed = hovered && hovered !== run;
+ return (
+ <span key={run.task.id} className="absolute inset-y-0 flex items-end justify-center" style={slot(i)}>
+ {total > 0 ? (
+ <span
+ data-run={run.task.id}
+ className={cn(
+ "flex w-[70%] max-w-10 min-w-px flex-col-reverse gap-px overflow-hidden rounded-t-xs transition-opacity",
+ dimmed && "opacity-35",
+ )}
+ style={{ height: Math.max(2, (total / yMax) * PLOT_HEIGHT) }}
+ >
+ {segmentsOf(run).map((s, _, all) =>
+ s.value > 0 ? (
+ <span
+ key={s.key}
+ className={cn("min-h-px", s.swatch)}
+ style={shareStyle(s.value, sumOf(all.map((x) => x.value)))}
+ />
+ ) : null,
+ )}
+ </span>
+ ) : (
+ <span
+ data-run={run.task.id}
+ className={cn(
+ "w-[70%] max-w-10 min-w-px rounded-t-xs transition-opacity",
+ run.active
+ ? "bg-info animate-pulse"
+ : "border border-b-0 border-dashed border-faint-foreground",
+ dimmed && "opacity-35",
+ )}
+ style={{ height: STUB_HEIGHT }}
+ />
+ )}
+ </span>
+ );
+ })}
+ </div>
- {/* Rows, not tracks, carry `data-lane`, and they touch: moving from one
- lane to the next never crosses a gap that belongs to no lane, which
- would briefly hand the hover to every agent's runs. */}
- <div className={cn(plotHeight > 0 && "mt-[9px]")}>
- {timeline.lanes.map((lane) => (
- <div key={lane.agentId} data-lane={lane.agentId} className="py-[3px]">
- <div className="relative h-3.5 rounded-xs bg-muted/60">
- {lane.runs.map((run) => (
+ {/* How a run ended, under its bar: the bar itself carries who ran it. */}
+ <div className="relative mt-1 h-1" aria-hidden>
+ {runs.map((run, i) =>
+ run.task.status === "failed" || run.task.status === "cancelled" ? (
+ <span key={run.task.id} className="absolute inset-y-0 flex justify-center" style={slot(i)}>
<span
- key={run.task.id}
className={cn(
- "absolute inset-y-0.5 min-w-[3px] rounded-xs transition-opacity",
- runBarTone(run, run === peak),
- hovered && run !== hovered && "opacity-35",
+ "h-full w-[70%] max-w-10 min-w-px rounded-full",
+ run.task.status === "failed" ? "bg-destructive" : "bg-faint-foreground",
)}
- style={{
- left: `${xPct(run.startMs)}%`,
- width: `${xPct(run.endMs) - xPct(run.startMs)}%`,
- }}
/>
- ))}
- </div>
- </div>
- ))}
- </div>
+ </span>
+ ) : null,
+ )}
+ </div>
- {hover && (
- <>
- <span
- aria-hidden
- className="pointer-events-none absolute top-0 bottom-5 w-px bg-foreground/30"
- style={{ left: `${hoverX}%` }}
- />
- {/* Beside the crosshair, on whichever side has room. */}
+ {hovered && hover && (
<div
aria-hidden
data-hover-card
- className="pointer-events-none absolute z-20 w-max max-w-72 rounded-lg border bg-popover px-2.5 py-1.5 text-caption text-popover-foreground shadow-[var(--menu-shadow)]"
+ className="pointer-events-none absolute top-0 z-20 w-max max-w-72 rounded-lg border bg-popover px-2.5 py-1.5 text-caption text-popover-foreground shadow-[var(--menu-shadow)]"
style={{
- left: `${hoverX}%`,
- top: cardTop,
- transform: cardOnLeft ? "translateX(calc(-100% - 10px))" : "translateX(10px)",
+ left: `${((cardOnLeft ? hover.index : hover.index + 1) / n) * 100}%`,
+ transform: cardOnLeft ? "translateX(calc(-100% - 8px))" : "translateX(8px)",
}}
>
- {hovered ? (
- <RunHoverCard run={hovered} />
- ) : (
- <IdleHoverCard
- {...idleSpanAround(timeline.runs, hover.t, hover.lane)}
- total={timeline.pricedCount > 0 ? cumulativeCostAt(steps, hover.t) : null}
- />
- )}
+ <RunHoverCard run={hovered} parts={metric === "tokens"} />
</div>
- </>
- )}
-
- <div className="relative mt-px h-5" aria-hidden>
- {ticks.map((tick) => {
- const x = xPct(tick.t);
- // The pointer's own time tag takes the axis where it stands.
- if (hover && Math.abs(((x - hoverX) / 100) * hover.width) < TIME_TAG_HALF_PX) return null;
- return (
- <span
- key={tick.t}
- className="absolute top-1 whitespace-nowrap px-1 text-micro text-muted-foreground"
- style={{ left: `${x}%`, transform: x > 92 ? "translateX(-100%)" : undefined }}
- >
- {tickFormat(tick)}
- </span>
- );
- })}
- {hover && (
- <span
- className="pointer-events-none absolute top-0.5 z-20 whitespace-nowrap rounded-xs bg-foreground px-1 text-micro font-medium tabular-nums text-background"
- style={{ left: `${hoverX}%`, transform: tagTransform }}
- >
- {pointerFormat(hover.t)}
- </span>
)}
+
+ <div className="relative mt-px h-5" aria-hidden>
+ {dayMarks.map((mark) =>
+ mark.label ? (
+ <span
+ key={mark.index}
+ className="absolute top-1 whitespace-nowrap px-1 text-micro text-muted-foreground"
+ style={{
+ left: `${(mark.index / n) * 100}%`,
+ transform: mark.index / n > 0.9 ? "translateX(-100%)" : undefined,
+ }}
+ >
+ {mark.label}
+ </span>
+ ) : null,
+ )}
+ </div>
</div>
- </div>
- {/* Y scale on the right, where the curve ends; the end value is the
- one figure labelled in full. */}
- <div className="relative w-12 shrink-0 text-micro tabular-nums" style={{ height: plotHeight }} aria-hidden>
- {yTicks.map((v) =>
- last && Math.abs(yPct(v) - yPct(last.cost)) < 12 ? null : (
+ <div className="relative w-12 shrink-0 text-micro tabular-nums" style={{ height: PLOT_HEIGHT }} aria-hidden>
+ {yTicks.map((v) => (
<span
key={v}
className="absolute left-1 -translate-y-1/2 text-muted-foreground"
- style={{ top: `${yPct(v)}%` }}
+ style={{ top: `${(1 - v / yMax) * 100}%` }}
>
- {formatTick(v)}
+ {formatValue(v)}
</span>
- ),
- )}
- {last && (
- <span
- className="absolute left-1 -translate-y-1/2 font-medium text-foreground"
- style={{ top: `${yPct(last.cost)}%` }}
- >
- {formatUsd(last.cost)}
- </span>
- )}
+ ))}
+ </div>
</div>
</div>
);
}
-// Axis steps are round numbers; "$50.00" would print noise the curve's end
-// label, which keeps full precision, does not need.
+// Axis steps are round numbers; "$50.00" would print noise a tick does not need.
function formatTick(v: number): string {
return Number.isInteger(v) ? `$${v}` : formatUsd(v);
}
-/**
- * A run's trigger, with a wakeup run naming its rule's condition ("Wakeup ·
- * When a linked PR's CI finishes") the way the execution log's rows do. The
- * rule lookup mounts only for wakeup runs.
- */
-export function RunTriggerLabel({
- task,
- fallback,
- children,
-}: {
- task: AgentTask;
- fallback: string;
- children: (label: string) => React.ReactNode;
-}) {
- if (!task.wakeup_id) return <>{children(fallback)}</>;
- return <WakeupRunLabel task={task} fallback={fallback} render={children} />;
-}
-
-function PeakLabel({
- run,
- className,
- style,
-}: {
- run: TimelineRun;
- className?: string;
- style: React.CSSProperties;
-}) {
- const trigger = useTriggerText(run.task);
- return (
- <span
- className={cn("absolute flex max-w-60 items-baseline gap-1 whitespace-nowrap text-micro", className)}
- style={style}
- >
- <span className="font-medium text-foreground">+{formatUsd(run.usage?.cost ?? 0)}</span>
- <RunTriggerLabel task={run.task} fallback={trigger}>
- {(label) => <span className="truncate text-muted-foreground">{label}</span>}
- </RunTriggerLabel>
- </span>
- );
-}
-
-function RunHoverCard({ run }: { run: TimelineRun }) {
+function RunHoverCard({ run, parts }: { run: TimelineRun; parts: boolean }) {
const { t } = useT("issues");
+ const partLabel = useCostPartLabel();
const { getActorName } = useActorName();
const trigger = useTriggerText(run.task);
const status = useStatusLabel(run.task.status);
@@ -637,69 +616,131 @@ function RunHoverCard({ run }: { run: TimelineRun }) {
<span className="truncate">{[getActorName("agent", run.task.agent_id), ...facts].join(" · ")}</span>
</span>
<span className="text-micro tabular-nums">
- <span className="font-medium">
- {run.usage ? formatUsd(run.usage.cost) : t(($) => $.runs_timeline.no_usage)}
- </span>
- <span className="text-muted-foreground">
- {" · "}
- {t(($) => $.runs_timeline.tooltip_total, { cost: formatUsd(run.costSoFar) })}
- </span>
+ {run.usage ? (
+ <>
+ <span className="font-medium">{formatUsd(run.usage.cost)}</span>
+ <span className="text-muted-foreground">
+ {" · "}
+ {t(($) => $.runs_timeline.tokens_count, { tokens: formatTokens(run.usage.tokens) })}
+ </span>
+ </>
+ ) : (
+ <span className="text-muted-foreground">{t(($) => $.runs_timeline.no_usage)}</span>
+ )}
</span>
+ {parts &&
+ run.usage &&
+ COST_PARTS.map((part) =>
+ run.usage![part.key] > 0 ? (
+ <span key={part.key} className="flex items-center gap-1.5 text-micro tabular-nums">
+ <span aria-hidden className={cn("size-2 shrink-0 rounded-xs", part.swatch)} />
+ <span className="min-w-0 flex-1 truncate text-muted-foreground">{partLabel(part.key)}</span>
+ <span className="font-medium">{formatTokens(run.usage![part.key])}</span>
+ </span>
+ ) : null,
+ )}
</div>
);
}
-// Between runs: nothing ran here. Says so, with how long the quiet lasted and
-// what the issue had spent by then — the curve's reading under the crosshair.
-function IdleHoverCard({
- fromMs,
- toMs,
+// ─── Cost split ────────────────────────────────────────────────────────────
+
+function CostSplit({ timeline }: { timeline: RunTimeline }) {
+ const { t } = useT("issues");
+ const { getActorName } = useActorName();
+ return (
+ <div className="grid grid-cols-1 gap-x-8 gap-y-3 border-b px-6 py-3 sm:grid-cols-2">
+ <ShareBand
+ title={t(($) => $.runs_timeline.by_agent)}
+ shares={timeline.costByAgent}
+ total={timeline.totalCost}
+ label={(key) => getActorName("agent", key)}
+ />
+ <ShareBand
+ title={t(($) => $.runs_timeline.by_model)}
+ shares={timeline.costByModel}
+ total={timeline.totalCost}
+ label={shortModelName}
+ hint={(key) => key}
+ />
+ </div>
+ );
+}
+
+function ShareBand({
+ title,
+ shares,
total,
+ label,
+ hint,
}: {
- fromMs: number | null;
- toMs: number | null;
- /** Null when no run reported usage — there is no total to quote. */
- total: number | null;
+ title: string;
+ shares: CostShare[];
+ total: number;
+ label: (key: string) => string;
+ /** Native tooltip for an entry, when its label shortens the key. */
+ hint?: (key: string) => string;
}) {
const { t } = useT("issues");
- const locale = useLocale();
- const span = useMemo(() => {
- if (fromMs == null || toMs == null) return null;
- const sameDay = new Date(fromMs).toDateString() === new Date(toMs).toDateString();
- const fmt = new Intl.DateTimeFormat(locale, {
- ...(sameDay ? {} : { month: "short", day: "numeric" }),
- hour: "2-digit",
- minute: "2-digit",
- hour12: false,
- });
- return `${fmt.format(fromMs)} → ${fmt.format(toMs)}`;
- }, [fromMs, toMs, locale]);
+ const percent = usePercent();
+ const named = shares.slice(0, SERIES_SWATCHES.length);
+ const rest = shares.slice(SERIES_SWATCHES.length);
+ const entries = [
+ ...named.map((s, i) => ({ key: s.key, name: label(s.key), hint: hint?.(s.key), cost: s.cost, swatch: swatchFor(i) })),
+ ...(rest.length > 0
+ ? [{
+ key: OTHERS_KEY,
+ name: t(($) => $.runs_timeline.others),
+ hint: undefined,
+ cost: rest.reduce((sum, s) => sum + s.cost, 0),
+ swatch: OTHERS_SWATCH,
+ }]
+ : []),
+ ].filter((e) => e.cost > 0);
+ if (entries.length === 0) return null;
+ const entriesTotal = sumOf(entries.map((e) => e.cost));
+
return (
- <div className="flex min-w-0 flex-col gap-1">
- <span className="font-medium">{t(($) => $.runs_timeline.hover_no_run)}</span>
- {span && fromMs != null && toMs != null && (
- <span className="truncate text-micro tabular-nums text-muted-foreground">
- {span} ·{" "}
- {t(($) => $.runs_timeline.hover_idle, {
- duration: formatDuration((toMs - fromMs) / 1000, UNDER_A_SECOND),
- })}
- </span>
- )}
- {total != null && (
- <span className="text-micro tabular-nums text-muted-foreground">
- {t(($) => $.runs_timeline.tooltip_total, { cost: formatUsd(total) })}
- </span>
- )}
- </div>
+ <section aria-label={title} className="min-w-0">
+ <div className="text-micro font-medium uppercase tracking-wider text-muted-foreground">{title}</div>
+ <div aria-hidden className="mt-1.5 mb-1.5 flex h-1.5 gap-0.5 overflow-hidden rounded-full">
+ {entries.map((e) => (
+ <span key={e.key} className={e.swatch} style={shareStyle(e.cost, entriesTotal)} />
+ ))}
+ </div>
+ <div className="flex flex-wrap gap-x-3 gap-y-0.5 text-caption tabular-nums text-muted-foreground">
+ {entries.map((e) => (
+ <span key={e.key} className="flex min-w-0 items-center gap-1.5" title={e.hint}>
+ <span aria-hidden className={cn("size-2 shrink-0 rounded-xs", e.swatch)} />
+ <span className="truncate text-foreground">{e.name}</span>
+ <span>{formatUsd(e.cost)}</span>
+ <span className="text-faint-foreground">{percent(total > 0 ? e.cost / total : 0)}</span>
+ </span>
+ ))}
+ </div>
+ </section>
);
}
// ─── List ──────────────────────────────────────────────────────────────────
+// Column widths shared by the header and every row.
+const COL = {
+ time: "w-10 shrink-0",
+ attribution: "w-4 shrink-0",
+ arrow: "w-3 shrink-0",
+ agent: "w-24 shrink-0",
+ model: "w-24 shrink-0",
+ status: "w-20 shrink-0",
+ tokens: "w-14 shrink-0 text-right",
+ cost: "w-14 shrink-0 text-right",
+ actions: "w-14 shrink-0",
+ toggle: "w-6 shrink-0",
+} as const;
+
function RunDayList({ timeline, issueId }: { timeline: RunTimeline; issueId: string }) {
const { t } = useT("issues");
const locale = useLocale();
- const partLabel = useCostPartLabel();
const groups = useMemo(() => groupRunsByDay(timeline.runs), [timeline.runs]);
const dayLabel = useMemo(() => {
@@ -717,61 +758,71 @@ function RunDayList({ timeline, issueId }: { timeline: RunTimeline; issueId: str
return (
<div>
- {timeline.pricedCount > 0 && (
- <div className="flex justify-end gap-3 pt-3 text-micro text-muted-foreground">
- {COST_PARTS.map((part) => (
- <span key={part.key} className="flex items-center gap-1.5">
- <span aria-hidden className={cn("size-2 rounded-xs", part.swatch)} />
- {partLabel(part.key)}
- </span>
- ))}
- </div>
- )}
- {groups.map((group) => (
- <section key={group.dayMs} aria-label={dayLabel(group.dayMs)}>
- <div className="flex items-baseline gap-2 border-b pt-4 pb-1.5 text-micro text-muted-foreground">
- <span className="font-medium uppercase tracking-wider text-foreground">
- {dayLabel(group.dayMs)}
- </span>
- <span className="ml-auto tabular-nums">
- {[
- t(($) => $.runs_timeline.day_runs, { count: group.runs.length }),
- group.agentMs > 0 ? formatDuration(group.agentMs / 1000, UNDER_A_SECOND) : null,
- group.runs.some((r) => r.usage) ? formatUsd(group.cost) : null,
- ]
- .filter(Boolean)
- .join(" · ")}
- </span>
- </div>
- {group.runs.map((run) => (
- <RunListRow
- key={run.task.id}
- run={run}
- issueId={issueId}
- maxCost={timeline.maxRunCost}
- />
- ))}
- </section>
- ))}
+ <div
+ aria-hidden
+ className="sticky top-0 z-10 flex h-8 items-center gap-2 border-b bg-popover text-micro font-medium text-muted-foreground"
+ >
+ <span className={COL.time}>{t(($) => $.runs_timeline.col_time)}</span>
+ <span className={COL.attribution} />
+ <span className="min-w-0 flex-1">{t(($) => $.runs_timeline.col_trigger)}</span>
+ <span className={COL.arrow} />
+ <span className={COL.agent}>{t(($) => $.runs_timeline.col_agent)}</span>
+ <span className={COL.model}>{t(($) => $.runs_timeline.col_model)}</span>
+ <span className={COL.status}>{t(($) => $.runs_timeline.col_duration)}</span>
+ <span className={COL.tokens}>{t(($) => $.runs_timeline.col_tokens)}</span>
+ <span className={COL.cost}>{t(($) => $.runs_timeline.col_cost)}</span>
+ <span className={COL.actions} />
+ <span className={COL.toggle} />
+ </div>
+ {groups.map((group) => {
+ const priced = group.runs.some((r) => r.usage);
+ return (
+ <section key={group.dayMs} aria-label={dayLabel(group.dayMs)}>
+ <div className="flex items-baseline gap-2 border-b pt-4 pb-1.5 text-micro text-muted-foreground">
+ <span className="font-medium uppercase tracking-wider text-foreground">
+ {dayLabel(group.dayMs)}
+ </span>
+ <span className="ml-auto tabular-nums">
+ {[
+ t(($) => $.runs_timeline.day_runs, { count: group.runs.length }),
+ group.agentMs > 0 ? formatDuration(group.agentMs / 1000, UNDER_A_SECOND) : null,
+ priced ? t(($) => $.runs_timeline.tokens_count, { tokens: formatTokens(group.tokens) }) : null,
+ priced ? formatUsd(group.cost) : null,
+ ]
+ .filter(Boolean)
+ .join(" · ")}
+ </span>
+ </div>
+ {group.runs.map((run) => (
+ <RunListRow key={run.task.id} run={run} issueId={issueId} />
+ ))}
+ </section>
+ );
+ })}
</div>
);
}
-function RunListRow({
- run,
- issueId,
- maxCost,
-}: {
- run: TimelineRun;
- issueId: string;
- maxCost: number;
-}) {
- const { t } = useT("issues");
+function useStatusReason(task: AgentTask): string | null {
const { t: tAgents } = useT("agents");
+ // Same localized reason the sidebar rows show — never the raw `task.error`,
+ // which is operator-facing English (#7411).
+ const reason =
+ task.status === "failed"
+ ? failureReasonLabel(task.failure_reason, tAgents)
+ : cancelReasonLabel(task, tAgents);
+ const cancelledBy = cancellationActorLabel(task, tAgents);
+ return [cancelledBy, reason].filter(Boolean).join(" · ") || null;
+}
+
+function RunListRow({ run, issueId }: { run: TimelineRun; issueId: string }) {
+ const { t } = useT("issues");
const locale = useLocale();
const { getActorName } = useActorName();
+ const [expanded, setExpanded] = useState(false);
const trigger = useTriggerText(run.task);
const statusLabel = useStatusLabel(run.task.status);
+ const reason = useStatusReason(run.task);
const task = run.task;
const time = new Intl.DateTimeFormat(locale, {
hour: "2-digit",
@@ -782,184 +833,236 @@ function RunListRow({
// (assignment, autopilot, retry labels) read as plain labels, and so do
// wakeup runs, whose comment id points at the thread the rule lives in.
const quoted = !task.wakeup_id && !!task.trigger_summary && !!task.trigger_comment_id;
- // Same localized reason the sidebar rows hover with — never the raw
- // `task.error`, which is operator-facing English (#7411).
- const reason =
- task.status === "failed"
- ? failureReasonLabel(task.failure_reason, tAgents)
- : cancelReasonLabel(task, tAgents);
- const cancelledBy = cancellationActorLabel(task, tAgents);
- const statusTitle = [cancelledBy, reason].filter(Boolean).join(" · ") || statusLabel;
const agentName = getActorName("agent", task.agent_id);
const label = quoted ? t(($) => $.runs_timeline.quoted, { text: trigger }) : trigger;
+ const model = run.usage?.models[0];
+ const detailsId = `run-details-${task.id}`;
return (
- <div className="group/run-row flex h-9 items-center gap-2.5 border-b text-caption transition-colors hover:bg-accent/40">
- <span className="w-10 shrink-0 font-mono text-micro tabular-nums text-muted-foreground">
- {time}
- </span>
- <span className="flex w-4 shrink-0 justify-center">
- <AttributionBadge attribution={task.attribution} variant="avatar" />
- </span>
- {/* One line keeps the list scannable; the full text is in the native
- tooltip and, whole and wrapped, at the top of the transcript. */}
- <RunTriggerLabel task={task} fallback={label}>
- {(text) => (
- <span
- title={text}
- className={cn(
- "min-w-0 flex-1 truncate text-label",
- run.usage || run.active ? "text-foreground" : "text-muted-foreground",
- )}
- >
- {text}
- </span>
- )}
- </RunTriggerLabel>
- <ArrowRight aria-hidden className="size-3 shrink-0 text-faint-foreground" />
- <span className="flex w-28 shrink-0 items-center gap-1.5">
- <ActorAvatar actorType="agent" actorId={task.agent_id} size="xs" enableHoverCard />
- <span className="truncate">{agentName}</span>
- </span>
- <span className="flex w-24 shrink-0 items-center gap-1" title={statusTitle}>
- {run.active ? (
- <span className="flex items-center gap-1 text-info">
- <span className="size-1.5 rounded-full bg-info" />
- {statusLabel}
- </span>
- ) : task.status === "failed" ? (
- <span className="flex items-center gap-1 text-destructive">
- <XCircle aria-hidden className="size-3.5 shrink-0" />
- {statusLabel}
- </span>
- ) : task.status === "cancelled" ? (
- <span className="flex items-center gap-1 text-muted-foreground">
- <Ban aria-hidden className="size-3.5 shrink-0" />
- {statusLabel}
- </span>
- ) : (
+ <div className={cn("border-b", expanded && "bg-accent/40")}>
+ <div className="group/run-row flex h-9 items-center gap-2 text-caption transition-colors hover:bg-accent/40">
+ <span className={cn(COL.time, "font-mono text-micro tabular-nums text-muted-foreground")}>
+ {time}
+ </span>
+ <span className={cn(COL.attribution, "flex justify-center")}>
+ <AttributionBadge attribution={task.attribution} variant="avatar" />
+ </span>
+ {/* One line keeps the list scannable; the full text is in the native
+ tooltip and, whole and wrapped, at the top of the transcript. */}
+ <RunTriggerLabel task={task} fallback={label}>
+ {(text) => (
+ <span
+ title={text}
+ className={cn(
+ "min-w-0 flex-1 truncate text-label",
+ run.usage || run.active ? "text-foreground" : "text-muted-foreground",
+ )}
+ >
+ {text}
+ </span>
+ )}
+ </RunTriggerLabel>
+ <ArrowRight aria-hidden className={cn(COL.arrow, "size-3 text-faint-foreground")} />
+ <span className={cn(COL.agent, "flex items-center gap-1.5")}>
+ <ActorAvatar actorType="agent" actorId={task.agent_id} size="xs" enableHoverCard />
+ <span className="truncate">{agentName}</span>
+ </span>
+ <span className={cn(COL.model, "min-w-0")}>
+ {model ? (
+ <span
+ title={run.usage!.models.join(", ")}
+ className="inline-block max-w-full truncate rounded-xs bg-muted px-1.5 py-0.5 align-middle text-micro text-muted-foreground"
+ >
+ {shortModelName(model)}
+ </span>
+ ) : (
+ <span className="text-faint-foreground">—</span>
+ )}
+ </span>
+ <span className={cn(COL.status, "flex items-center gap-1")} title={reason ?? statusLabel}>
+ {run.active ? (
+ <span className="flex items-center gap-1 text-info">
+ <span className="size-1.5 rounded-full bg-info" />
+ {statusLabel}
+ </span>
+ ) : task.status === "failed" ? (
+ <span className="flex min-w-0 items-center gap-1 text-destructive">
+ <XCircle aria-hidden className="size-3.5 shrink-0" />
+ <span className="truncate">{statusLabel}</span>
+ </span>
+ ) : task.status === "cancelled" ? (
+ <span className="flex min-w-0 items-center gap-1 text-muted-foreground">
+ <Ban aria-hidden className="size-3.5 shrink-0" />
+ <span className="truncate">{statusLabel}</span>
+ </span>
+ ) : (
+ <>
+ <span className="tabular-nums text-muted-foreground">
+ {run.durationMs != null ? formatDuration(run.durationMs / 1000, UNDER_A_SECOND) : "—"}
+ </span>
+ <span className="sr-only">{statusLabel}</span>
+ </>
+ )}
+ </span>
+ {run.usage ? (
<>
- <span className="tabular-nums text-muted-foreground">
- {run.durationMs != null ? formatDuration(run.durationMs / 1000, UNDER_A_SECOND) : "—"}
+ <span className={cn(COL.tokens, "tabular-nums text-muted-foreground")}>
+ {formatTokens(run.usage.tokens)}
</span>
- <span className="sr-only">{statusLabel}</span>
+ <span className={cn(COL.cost, "font-medium tabular-nums")}>{formatUsd(run.usage.cost)}</span>
</>
- )}
- </span>
- <span className="flex w-36 shrink-0 items-center justify-end gap-2">
- {run.usage && run.breakdown ? (
- <CostCell run={run} maxCost={maxCost} />
) : (
// No figure is not zero: a run without usage data was not free.
- <span className="text-faint-foreground" title={t(($) => $.runs_timeline.no_usage)}>
- —
- </span>
+ <>
+ <span className={cn(COL.tokens, "text-faint-foreground")}>—</span>
+ <span className={cn(COL.cost, "text-faint-foreground")} title={t(($) => $.runs_timeline.no_usage)}>
+ —
+ </span>
+ </>
)}
- </span>
- <span className="flex w-14 shrink-0 items-center justify-end gap-0.5 [@media(hover:hover)]:opacity-0 [@media(hover:hover)]:group-hover/run-row:opacity-100 [@media(hover:hover)]:focus-within:opacity-100">
- <TranscriptButton
- task={task}
- agentName={agentName}
- isLive={task.status === "running"}
- title={t(($) => $.execution_log.transcript_tooltip)}
- />
- {canRetryRun(task) && <RetryRunButton task={task} issueId={issueId} />}
- </span>
+ <span className={cn(COL.actions, "flex items-center justify-end gap-0.5 [@media(hover:hover)]:opacity-0 [@media(hover:hover)]:group-hover/run-row:opacity-100 [@media(hover:hover)]:focus-within:opacity-100")}>
+ <TranscriptButton
+ task={task}
+ agentName={agentName}
+ isLive={task.status === "running"}
+ title={t(($) => $.execution_log.transcript_tooltip)}
+ />
+ {canRetryRun(task) && <RetryRunButton task={task} issueId={issueId} />}
+ </span>
+ <span className={cn(COL.toggle, "flex justify-end")}>
+ <button
+ type="button"
+ aria-expanded={expanded}
+ aria-controls={detailsId}
+ aria-label={t(($) => $.runs_timeline.details_toggle)}
+ onClick={() => setExpanded((v) => !v)}
+ className="flex size-6 items-center justify-center rounded-xs text-muted-foreground transition-colors outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50"
+ >
+ <ChevronRight aria-hidden className={cn("size-3.5 transition-transform", expanded && "rotate-90")} />
+ </button>
+ </span>
+ </div>
+ {expanded && <RunDetails id={detailsId} run={run} reason={reason} />}
</div>
);
}
-function CostCell({ run, maxCost }: { run: TimelineRun; maxCost: number }) {
+function RunDetails({ id, run, reason }: { id: string; run: TimelineRun; reason: string | null }) {
const { t } = useT("issues");
+ const locale = useLocale();
const partLabel = useCostPartLabel();
- const usage = run.usage!;
- const breakdown = run.breakdown!;
- const share = maxCost > 0 ? (usage.cost / maxCost) * 100 : 0;
- const tokenCount: Record<CostPartKey, number> = {
- input: usage.input,
- output: usage.output,
- cacheRead: usage.cacheRead,
- cacheWrite: usage.cacheWrite,
- };
+ const percent = usePercent();
+ const statusLabel = useStatusLabel(run.task.status);
+ const usage = run.usage;
+ const breakdown = run.breakdown;
+ const hit = usage ? cacheHitRate(usage) : null;
+ const hm = new Intl.DateTimeFormat(locale, { hour: "2-digit", minute: "2-digit", hour12: false });
+ const tokenCount: Record<CostPartKey, number> = usage
+ ? { input: usage.input, output: usage.output, cacheRead: usage.cacheRead, cacheWrite: usage.cacheWrite }
+ : { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
+ const statusTone =
+ run.task.status === "failed"
+ ? "text-destructive"
+ : run.active
+ ? "text-info"
+ : undefined;
- // A real button, not a hover-only tooltip: the split is the detail the old
- // table's four token columns carried, so keyboard and touch users need a way
- // to it too. Pointer users still get it on hover.
return (
- <Popover>
- <PopoverTrigger
- openOnHover
- delay={150}
- render={
- <button
- type="button"
- aria-label={t(($) => $.runs_timeline.cost_breakdown_aria, { cost: formatUsd(usage.cost) })}
- />
- }
- className="flex items-center justify-end gap-2 rounded-xs outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
- >
- <span className="flex w-20 justify-start">
- <CostBar breakdown={breakdown} total={usage.cost} widthPx={(share / 100) * COST_TRACK_PX} />
- </span>
- <span className="w-14 text-right font-medium tabular-nums">{formatUsd(usage.cost)}</span>
- </PopoverTrigger>
- <PopoverContent side="top" align="end" className="w-72 gap-1 text-caption">
- {COST_PARTS.map((part) => (
- <span key={part.key} className="flex items-center gap-2 tabular-nums">
- <span aria-hidden className={cn("size-2 shrink-0 rounded-xs", part.swatch)} />
- <span className="flex-1 text-muted-foreground">{partLabel(part.key)}</span>
- <span className="w-14 text-right text-muted-foreground">
- {formatTokens(tokenCount[part.key])}
- </span>
- <span className="w-14 text-right font-medium">{formatUsd(breakdown[part.key])}</span>
- </span>
- ))}
- {usage.models.length > 0 && (
- <span className="mt-1 border-t pt-1 text-micro text-muted-foreground">
- {usage.models.join(", ")}
- </span>
+ <div id={id} className="grid grid-cols-1 gap-x-8 gap-y-4 px-3 pt-2 pb-4 pl-[4.5rem] text-caption md:grid-cols-[minmax(0,1fr)_16rem]">
+ {usage && breakdown ? (
+ <div className="min-w-0">
+ <div className="mb-2 text-micro font-medium uppercase tracking-wider text-muted-foreground">
+ {t(($) => $.runs_timeline.detail_breakdown)}
+ </div>
+ <div aria-hidden className="mb-2.5 flex h-1.5 gap-0.5 overflow-hidden rounded-full">
+ {COST_PARTS.map((part) =>
+ breakdown[part.key] > 0 ? (
+ <span
+ key={part.key}
+ className={part.swatch}
+ style={shareStyle(breakdown[part.key], sumOf(COST_PARTS.map((p) => breakdown[p.key])))}
+ />
+ ) : null,
+ )}
+ </div>
+ <div className="grid grid-cols-[auto_minmax(0,1fr)_auto_auto_auto] items-center gap-x-3 gap-y-1 tabular-nums">
+ {COST_PARTS.map((part) => (
+ <RunDetailPart
+ key={part.key}
+ swatch={part.swatch}
+ label={partLabel(part.key)}
+ tokens={tokenCount[part.key]}
+ cost={breakdown[part.key]}
+ share={usage.cost > 0 ? percent(breakdown[part.key] / usage.cost) : ""}
+ />
+ ))}
+ <span />
+ <span className="font-medium">{t(($) => $.runs_timeline.detail_total)}</span>
+ <span className="text-right font-medium">{formatTokens(usage.tokens)}</span>
+ <span className="w-14 text-right font-semibold">{formatUsd(usage.cost)}</span>
+ <span />
+ </div>
+ </div>
+ ) : (
+ <p className="text-muted-foreground">{t(($) => $.runs_timeline.no_usage)}</p>
+ )}
+ <dl className="grid grid-cols-[auto_minmax(0,1fr)] content-start gap-x-3 gap-y-1">
+ <dt className="text-muted-foreground">{t(($) => $.runs_timeline.detail_status)}</dt>
+ <dd className={cn("min-w-0", statusTone)}>{[statusLabel, reason].filter(Boolean).join(" · ")}</dd>
+ {usage && usage.models.length > 0 && (
+ <>
+ <dt className="text-muted-foreground">{t(($) => $.runs_timeline.detail_model)}</dt>
+ <dd className="min-w-0 break-words">{usage.models.join(", ")}</dd>
+ </>
+ )}
+ {usage && hit != null && (
+ <>
+ <dt className="text-muted-foreground">{t(($) => $.runs_timeline.detail_cache)}</dt>
+ <dd className="tabular-nums">
+ {t(($) => $.runs_timeline.cache_hit_value, {
+ percent: percent(hit),
+ amount: formatUsd(usage.cacheSavings),
+ })}
+ </dd>
+ </>
+ )}
+ <dt className="text-muted-foreground">{t(($) => $.runs_timeline.detail_time)}</dt>
+ <dd className="tabular-nums">
+ {run.active ? hm.format(run.startMs) : `${hm.format(run.startMs)}–${hm.format(run.endMs)}`}
+ </dd>
+ {run.task.branch_name && (
+ <>
+ <dt className="text-muted-foreground">{t(($) => $.runs_timeline.detail_branch)}</dt>
+ <dd className="min-w-0 truncate font-mono text-micro" title={run.task.branch_name}>
+ {run.task.branch_name}
+ </dd>
+ </>
)}
- </PopoverContent>
- </Popover>
+ </dl>
+ </div>
);
}
-// Width of the cost bar's track (`w-20`).
-const COST_TRACK_PX = 80;
-
-// A run's cost as one bar: length is its share of the most expensive run, the
-// segments split it by what was billed. Segments too thin to see are dropped
-// rather than drawn as a sliver next to a gap, and a bar too short to hold
-// its gaps shows only its largest part — gaps alone would swallow it.
-function CostBar({
- breakdown,
- total,
- widthPx,
+function RunDetailPart({
+ swatch,
+ label,
+ tokens,
+ cost,
+ share,
}: {
- breakdown: CostBreakdown;
- total: number;
- widthPx: number;
+ swatch: string;
+ label: string;
+ tokens: number;
+ cost: number;
+ share: string;
}) {
- const visible = total > 0
- ? COST_PARTS.filter((part) => breakdown[part.key] / total >= 0.01)
- : [];
- const parts =
- widthPx < 12
- ? visible.toSorted((a, b) => breakdown[b.key] - breakdown[a.key]).slice(0, 1)
- : visible;
return (
- <span
- aria-hidden
- className="flex h-1 gap-0.5 overflow-hidden rounded-full"
- style={{ width: Math.max(3, widthPx) }}
- >
- {parts.map((part) => (
- <span
- key={part.key}
- className={cn("h-full", part.swatch)}
- style={{ flexGrow: breakdown[part.key], flexBasis: 0 }}
- />
- ))}
- </span>
+ <>
+ <span aria-hidden className={cn("size-2 rounded-xs", swatch)} />
+ <span className="truncate text-muted-foreground">{label}</span>
+ <span className="text-right">{formatTokens(tokens)}</span>
+ <span className="w-14 text-right font-medium">{formatUsd(cost)}</span>
+ <span className="w-10 text-right text-faint-foreground">{share}</span>
+ </>
);
}
diff --git a/packages/views/issues/components/run-trigger-label.tsx b/packages/views/issues/components/run-trigger-label.tsx
new file mode 100644
index 0000000000..38dcf6f391
--- /dev/null
+++ b/packages/views/issues/components/run-trigger-label.tsx
@@ -0,0 +1,22 @@
+"use client";
+
+import type { AgentTask } from "@multica/core/types";
+import { WakeupRunLabel } from "./wakeup-source-chip";
+
+/**
+ * A run's trigger, with a wakeup run naming its rule's condition ("Wakeup ·
+ * When a linked PR's CI finishes") the way the execution log's rows do. The
+ * rule lookup mounts only for wakeup runs.
+ */
+export function RunTriggerLabel({
+ task,
+ fallback,
+ children,
+}: {
+ task: AgentTask;
+ fallback: string;
+ children: (label: string) => React.ReactNode;
+}) {
+ if (!task.wakeup_id) return <>{children(fallback)}</>;
+ return <WakeupRunLabel task={task} fallback={fallback} render={children} />;
+}
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index b61648c300..d62026673d 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -756,13 +756,11 @@
"trigger_image": "[Image]",
"summary_runs_one": "{{count}} run",
"summary_runs_other": "{{count}} runs",
- "agent_time": "{{duration}} agent time",
- "elapsed": "{{duration}} elapsed",
"latest": "Latest",
"open_timeline": "Open timeline",
"more_runs_one": "{{count}} more",
"more_runs_other": "{{count}} more",
- "strip_aria": "Cumulative cost over time — open the run timeline",
+ "strip_aria": "Cost per run — open the run timeline",
"strip_no_usage": "No usage recorded",
"sparkline_now": "Now"
},
@@ -778,10 +776,8 @@
"count_cancelled_other": "{{count}} cancelled",
"count_active_one": "{{count}} active",
"count_active_other": "{{count}} active",
- "legend_cumulative": "Cumulative cost",
- "legend_run": "Run · width is duration",
- "chart_aria_one": "Cumulative cost over time: {{cost}} across {{count}} run",
- "chart_aria_other": "Cumulative cost over time: {{cost}} across {{count}} runs",
+ "chart_aria_one": "Run activity: {{cost}} across {{count}} run",
+ "chart_aria_other": "Run activity: {{cost}} across {{count}} runs",
"day_today": "Today",
"day_yesterday": "Yesterday",
"day_runs_one": "{{count}} run",
@@ -791,13 +787,50 @@
"cost_output": "Output",
"cost_cache_read": "Cache read",
"cost_cache_write": "Cache write",
- "cost_breakdown_aria": "Cost breakdown: {{cost}}",
"no_usage": "No usage recorded",
+ "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.",
+ "stat_tokens": "Tokens",
+ "stat_output": "Output",
+ "tokens_cached": "{{percent}} from cache",
+ "elapsed_note": "{{duration}} elapsed",
+ "view_label": "Chart view",
+ "view_runs": "Per run",
+ "view_cumulative": "Cumulative",
+ "legend_cumulative": "Cumulative cost",
+ "legend_run": "Run · width is duration",
"tooltip_total": "Total so far {{cost}}",
"hover_no_run": "No run",
"hover_idle": "Idle {{duration}}",
- "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."
+ "cumulative_aria_one": "Cumulative cost over time: {{cost}} across {{count}} run",
+ "cumulative_aria_other": "Cumulative cost over time: {{cost}} across {{count}} runs",
+ "metric_label": "Chart metric",
+ "metric_cost": "Cost",
+ "metric_tokens": "Tokens",
+ "metric_time": "Agent time",
+ "unit_run": "per run",
+ "stack_agent": "by agent",
+ "stack_type": "by token type",
+ "by_agent": "By agent",
+ "by_model": "By model",
+ "others": "Others",
+ "col_time": "Time",
+ "col_trigger": "Trigger",
+ "col_agent": "Agent",
+ "col_model": "Model",
+ "col_duration": "Duration",
+ "col_tokens": "Tokens",
+ "col_cost": "Cost",
+ "tokens_count": "{{tokens}} tokens",
+ "details_toggle": "Run details",
+ "detail_breakdown": "Cost breakdown",
+ "detail_total": "Total",
+ "detail_status": "Status",
+ "detail_model": "Model",
+ "detail_cache": "Cache hit",
+ "cache_hit_value": "{{percent}} · saved {{amount}}",
+ "detail_time": "Time",
+ "detail_branch": "Branch"
},
"terminate_dialog": {
"title": "Stop this run?",
diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.json
index 3528dc1632..b454515d97 100644
--- a/packages/views/locales/fr/issues.json
+++ b/packages/views/locales/fr/issues.json
@@ -756,13 +756,11 @@
"trigger_image": "[Image]",
"summary_runs_one": "{{count}} exécution",
"summary_runs_other": "{{count}} exécutions",
- "agent_time": "{{duration}} de travail d'agent",
- "elapsed": "sur {{duration}}",
"latest": "Récentes",
"open_timeline": "Ouvrir la chronologie",
"more_runs_one": "{{count}} de plus",
"more_runs_other": "{{count}} de plus",
- "strip_aria": "Coût cumulé dans le temps — ouvrir la chronologie",
+ "strip_aria": "Coût par exécution — ouvrir la chronologie",
"strip_no_usage": "Aucune consommation enregistrée",
"sparkline_now": "Maintenant"
},
@@ -778,10 +776,8 @@
"count_cancelled_other": "{{count}} annulées",
"count_active_one": "{{count}} en cours",
"count_active_other": "{{count}} en cours",
- "legend_cumulative": "Coût cumulé",
- "legend_run": "Exécution · largeur = durée",
- "chart_aria_one": "Coût cumulé dans le temps : {{cost}} pour {{count}} exécution",
- "chart_aria_other": "Coût cumulé dans le temps : {{cost}} pour {{count}} exécutions",
+ "chart_aria_one": "Activité des exécutions : {{cost}} pour {{count}} exécution",
+ "chart_aria_other": "Activité des exécutions : {{cost}} pour {{count}} exécutions",
"day_today": "Aujourd'hui",
"day_yesterday": "Hier",
"day_runs_one": "{{count}} exécution",
@@ -791,13 +787,50 @@
"cost_output": "Sortie",
"cost_cache_read": "Lecture du cache",
"cost_cache_write": "Écriture du cache",
- "cost_breakdown_aria": "Détail du coût : {{cost}}",
"no_usage": "Aucune consommation enregistrée",
+ "note_unmapped": "Aucun tarif connu pour {{models}} ; leurs tokens sont comptés, mais pas leur coût.",
+ "note_estimate": "Le coût est estimé d'après les tarifs publiés des modèles, sauf lorsque le fournisseur a communiqué son propre chiffre.",
+ "stat_tokens": "Tokens",
+ "stat_output": "Sortie",
+ "tokens_cached": "{{percent}} depuis le cache",
+ "elapsed_note": "sur {{duration}}",
+ "view_label": "Vue du graphique",
+ "view_runs": "Par exécution",
+ "view_cumulative": "Cumul",
+ "legend_cumulative": "Coût cumulé",
+ "legend_run": "Exécution · largeur = durée",
"tooltip_total": "Cumul : {{cost}}",
"hover_no_run": "Aucune exécution",
"hover_idle": "Inactif {{duration}}",
- "note_unmapped": "Aucun tarif connu pour {{models}} ; leurs tokens sont comptés, mais pas leur coût.",
- "note_estimate": "Le coût est estimé d'après les tarifs publiés des modèles, sauf lorsque le fournisseur a communiqué son propre chiffre."
+ "cumulative_aria_one": "Coût cumulé dans le temps : {{cost}} pour {{count}} exécution",
+ "cumulative_aria_other": "Coût cumulé dans le temps : {{cost}} pour {{count}} exécutions",
+ "metric_label": "Mesure du graphique",
+ "metric_cost": "Coût",
+ "metric_tokens": "Tokens",
+ "metric_time": "Travail d'agent",
+ "unit_run": "par exécution",
+ "stack_agent": "par agent",
+ "stack_type": "par type de token",
+ "by_agent": "Par agent",
+ "by_model": "Par modèle",
+ "others": "Autres",
+ "col_time": "Heure",
+ "col_trigger": "Déclencheur",
+ "col_agent": "Agent",
+ "col_model": "Modèle",
+ "col_duration": "Durée",
+ "col_tokens": "Tokens",
+ "col_cost": "Coût",
+ "tokens_count": "{{tokens}} tokens",
+ "details_toggle": "Détails de l'exécution",
+ "detail_breakdown": "Détail du coût",
+ "detail_total": "Total",
+ "detail_status": "Statut",
+ "detail_model": "Modèle",
+ "detail_cache": "Taux de cache",
+ "cache_hit_value": "{{percent}} · {{amount}} économisés",
+ "detail_time": "Heure",
+ "detail_branch": "Branche"
},
"terminate_dialog": {
"title": "Arrêter cette exécution ?",
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index b7d546a85f..274cf8c05d 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -727,12 +727,10 @@
"trigger_wakeup": "起動 · {{condition}}",
"trigger_image": "[画像]",
"summary_runs_other": "{{count}} 回の実行",
- "agent_time": "エージェント作業 {{duration}}",
- "elapsed": "経過 {{duration}}",
"latest": "最新",
"open_timeline": "タイムラインを開く",
"more_runs_other": "他 {{count}} 件",
- "strip_aria": "累計費用の推移 — 実行タイムラインを開く",
+ "strip_aria": "実行ごとの費用 — 実行タイムラインを開く",
"strip_no_usage": "使用量の記録なし",
"sparkline_now": "現在"
},
@@ -745,9 +743,7 @@
"count_failed_other": "失敗 {{count}}",
"count_cancelled_other": "キャンセル {{count}}",
"count_active_other": "進行中 {{count}}",
- "legend_cumulative": "累計費用",
- "legend_run": "実行 · 幅は所要時間",
- "chart_aria_other": "累計費用の推移:{{count}} 回の実行で {{cost}}",
+ "chart_aria_other": "実行の推移:{{count}} 回の実行で {{cost}}",
"day_today": "今日",
"day_yesterday": "昨日",
"day_runs_other": "{{count}} 回",
@@ -756,13 +752,49 @@
"cost_output": "出力",
"cost_cache_read": "キャッシュ読み取り",
"cost_cache_write": "キャッシュ書き込み",
- "cost_breakdown_aria": "費用の内訳:{{cost}}",
"no_usage": "使用量の記録なし",
+ "note_unmapped": "{{models}} は価格が未登録です。トークンは集計されますが費用は含まれません。",
+ "note_estimate": "費用は公開モデル料金からの概算です(プロバイダーが独自の費用を返した分を除く)。",
+ "stat_tokens": "トークン",
+ "stat_output": "出力",
+ "tokens_cached": "{{percent}} がキャッシュ",
+ "elapsed_note": "経過 {{duration}}",
+ "view_label": "グラフ表示",
+ "view_runs": "実行ごと",
+ "view_cumulative": "累計",
+ "legend_cumulative": "累計費用",
+ "legend_run": "実行 · 幅は所要時間",
"tooltip_total": "累計 {{cost}}",
"hover_no_run": "実行なし",
"hover_idle": "アイドル {{duration}}",
- "note_unmapped": "{{models}} は価格が未登録です。トークンは集計されますが費用は含まれません。",
- "note_estimate": "費用は公開モデル料金からの概算です(プロバイダーが独自の費用を返した分を除く)。"
+ "cumulative_aria_other": "累計費用の推移:{{count}} 回の実行で {{cost}}",
+ "metric_label": "グラフの指標",
+ "metric_cost": "費用",
+ "metric_tokens": "トークン",
+ "metric_time": "エージェント作業",
+ "unit_run": "実行ごと",
+ "stack_agent": "エージェント別",
+ "stack_type": "トークン種別",
+ "by_agent": "エージェント別",
+ "by_model": "モデル別",
+ "others": "その他",
+ "col_time": "時刻",
+ "col_trigger": "トリガー",
+ "col_agent": "エージェント",
+ "col_model": "モデル",
+ "col_duration": "所要時間",
+ "col_tokens": "トークン",
+ "col_cost": "費用",
+ "tokens_count": "{{tokens}} トークン",
+ "details_toggle": "実行の詳細",
+ "detail_breakdown": "費用の内訳",
+ "detail_total": "合計",
+ "detail_status": "ステータス",
+ "detail_model": "モデル",
+ "detail_cache": "キャッシュヒット",
+ "cache_hit_value": "{{percent}} · {{amount}} 節約",
+ "detail_time": "時刻",
+ "detail_branch": "ブランチ"
},
"terminate_dialog": {
"title": "この実行を停止しますか?",
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index b737da945f..f3a57965e4 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -727,12 +727,10 @@
"trigger_wakeup": "깨우기 · {{condition}}",
"trigger_image": "[이미지]",
"summary_runs_other": "실행 {{count}}회",
- "agent_time": "에이전트 작업 {{duration}}",
- "elapsed": "경과 {{duration}}",
"latest": "최근",
"open_timeline": "타임라인 열기",
"more_runs_other": "{{count}}개 더",
- "strip_aria": "시간에 따른 누적 비용 — 실행 타임라인 열기",
+ "strip_aria": "실행별 비용 — 실행 타임라인 열기",
"strip_no_usage": "사용량 기록 없음",
"sparkline_now": "지금"
},
@@ -745,9 +743,7 @@
"count_failed_other": "실패 {{count}}회",
"count_cancelled_other": "취소 {{count}}회",
"count_active_other": "진행 중 {{count}}회",
- "legend_cumulative": "누적 비용",
- "legend_run": "실행 · 너비는 소요 시간",
- "chart_aria_other": "시간에 따른 누적 비용: 실행 {{count}}회, 총 {{cost}}",
+ "chart_aria_other": "실행 현황: 실행 {{count}}회, 총 {{cost}}",
"day_today": "오늘",
"day_yesterday": "어제",
"day_runs_other": "실행 {{count}}회",
@@ -756,13 +752,49 @@
"cost_output": "출력",
"cost_cache_read": "캐시 읽기",
"cost_cache_write": "캐시 쓰기",
- "cost_breakdown_aria": "비용 내역: {{cost}}",
"no_usage": "사용량 기록 없음",
+ "note_unmapped": "{{models}}의 가격 정보가 없어 토큰은 집계되지만 비용은 포함되지 않습니다.",
+ "note_estimate": "비용은 공개된 모델 요금 기준 추정치이며, 제공자가 자체 비용을 보고한 경우는 그 값을 사용합니다.",
+ "stat_tokens": "토큰",
+ "stat_output": "출력",
+ "tokens_cached": "{{percent}} 캐시",
+ "elapsed_note": "경과 {{duration}}",
+ "view_label": "차트 보기",
+ "view_runs": "실행별",
+ "view_cumulative": "누적",
+ "legend_cumulative": "누적 비용",
+ "legend_run": "실행 · 너비는 소요 시간",
"tooltip_total": "누적 {{cost}}",
"hover_no_run": "실행 없음",
"hover_idle": "유휴 {{duration}}",
- "note_unmapped": "{{models}}의 가격 정보가 없어 토큰은 집계되지만 비용은 포함되지 않습니다.",
- "note_estimate": "비용은 공개된 모델 요금 기준 추정치이며, 제공자가 자체 비용을 보고한 경우는 그 값을 사용합니다."
+ "cumulative_aria_other": "시간에 따른 누적 비용: 실행 {{count}}회, 총 {{cost}}",
+ "metric_label": "차트 지표",
+ "metric_cost": "비용",
+ "metric_tokens": "토큰",
+ "metric_time": "에이전트 작업",
+ "unit_run": "실행별",
+ "stack_agent": "에이전트별",
+ "stack_type": "토큰 유형별",
+ "by_agent": "에이전트별",
+ "by_model": "모델별",
+ "others": "기타",
+ "col_time": "시간",
+ "col_trigger": "트리거",
+ "col_agent": "에이전트",
+ "col_model": "모델",
+ "col_duration": "소요 시간",
+ "col_tokens": "토큰",
+ "col_cost": "비용",
+ "tokens_count": "토큰 {{tokens}}",
+ "details_toggle": "실행 세부 정보",
+ "detail_breakdown": "비용 내역",
+ "detail_total": "합계",
+ "detail_status": "상태",
+ "detail_model": "모델",
+ "detail_cache": "캐시 적중",
+ "cache_hit_value": "{{percent}} · {{amount}} 절약",
+ "detail_time": "시간",
+ "detail_branch": "브랜치"
},
"terminate_dialog": {
"title": "이 실행을 중지할까요?",
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index 61877ceb6f..2fe23f0a29 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -727,12 +727,10 @@
"trigger_wakeup": "由唤醒触发 · {{condition}}",
"trigger_image": "[图片]",
"summary_runs_other": "{{count}} 次运行",
- "agent_time": "智能体工作 {{duration}}",
- "elapsed": "历时 {{duration}}",
"latest": "最近",
"open_timeline": "打开时间线",
"more_runs_other": "还有 {{count}} 次",
- "strip_aria": "累计费用随时间的变化——打开运行时间线",
+ "strip_aria": "每次运行的费用——打开运行时间线",
"strip_no_usage": "没有用量记录",
"sparkline_now": "现在"
},
@@ -745,9 +743,7 @@
"count_failed_other": "{{count}} 次失败",
"count_cancelled_other": "{{count}} 次取消",
"count_active_other": "{{count}} 次进行中",
- "legend_cumulative": "累计费用",
- "legend_run": "运行 · 宽度为时长",
- "chart_aria_other": "累计费用随时间的变化:{{count}} 次运行,共 {{cost}}",
+ "chart_aria_other": "运行情况:{{count}} 次运行,共 {{cost}}",
"day_today": "今天",
"day_yesterday": "昨天",
"day_runs_other": "{{count}} 次运行",
@@ -756,13 +752,49 @@
"cost_output": "输出",
"cost_cache_read": "缓存读",
"cost_cache_write": "缓存写",
- "cost_breakdown_aria": "费用明细:{{cost}}",
"no_usage": "没有用量记录",
+ "note_unmapped": "{{models}} 没有维护价格,token 已计入,费用未计入。",
+ "note_estimate": "费用按各模型公开价目估算;供应商回报实际费用时以回报值为准。",
+ "stat_tokens": "Token",
+ "stat_output": "输出",
+ "tokens_cached": "{{percent}} 来自缓存",
+ "elapsed_note": "历时 {{duration}}",
+ "view_label": "图表视图",
+ "view_runs": "按次",
+ "view_cumulative": "累计",
+ "legend_cumulative": "累计费用",
+ "legend_run": "运行 · 宽度为时长",
"tooltip_total": "累计 {{cost}}",
"hover_no_run": "没有运行",
"hover_idle": "空闲 {{duration}}",
- "note_unmapped": "{{models}} 没有维护价格,token 已计入,费用未计入。",
- "note_estimate": "费用按各模型公开价目估算;供应商回报实际费用时以回报值为准。"
+ "cumulative_aria_other": "累计费用随时间的变化:{{count}} 次运行,共 {{cost}}",
+ "metric_label": "图表指标",
+ "metric_cost": "费用",
+ "metric_tokens": "Token",
+ "metric_time": "智能体工作",
+ "unit_run": "每次运行",
+ "stack_agent": "按智能体",
+ "stack_type": "按 Token 类型",
+ "by_agent": "按智能体",
+ "by_model": "按模型",
+ "others": "其他",
+ "col_time": "时间",
+ "col_trigger": "触发",
+ "col_agent": "智能体",
+ "col_model": "模型",
+ "col_duration": "时长",
+ "col_tokens": "Token",
+ "col_cost": "费用",
+ "tokens_count": "{{tokens}} Token",
+ "details_toggle": "运行详情",
+ "detail_breakdown": "费用明细",
+ "detail_total": "合计",
+ "detail_status": "状态",
+ "detail_model": "模型",
+ "detail_cache": "缓存命中",
+ "cache_hit_value": "{{percent}} · 节省 {{amount}}",
+ "detail_time": "时间",
+ "detail_branch": "分支"
},
"terminate_dialog": {
"title": "确定停止本次运行?",