Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7758: lay an issue's runs out in time (#8890)
Jiayuan Zhang13094caf7a5f
diff --git a/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx b/packages/views/common/task-transcript/agent-transcript-dialog.test.tsxindex a45e56c93d..9540b8bc83 100644--- a/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx+++ b/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx@@ -249,6 +249,22 @@ afterEach(() => {});describe("AgentTranscriptDialog", () => {+ it("shows what was asked, whole, under the header", () => {+ // The lists that open this dialog cut the ask to one line; here it wraps.+ const ask = "Merge the three split-out sub-issues back into this PR & ship conditions, history and runaway protection together";+ renderDialog(items, { task: { ...baseTask, trigger_comment_id: "comment-1", trigger_summary: ask } });++ expect(screen.getByText("Trigger")).toBeInTheDocument();+ expect(+ screen.getByText("Merge the three split-out sub-issues back into this PR & ship conditions, history and runaway protection together"),+ ).toBeInTheDocument();+ });++ it("has no trigger row for a run with no snapshot", () => {+ renderDialog(items, { task: { ...baseTask, trigger_summary: undefined } });+ expect(screen.queryByText("Trigger")).not.toBeInTheDocument();+ });+it("opens the matching result and duration for parallel same-tool calls", () => {const at = (seconds: number) =>new Date(Date.parse(baseTask.started_at!) + seconds * 1000).toISOString();diff --git a/packages/views/common/task-transcript/agent-transcript-dialog.tsx b/packages/views/common/task-transcript/agent-transcript-dialog.tsxindex fa7ead0225..1354cad2dc 100644--- a/packages/views/common/task-transcript/agent-transcript-dialog.tsx+++ b/packages/views/common/task-transcript/agent-transcript-dialog.tsx@@ -43,6 +43,7 @@ import {} from "@multica/ui/components/ui/dropdown-menu";import { ActorAvatar } from "../actor-avatar";import { AttributionBadge } from "../../issues/components/attribution-badge";+import { plainTriggerSummary } from "../../issues/components/task-run-labels";import { cancellationActorLabel, cancelReasonLabel, failureReasonLabel } from "../../agents/components/tabs/task-failure";import { RichContent } from "../../rich-content";import { api } from "@multica/core/api";@@ -1084,6 +1085,9 @@ export function AgentTranscriptDialog({</div></div>+ {/* ── What was asked ─────────────────────────────────────────── */}+ <RunTriggerRow task={task} />+{/* ── What the run produced ──────────────────────────────────── */}<RunOutcomeRow outcome={outcome} branch={task.branch_name} />@@ -1318,6 +1322,32 @@ function FactDot() {* Renders nothing when the run produced nothing nameable; a row of zeroes* would read as "it did nothing" rather than "we have nothing to summarize".*/+/**+ * What the person asked for, in full. The header names only how the run was+ * triggered ("Comment"), and the lists that open this dialog show the ask on+ * one truncated line — so this is where a long request is read whole. The+ * snapshot itself is capped at ~200 runes by the server; it is shown as it+ * was captured, wrapping rather than truncating.+ */+function RunTriggerRow({ task }: { task: AgentTask }) {+ const { t } = useT("agents");+ const { t: tIssues } = useT("issues");+ if (!task.trigger_summary) return null;+ const text = plainTriggerSummary(+ task.trigger_summary,+ tIssues(($) => $.execution_log.trigger_image),+ );+ if (!text) return null;+ return (+ <div className="flex shrink-0 items-baseline gap-2 border-b px-4 py-2">+ <span className="shrink-0 text-micro text-muted-foreground">+ {t(($) => $.transcript.trigger_text)}+ </span>+ <p className="min-w-0 whitespace-pre-wrap break-words text-caption text-foreground">{text}</p>+ </div>+ );+}+function RunOutcomeRow({outcome,branch,diff --git a/packages/views/issues/components/execution-log-section.test.tsx b/packages/views/issues/components/execution-log-section.test.tsxindex 0bd00508e8..1b7e88f580 100644--- a/packages/views/issues/components/execution-log-section.test.tsx+++ b/packages/views/issues/components/execution-log-section.test.tsx@@ -27,11 +27,15 @@ vi.mock("./terminate-task-confirm-dialog", () => ({TerminateTaskConfirmDialog: () => null,}));+vi.mock("@multica/core/workspace/hooks", () => ({+ useActorName: () => ({ getActorName: () => "Lambda" }),+}));+import {ActiveTaskRow,ExecutionLogSection,TaskCommentCoverage,- IssueUsageTotal,+ IssueRunsTotal,} from "./execution-log-section";import type { TaskUsage } from "@multica/core/types";import { act, within } from "@testing-library/react";@@ -234,7 +238,7 @@ describe("execution log failure reasons", () => {{ locale: "zh-Hans" },);- fireEvent.click(screen.getByRole("button", { name: "显示历史运行(1)" }));+ // The latest past runs are listed without a toggle.expect(screen.getByText(/提供商配额已用尽/)).toBeInTheDocument();expect(screen.queryByText(/Provider quota exhausted/),@@ -254,7 +258,6 @@ describe("execution log failure reasons", () => {{ locale: "zh-Hans" },);- fireEvent.click(screen.getByRole("button", { name: "显示历史运行(1)" }));expect(screen.queryByTitle(/provider returned 402/)).not.toBeInTheDocument();expect(screen.getByTitle("提供商配额已用尽")).toBeInTheDocument();});@@ -301,7 +304,7 @@ describe("per-run token usage", () => {// 260px minimum the row has 227px and the full header wants ~238px, and the// label was the only item that could give. It gave by breaking "Execution log"// across two lines (MUL-5804). These tests pin the contract that replaced that:-// one line always, and a width tier that drops the token figure whole.+// one line always, and a width tier that drops the run count whole.describe("execution log header geometry", () => {function renderSection(tasks: AgentTask[]) {// Seed the cache instead of mocking the API: the query is fresh for 30s,@@ -358,15 +361,15 @@ describe("execution log header geometry", () => {}});- it("drops the token figure whole rather than clipping a number", () => {+ it("drops the run count whole rather than clipping a number", () => {const { unmount } = renderSection([completed]);let header = within(headerOf());- // Below the tier the tokens and their separator leave together and the- // cost stays — never a clipped "$2.0…", which would read as a different- // figure than the issue actually spent.+ // Below the tier the count and its separator leave together and the cost+ // stays — never a clipped "$2.0…", which would read as a different figure+ // than the issue actually spent.const cost = header.getByText("$2.00");- expect(header.getByText("892K").className).toContain(+ expect(header.getByText("1 run").className).toContain("@max-[14rem]/execution-log:hidden",);expect(header.getByText("·").className).toContain(@@ -384,13 +387,88 @@ describe("execution log header geometry", () => {unmount();renderSection([completed, makeTask({ status: "running" })]);header = within(headerOf());- expect(header.getByText("892K").className).toContain(+ expect(header.getByText("2 runs").className).toContain("@max-[16rem]/execution-log:hidden",);});++ it("keeps the run count when there is no cost to show instead", () => {+ renderSection([makeTask({ status: "completed", completed_at: "2026-06-08T08:04:00Z" })]);+ const count = within(headerOf()).getByText("1 run");+ expect(count.className).not.toContain("hidden");+ expect(within(headerOf()).queryByText("$0.00")).not.toBeInTheDocument();+ });+});++describe("execution log past runs", () => {+ function renderSection(tasks: AgentTask[]) {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ queryClient.setQueryData(issueKeys.tasks("issue-1"), tasks);+ return renderWithI18n(+ <QueryClientProvider client={queryClient}>+ <ExecutionLogSection issueId="issue-1" identifier="MUL-1" issueTitle="Wakeups" />+ </QueryClientProvider>,+ );+ }++ const past = (i: number, overrides: Partial<AgentTask> = {}) =>+ makeTask({+ id: `past-${i}`,+ status: "completed",+ trigger_summary: `Past run ${i}`,+ started_at: `2026-06-0${i}T08:00:00Z`,+ completed_at: `2026-06-0${i}T08:10:00Z`,+ usage: [usageSlice()],+ ...overrides,+ });++ it("lists the latest three and hands the rest to the Runs dialog", () => {+ renderSection([past(1), past(2), past(3), past(4), past(5)]);++ expect(screen.getAllByText(/^Past run \d$/).map((el) => el.textContent)).toEqual([+ "Past run 5",+ "Past run 4",+ "Past run 3",+ ]);+ expect(screen.getByText("2 more")).toBeInTheDocument();++ fireEvent.click(screen.getByRole("button", { name: /Open timeline/ }));+ expect(screen.getByRole("heading", { name: "Runs" })).toBeInTheDocument();+ expect(screen.getByText("MUL-1 · Wakeups")).toBeInTheDocument();+ });++ it("shows each past run's cost, not its token count", () => {+ renderSection([past(1)]);++ const row = screen.getByText("Past run 1").closest("div")!;+ expect(within(row).getByText("$2.00")).toBeInTheDocument();+ expect(within(row).queryByText("892K")).not.toBeInTheDocument();+ });++ it("draws one strip bar per past run and sums the agent time", () => {+ renderSection([past(1), past(2), past(3, { status: "failed", usage: [] })]);++ const strip = screen.getByRole("button", {+ name: "Cost of each run, oldest to newest — open the run timeline",+ });+ expect(strip.children).toHaveLength(3);+ expect(screen.getByText(/30m agent time/)).toBeInTheDocument();++ fireEvent.click(strip);+ expect(screen.getByRole("heading", { name: "Runs" })).toBeInTheDocument();+ });++ it("skips the strip for a single run, where it would say nothing", () => {+ renderSection([past(1)]);+ expect(+ screen.queryByRole("button", { name: /Cost of each run/ }),+ ).not.toBeInTheDocument();+ });});-describe("IssueUsageTotal pricing", () => {+describe("IssueRunsTotal pricing", () => {afterEach(() => {useCustomPricingStore.setState({ pricings: {} });});@@ -411,7 +489,7 @@ describe("IssueUsageTotal pricing", () => {const task = makeTask({ status: "completed", usage: [unpriced] });renderWithI18n(- <IssueUsageTotal tasks={[task]} alone onOpen={() => {}} />,+ <IssueRunsTotal tasks={[task]} alone onOpen={() => {}} />,);// No rate on file for this model yet.diff --git a/packages/views/issues/components/execution-log-section.tsx b/packages/views/issues/components/execution-log-section.tsxindex b73ff43d3a..e79373c3f3 100644--- a/packages/views/issues/components/execution-log-section.tsx+++ b/packages/views/issues/components/execution-log-section.tsx@@ -2,13 +2,13 @@import { useEffect, useMemo, useState } from "react";import { useQuery } from "@tanstack/react-query";-import { ChevronRight, Loader2, RotateCcw, Square } from "lucide-react";+import { ChevronRight, Loader2, Maximize2, Square } from "lucide-react";import { toast } from "sonner";-import { api, dispatchReasonCode } from "@multica/core/api";+import { api } from "@multica/core/api";import { issueTasksOptions } from "@multica/core/issues/queries";import { useCustomPricingStore } from "@multica/core/runtimes/custom-pricing-store";import type { AgentTask } from "@multica/core/types";-import { useTimeAgo } from "../../i18n";+import { useLocale, useTimeAgo } from "../../i18n";import {Tooltip,TooltipContent,@@ -20,6 +20,7 @@ import { TranscriptButton } from "../../common/task-transcript";import { cancellationActorLabel, cancelReasonLabel, failureReasonLabel } from "../../agents/components/tabs/task-failure";import { useT } from "../../i18n";import { compareActiveIssueTasks } from "./active-task-order";+import { formatDuration as formatAgentTime } from "../../dashboard/utils";import {formatTokens,formatUsd,@@ -27,14 +28,19 @@ import {summarizeTaskUsageAcross,} from "../../runtimes/utils";import { TerminateTaskConfirmDialog } from "./terminate-task-confirm-dialog";-import { IssueUsageDialog } from "./issue-usage-dialog";+import { IssueRunsDialog, RunTriggerLabel } from "./issue-runs-dialog";+import { buildRunTimeline, type TimelineRun } from "./issue-run-timeline";+import { canRetryRun, RetryRunButton } from "./retry-run-button";import { TaskStatusIcon } from "./task-status-icon";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); past runs (terminal-// statuses) collapse behind a "Show past runs (N)" toggle.+// runs sit at the top (always visible when present); below them a spend strip+// (one bar per past run, oldest to newest, height = cost) and the latest few+// past runs. The full history lives in the Runs dialog the header total, the+// strip 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@@ -58,10 +64,14 @@ import { WakeupRunLabel } from "./wakeup-source-chip";interface ExecutionLogSectionProps {issueId: string;- /** Shown in the usage dialog's subtitle so the panel names what it totals. */+ /** Shown in the Runs dialog's subtitle so it names the issue it lays out. */identifier?: string;+ issueTitle?: string;}+// How many past runs the sidebar lists before deferring to the Runs dialog.+const LATEST_PAST_RUNS = 3;+// Past-runs sort priority: newest first by timestamp. When two runs// share the same timestamp, failed ranks above cancelled, which ranks// above completed.@@ -71,11 +81,11 @@ const PAST_STATUS_RANK: Record<string, number> = {completed: 2,};-export function ExecutionLogSection({ issueId, identifier }: ExecutionLogSectionProps) {+export function ExecutionLogSection({ issueId, identifier, issueTitle }: ExecutionLogSectionProps) {const { t } = useT("issues");const [open, setOpen] = useState(true);- const [showPast, setShowPast] = useState(false);- const [usageOpen, setUsageOpen] = useState(false);+ const [runsOpen, setRunsOpen] = useState(false);+ const pricings = useCustomPricingStore((s) => s.pricings);// Cache key registered in `issueKeys.tasks` (packages/core/issues/queries.ts)// so the global useRealtimeSync `task:` prefix path invalidates it via@@ -118,18 +128,32 @@ export function ExecutionLogSection({ issueId, identifier }: ExecutionLogSection});}, [tasks]);+ // Sidebar-only figures: the strip's bars 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.+ const timeline = useMemo(+ () => buildRunTimeline(tasks, Date.now()),+ // eslint-disable-next-line react-hooks/exhaustive-deps -- `pricings` re-prices on a saved custom rate+ [tasks, pricings],+ );+ const pastRuns = useMemo(() => timeline.runs.filter((run) => !run.active), [timeline]);+if (activeTasks.length === 0 && pastTasks.length === 0) return null;+ const latest = pastTasks.slice(0, LATEST_PAST_RUNS);+ const hiddenCount = pastTasks.length - latest.length;+ const openRuns = () => setRunsOpen(true);+return (// `@container/execution-log`: the header's three items only fit side by// side above a certain width, and the width that decides it is the// sidebar's — a resizable 260–420px panel — not the viewport's. See- // IssueUsageTotal for the tier this container drives.+ // IssueRunsTotal for the tier this container drives.<div className="@container/execution-log">{/* Header is two independent targets, not one: the label + chevron- collapse the section, the total on the right opens the usage- breakdown. Nesting a button inside a button is invalid HTML, so they- are siblings in a flex row rather than a button wrapping a button. */}+ collapse the section, the total on the right opens the Runs dialog.+ Nesting a button inside a button is invalid HTML, so they are+ siblings in a flex row rather than a button wrapping a button. */}<div className="mb-2 flex w-full items-center gap-1"><buttontype="button"@@ -158,10 +182,10 @@ export function ExecutionLogSection({ issueId, identifier }: ExecutionLogSection<span className="font-mono text-caption tabular-nums">{activeTasks.length}</span></span>)}- <IssueUsageTotal+ <IssueRunsTotaltasks={tasks}alone={activeTasks.length === 0}- onOpen={() => setUsageOpen(true)}+ onOpen={openRuns}/></div>{open && (@@ -169,65 +193,182 @@ export function ExecutionLogSection({ issueId, identifier }: ExecutionLogSection{activeTasks.map((task) => (<ActiveTaskRow key={task.id} task={task} issueId={issueId} />))}+ {activeTasks.length > 0 && pastRuns.length > 0 && (+ <div className="my-1.5 border-t border-border/60" />+ )}- {pastTasks.length > 0 && (+ {pastRuns.length >= 2 && <RunSpendStrip runs={pastRuns} 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>+ )}++ {latest.length > 0 && (<>- {activeTasks.length > 0 && (- <div className="my-1.5 border-t border-border/60" />- )}- <button- type="button"- onClick={() => setShowPast(!showPast)}- className="flex w-full items-center gap-1 rounded-xs px-1 py-1 text-caption text-muted-foreground transition-colors hover:bg-accent/40 hover:text-foreground"- >- <ChevronRight- className={`!size-3 shrink-0 stroke-[2.5] transition-transform ${- showPast ? "rotate-90" : ""- }`}- />- {showPast- ? t(($) => $.execution_log.hide_past, { count: pastTasks.length })- : t(($) => $.execution_log.show_past, { count: pastTasks.length })}- </button>- {showPast && (- <div className="mt-0.5 space-y-0.5">- {pastTasks.map((task) => (- <PastRow key={task.id} task={task} issueId={issueId} />- ))}- </div>- )}+ <div className="px-1 pt-2 pb-0.5 text-micro text-muted-foreground">+ {t(($) => $.execution_log.latest)}+ </div>+ {latest.map((task) => (+ <PastRow key={task.id} task={task} issueId={issueId} />+ ))}</>)}+ <button+ type="button"+ onClick={openRuns}+ className="flex w-full items-center gap-1.5 rounded-xs px-1 py-1.5 text-caption transition-colors hover:bg-accent/40"+ >+ <Maximize2 aria-hidden className="size-3 shrink-0 text-muted-foreground" />+ <span className="truncate">{t(($) => $.execution_log.open_timeline)}</span>+ {hiddenCount > 0 && (+ <span className="ml-auto shrink-0 text-muted-foreground tabular-nums">+ {t(($) => $.execution_log.more_runs, { count: hiddenCount })}+ </span>+ )}+ </button></div>)}- <IssueUsageDialog- open={usageOpen}- onOpenChange={setUsageOpen}+ <IssueRunsDialog+ open={runsOpen}+ onOpenChange={setRunsOpen}+ issueId={issueId}identifier={identifier ?? ""}+ issueTitle={issueTitle}tasks={tasks}/></div>);}+// ─── Spend strip ───────────────────────────────────────────────────────────++// The most bars the strip draws; older runs stay in the Runs dialog. Past this+// a 260px column cannot keep a gap between bars.+const STRIP_MAX_RUNS = 48;+const STRIP_HEIGHT = 36;++// One bar per past run, oldest to newest, height = that run's cost — the+// issue's rhythm at a glance: how busy it has been, which runs were expensive,+// and where one failed. The whole strip is one button into the Runs dialog;+// each bar carries its own hover summary.+function RunSpendStrip({ runs, onOpen }: { runs: TimelineRun[]; onOpen: () => void }) {+ const { t } = useT("issues");+ const locale = useLocale();+ const shown = runs.slice(-STRIP_MAX_RUNS);+ const maxCost = shown.reduce((m, run) => Math.max(m, run.usage?.cost ?? 0), 0);+ const dayOf = (ms: number) => new Date(ms).toDateString();+ const edgeLabel = (ms: number) =>+ dayOf(ms) === new Date().toDateString()+ ? t(($) => $.runs_timeline.day_today)+ : new Intl.DateTimeFormat(locale, { month: "short", day: "numeric" }).format(ms);+ const first = shown[0];+ const last = shown[shown.length - 1];++ return (+ <div className="px-1 pb-1">+ <button+ type="button"+ onClick={onOpen}+ aria-label={t(($) => $.execution_log.strip_aria)}+ className="flex w-full items-end gap-[3px] rounded-xs"+ style={{ height: STRIP_HEIGHT }}+ >+ {shown.map((run) => (+ <StripBar key={run.task.id} run={run} maxCost={maxCost} />+ ))}+ </button>+ {/* Day boundaries, on the same flex grid as the bars so each tick sits+ exactly between the last run of one day and the first of the next. */}+ <div aria-hidden className="flex h-1.5 gap-[3px] border-t border-border">+ {shown.map((run, i) => (+ <span key={run.task.id} className="relative max-w-3 flex-1">+ {i > 0 && dayOf(run.startMs) !== dayOf(shown[i - 1]!.startMs) && (+ <span className="absolute top-0 -left-[2px] h-1.5 w-px bg-faint-foreground" />+ )}+ </span>+ ))}+ </div>+ {first && last && (+ <div aria-hidden className="flex justify-between text-micro text-muted-foreground">+ <span>{edgeLabel(first.startMs)}</span>+ {dayOf(first.startMs) !== dayOf(last.startMs) && <span>{edgeLabel(last.startMs)}</span>}+ </div>+ )}+ </div>+ );+}++function StripBar({ run, maxCost }: { run: TimelineRun; maxCost: number }) {+ const { t } = useT("issues");+ const trigger = useTriggerText(run.task);+ const status = useStatusLabel(run.task.status);+ const cost = run.usage?.cost;+ // A run without usage is not a zero-height bar — that would read as "free".+ // It gets a dot on the baseline instead, coloured by how it ended.+ const bar =+ cost != null ? (+ <span+ className="block w-full rounded-t-xs bg-chart-2 transition-colors group-hover/strip-bar:bg-chart-1"+ style={{ height: Math.max(3, maxCost > 0 ? (cost / maxCost) * STRIP_HEIGHT : 3) }}+ />+ ) : (+ <span+ className={`mx-auto block size-1 rounded-full ${+ run.task.status === "failed" ? "bg-destructive" : "bg-faint-foreground"+ }`}+ />+ );+ return (+ <Tooltip>+ <TooltipTrigger+ render={<span />}+ className="group/strip-bar flex h-full max-w-3 min-w-0 flex-1 items-end"+ >+ {bar}+ </TooltipTrigger>+ <TooltipContent className="max-w-64 flex-col items-start gap-0">+ <RunTriggerLabel task={run.task} fallback={trigger}>+ {(label) => <span className="max-w-full truncate">{label}</span>}+ </RunTriggerLabel>+ <span className="text-micro text-muted-foreground">+ {[+ cost != null ? formatUsd(cost) : t(($) => $.execution_log.strip_no_usage),+ run.durationMs != null ? formatAgentTime(run.durationMs / 1000, "0s") : null,+ run.task.status === "completed" ? null : status,+ ]+ .filter(Boolean)+ .join(" · ")}+ </span>+ </TooltipContent>+ </Tooltip>+ );+}+// ─── Issue total ───────────────────────────────────────────────────────────-// The issue's whole spend, as a header affordance: "2.1M · $4.92". Answers-// "what has this issue cost" without expanding anything, and is the entry-// point to the per-run breakdown.+// The issue's run count and whole spend, as a header affordance: "21 runs ·+// $166". Answers "what has this issue cost" without expanding anything, and is+// the entry point to the Runs dialog.//-// Renders nothing when no run on the issue has recorded usage — an issue whose-// runs all predate usage reporting gets its old header back rather than a-// "0 · $0.00" that would read as "this was free".+// The cost is left out when no run on the issue has recorded usage — an issue+// whose runs all predate usage reporting shows its run count rather than a+// "$0.00" that would read as "this was free".//-// Narrow sections drop the token figure and keep the cost. Something has to-// give at the narrow end — the header's full form needs ~246px next to the-// active-run chip and the sidebar's 260px minimum leaves 228px — and the token-// count is the piece whose absence costs least: the cost answers "what has-// this issue spent", and the exact token split is a click away in the dialog-// this opens. It is a figure that yields, never a figure's digits: a clipped-// "$31.1…" would read as a different number than the issue actually spent.-export function IssueUsageTotal({+// Narrow sections drop the run count and keep the cost. Something has to give+// at the narrow end — the header's full form needs ~246px next to the+// active-run chip and the sidebar's 260px minimum leaves 228px — and the count+// is the piece whose absence costs least: the cost answers "what has this+// issue spent", and the runs are listed right below. It is a figure that+// yields, never a figure's digits: a clipped "$31.1…" would read as a+// different number than the issue actually spent.+export function IssueRunsTotal({tasks,alone,onOpen,@@ -244,9 +385,11 @@ export function IssueUsageTotal({const pricings = useCustomPricingStore((s) => s.pricings);const total = useMemo(() => summarizeTaskUsageAcross(tasks.map((task) => task.usage)),+ // eslint-disable-next-line react-hooks/exhaustive-deps -- see above[tasks, pricings],);- if (!total) return null;+ const runCount = tasks.filter((task) => task.status !== "deferred").length;+ if (runCount === 0) return null;// Two thresholds because the header has two shapes, and the tier should cost// the reader a figure only where the row genuinely runs out: beside the@@ -254,10 +397,13 @@ export function IssueUsageTotal({// literal classes — Tailwind scans source text, so a composed string would// generate neither. `@max-…` (rather than showing at `@min-…`) is what makes// a host that renders this outside the section's `@container` degrade to the- // full form instead of silently losing the tokens forever.- const narrowTier = alone- ? "@max-[14rem]/execution-log:hidden"- : "@max-[16rem]/execution-log:hidden";+ // full form instead of silently losing the count forever. With no cost to+ // keep, the count is the whole affordance and never tiers away.+ const narrowTier = !total+ ? ""+ : alone+ ? "@max-[14rem]/execution-log:hidden"+ : "@max-[16rem]/execution-log:hidden";return (<Tooltip>@@ -267,11 +413,15 @@ export function IssueUsageTotal({alone ? "ml-auto" : ""}`}>- <span className={`font-medium ${narrowTier}`}>- {formatTokens(total.tokens)}+ <span className={`text-muted-foreground ${narrowTier}`}>+ {t(($) => $.execution_log.summary_runs, { count: runCount })}</span>- <span className={`text-faint-foreground ${narrowTier}`}>·</span>- <span className="text-muted-foreground">{formatUsd(total.cost)}</span>+ {total && (+ <>+ <span className={`text-faint-foreground ${narrowTier}`}>·</span>+ <span className="font-medium">{formatUsd(total.cost)}</span>+ </>+ )}</TooltipTrigger><TooltipContent>{t(($) => $.execution_log.usage_total_tooltip)}</TooltipContent></Tooltip>@@ -431,7 +581,6 @@ function PastRow({ task, issueId }: { task: AgentTask; issueId: string }) {const { t } = useT("issues");const { t: tAgents } = useT("agents");const timeAgo = useTimeAgo();- const [retrying, setRetrying] = useState(false);const label = useStatusLabel(task.status);const trigger = useTriggerText(task);const time = task.completed_at ? timeAgo(task.completed_at) : "—";@@ -462,9 +611,9 @@ function PastRow({ task, issueId }: { task: AgentTask; issueId: string }) {// newest-first, so "which run came first" is already expressed by position —// the exact "when" is the detail, and how much it cost is the new question.// The displaced timestamp moves into the row tooltip below, together with- // the duration and model, which were previously not surfaced here at all.+ // the duration, token count and model — the split lives in the Runs dialog.//- // `null` (no usage recorded) renders an em dash, never 0: a run from before+ // `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 = [@@ -472,42 +621,12 @@ function PastRow({ task, issueId }: { task: AgentTask; issueId: string }) {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(" · ");- // Retry only makes sense for terminal-but-not-success rows. Passing- // task.id targets this specific row's agent — without it, the rerun- // endpoint would fall back to the issue's current assignee and the- // wrong agent would fire on rows whose agent has since been displaced- // (e.g. reassignment, squad worker, or a one-off @-mention agent).- const canRetry = task.status === "failed" || task.status === "cancelled";-- const handleRetry = async () => {- if (retrying) return;- setRetrying(true);- try {- await api.rerunIssue(issueId, task.id);- } catch (e) {- // A rerun is now re-gated on the operator's invoke permission (MUL-4525):- // a structured 403 means the agent can't be triggered, not a transient- // failure — localize it instead of echoing the server's generic message.- toast.error(- dispatchReasonCode(e) === "invocation_not_allowed"- ? t(($) => $.execution_log.retry_blocked)- : e instanceof Error- ? e.message- : t(($) => $.execution_log.retry_failed),- );- } finally {- // Reset on both success and failure: the past row stays mounted- // (its task.id is unchanged), so leaving `retrying` true on success- // would pin the button as a permanent spinner.- setRetrying(false);- }- };-return (<RowShell task={task} title={rowTitle}>{task.wakeup_id ? (@@ -522,35 +641,14 @@ function PastRow({ task, issueId }: { task: AgentTask; issueId: string }) {{[statusTitle, time].filter(Boolean).join(" · ")}</span>{usage ? (- <span className="tabular-nums">{formatTokens(usage.tokens)}</span>+ <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)} />- {canRetry && (- <Tooltip>- <TooltipTrigger- render={- <button- type="button"- onClick={handleRetry}- disabled={retrying}- aria-label={t(($) => $.execution_log.retry_task_aria)}- />- }- className="flex items-center justify-center rounded-xs p-1 text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50"- >- {retrying ? (- <Loader2 className="h-3.5 w-3.5 animate-spin" />- ) : (- <RotateCcw className="h-3.5 w-3.5" />- )}- </TooltipTrigger>- <TooltipContent>{t(($) => $.execution_log.retry_task_tooltip)}</TooltipContent>- </Tooltip>- )}+ {canRetryRun(task) && <RetryRunButton task={task} issueId={issueId} />}</RowActions></RowShell>);diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsxindex e26f330972..91123c36bf 100644--- a/packages/views/issues/components/issue-detail.test.tsx+++ b/packages/views/issues/components/issue-detail.test.tsx@@ -1681,7 +1681,12 @@ describe("IssueDetail (shared)", () => {expect(within(slot).getByText("Cancelled by the system")).toBeInTheDocument();expect(within(slot).queryByText("task cancelled by server")).not.toBeInTheDocument();expect(within(slot).queryByText("Failed")).not.toBeInTheDocument();- expect(screen.getAllByRole("button", { name: "Retry run" })).toHaveLength(1);+ // Once in the timeline. The sidebar's execution log lists the latest+ // runs with their own row actions, which is a separate surface.+ const timelineRetries = screen+ .getAllByRole("button", { name: "Retry run" })+ .filter((button) => !button.closest(".\\@container\\/execution-log"));+ expect(timelineRetries).toHaveLength(1);};it("renders the run block in the notice's thread slot and retries that run", async () => {diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex 2d9b213601..0dd3b1caa5 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -2940,7 +2940,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = trown token spend, with the issue total on the section header.Self-contained; owns its own collapse state and WS subscriptions.Hides itself when there are no runs to show. */}- <ExecutionLogSection issueId={id} identifier={issue.identifier} />+ <ExecutionLogSection issueId={id} identifier={issue.identifier} issueTitle={issue.title} />{/* Details — creator and timestamps. Sits below the execution logbecause it is the least-read block in the sidebar: the valuesdiff --git a/packages/views/issues/components/issue-run-timeline.test.ts b/packages/views/issues/components/issue-run-timeline.test.tsnew file mode 100644index 0000000000..d494a53735--- /dev/null+++ b/packages/views/issues/components/issue-run-timeline.test.ts@@ -0,0 +1,314 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import type { AgentTask, TaskUsage } from "@multica/core/types";+import {+ buildRunTimeline,+ groupRunsByDay,+ nearestRunIndex,+ niceTicks,+ timeTicks,+} from "./issue-run-timeline";++function makeTask(overrides: Partial<AgentTask> = {}): AgentTask {+ return {+ id: "task-1",+ agent_id: "agent-1",+ runtime_id: "runtime-1",+ issue_id: "issue-1",+ status: "completed",+ priority: 0,+ dispatched_at: null,+ started_at: "2026-09-24T10:00:00",+ completed_at: "2026-09-24T10:30:00",+ result: null,+ error: null,+ created_at: "2026-09-24T09:59:00",+ ...overrides,+ };+}++// claude-opus-5 at 5 / 25 / 0.50 / 6.25 per million: 1M output = $25.+function usage(outputTokens: number): TaskUsage[] {+ return [+ {+ provider: "anthropic",+ model: "claude-opus-5",+ input_tokens: 0,+ output_tokens: outputTokens,+ cache_read_tokens: 0,+ cache_write_tokens: 0,+ },+ ];+}++const NOW = new Date("2026-09-27T18:00:00").getTime();++describe("buildRunTimeline", () => {+ it("orders runs by start and falls back to dispatch, then creation", () => {+ const timeline = buildRunTimeline(+ [+ makeTask({ id: "late", started_at: "2026-09-25T09:00:00", completed_at: "2026-09-25T09:10:00" }),+ makeTask({+ id: "never-started",+ status: "cancelled",+ started_at: null,+ dispatched_at: null,+ created_at: "2026-09-24T08:00:00",+ completed_at: null,+ }),+ makeTask({ id: "dispatched", started_at: null, dispatched_at: "2026-09-24T09:00:00" }),+ ],+ NOW,+ );++ expect(timeline.runs.map((r) => r.task.id)).toEqual(["never-started", "dispatched", "late"]);+ // A run cancelled before it started still lands on the axis, as a sliver.+ const sliver = timeline.runs[0]!;+ expect(sliver.endMs).toBe(sliver.startMs);+ });++ it("stretches active runs to now and keeps them out of agent time", () => {+ const timeline = buildRunTimeline(+ [+ makeTask({ id: "done" }),+ makeTask({ id: "live", status: "running", started_at: "2026-09-27T17:00:00", completed_at: null }),+ ],+ NOW,+ );++ const live = timeline.runs.find((r) => r.task.id === "live")!;+ expect(live.active).toBe(true);+ expect(live.endMs).toBe(NOW);+ expect(timeline.activeCount).toBe(1);+ 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());+ });++ it("ignores deferred runs, which the execution log does not list", () => {+ const timeline = buildRunTimeline([makeTask({ status: "deferred" })], NOW);+ expect(timeline.runs).toHaveLength(0);+ });++ it("steps the cumulative cost at completion, in completion order", () => {+ // `a` starts first but finishes last; the curve must still only rise.+ const timeline = buildRunTimeline(+ [+ makeTask({ id: "a", started_at: "2026-09-24T10:00:00", completed_at: "2026-09-24T12:00:00", usage: usage(400_000) }),+ makeTask({ id: "b", started_at: "2026-09-24T10:30:00", completed_at: "2026-09-24T11:00: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.cumulative.map((s) => s.cost)).toEqual([5, 15]);+ expect(timeline.cumulative.map((s) => s.t)).toEqual([+ new Date("2026-09-24T11:00:00").getTime(),+ new Date("2026-09-24T12:00:00").getTime(),+ ]);+ expect(timeline.totalCost).toBe(15);+ expect(timeline.pricedCount).toBe(2);+ expect(timeline.maxRunCost).toBe(10);+ });++ it("keeps a run without usage at no figure, not $0", () => {+ const timeline = buildRunTimeline([makeTask({ usage: [] })], NOW);+ expect(timeline.runs[0]!.usage).toBeNull();+ expect(timeline.runs[0]!.breakdown).toBeNull();+ expect(timeline.pricedCount).toBe(0);+ });++ it("splits a run's cost by what was billed", () => {+ const timeline = buildRunTimeline([makeTask({ usage: usage(1_000_000) })], NOW);+ expect(timeline.runs[0]!.breakdown).toEqual({ input: 0, output: 25, cacheRead: 0, cacheWrite: 0 });+ });++ it("puts each agent in its own lane, in order of first appearance", () => {+ const timeline = buildRunTimeline(+ [+ makeTask({ id: "b1", agent_id: "agent-b", started_at: "2026-09-24T11:00:00" }),+ makeTask({ id: "a1", agent_id: "agent-a", started_at: "2026-09-24T10:00:00" }),+ makeTask({ id: "a2", agent_id: "agent-a", started_at: "2026-09-24T12:00:00", completed_at: "2026-09-24T12:30:00" }),+ ],+ NOW,+ );++ expect(timeline.lanes.map((l) => [l.agentId, l.runs.map((r) => r.task.id)])).toEqual([+ ["agent-a", ["a1", "a2"]],+ ["agent-b", ["b1"]],+ ]);+ });++ it("names a peak only when one run moved the total enough", () => {+ const dominant = buildRunTimeline(+ [+ makeTask({ id: "big", usage: usage(800_000) }),+ makeTask({ id: "small", started_at: "2026-09-24T11:00:00", completed_at: "2026-09-24T11:10:00", usage: usage(200_000) }),+ ],+ NOW,+ );+ expect(dominant.peak?.task.id).toBe("big");++ // Ten equal runs: the biggest is 10% of the total, which explains nothing.+ const even = buildRunTimeline(+ Array.from({ length: 10 }, (_, i) =>+ makeTask({+ id: `run-${i}`,+ started_at: `2026-09-24T1${i}:00:00`,+ completed_at: `2026-09-24T1${i}:10:00`,+ usage: usage(100_000),+ }),+ ),+ NOW,+ );+ expect(even.peak).toBeNull();+ });++ it("counts failed and cancelled runs", () => {+ const timeline = buildRunTimeline(+ [makeTask({ status: "failed" }), makeTask({ status: "cancelled" }), makeTask({ status: "cancelled" })],+ NOW,+ );+ expect([timeline.failedCount, timeline.cancelledCount]).toEqual([1, 2]);+ });++ it("widens a short span so a single run does not fill the axis", () => {+ const timeline = buildRunTimeline(+ [makeTask({ started_at: "2026-09-24T10:00:00", completed_at: "2026-09-24T10:00:14" })],+ NOW,+ );+ const [d0, d1] = timeline.domain;+ expect(d1 - d0).toBeGreaterThanOrEqual(60 * 60 * 1000);+ });+});++describe("costSoFar", () => {+ it("reads the curve at each run's end, unpriced runs included", () => {+ const timeline = buildRunTimeline(+ [+ makeTask({ id: "a", started_at: "2026-09-24T10:00:00", completed_at: "2026-09-24T10:30:00", usage: usage(400_000) }),+ makeTask({ id: "gap", status: "cancelled", started_at: "2026-09-24T11:00:00", completed_at: "2026-09-24T11:00:05" }),+ makeTask({ id: "b", started_at: "2026-09-24T12:00:00", completed_at: "2026-09-24T12:30:00", usage: usage(200_000) }),+ ],+ NOW,+ );+ expect(timeline.runs.map((r) => [r.task.id, r.costSoFar])).toEqual([+ ["a", 10],+ ["gap", 10],+ ["b", 15],+ ]);+ });+});++describe("nearestRunIndex", () => {+ const { runs } = buildRunTimeline(+ [+ makeTask({ id: "a", started_at: "2026-09-24T10:00:00", completed_at: "2026-09-24T10:30:00" }),+ makeTask({ id: "b", started_at: "2026-09-24T14:00:00", completed_at: "2026-09-24T14:00:20" }),+ ],+ NOW,+ );+ const at = (iso: string) => runs[nearestRunIndex(runs, new Date(iso).getTime())]!.task.id;++ it("picks the run under the pointer", () => {+ expect(at("2026-09-24T10:15:00")).toBe("a");+ });++ it("snaps to the nearest bar, however thin, when between runs", () => {+ expect(at("2026-09-24T11:00:00")).toBe("a");+ expect(at("2026-09-24T13:00:00")).toBe("b");+ expect(at("2026-09-25T00:00:00")).toBe("b");+ });++ it("reaches a run nested inside a longer one", () => {+ // Review repro: A 09:00–12:00 wraps B 10:00–11:00. Over B, B must win.+ const { runs: nested } = buildRunTimeline(+ [+ makeTask({ id: "outer", started_at: "2026-09-24T09:00:00", completed_at: "2026-09-24T12:00:00" }),+ makeTask({ id: "inner", started_at: "2026-09-24T10:00:00", completed_at: "2026-09-24T11:00:00" }),+ ],+ NOW,+ );+ const pick = (iso: string) => nested[nearestRunIndex(nested, new Date(iso).getTime())]!.task.id;+ expect(pick("2026-09-24T10:30:00")).toBe("inner");+ expect(pick("2026-09-24T09:30:00")).toBe("outer");+ expect(pick("2026-09-24T11:30:00")).toBe("outer");+ });++ it("stays in the lane the pointer is over", () => {+ const { runs: lanes } = buildRunTimeline(+ [+ makeTask({ id: "lambda", agent_id: "agent-lambda", started_at: "2026-09-24T10:00:00", completed_at: "2026-09-24T10:20:00" }),+ makeTask({ id: "emacs", agent_id: "agent-emacs", started_at: "2026-09-24T09:00:00", completed_at: "2026-09-24T12:00:00" }),+ ],+ NOW,+ );+ const t = new Date("2026-09-24T10:10:00").getTime();+ expect(lanes[nearestRunIndex(lanes, t)]!.task.id).toBe("lambda");+ expect(lanes[nearestRunIndex(lanes, t, "agent-emacs")]!.task.id).toBe("emacs");+ });++ it("has nothing to point at without runs", () => {+ expect(nearestRunIndex([], 0)).toBe(-1);+ });+});++describe("niceTicks", () => {+ it("steps in clean values and tops out at or above the max", () => {+ expect(niceTicks(166)).toEqual([50, 100, 150, 200]);+ expect(niceTicks(100)).toEqual([25, 50, 75, 100]);+ expect(niceTicks(2)).toEqual([0.5, 1, 1.5, 2]);+ expect(niceTicks(0.37)).toEqual([0.1, 0.2, 0.3, 0.4]);+ });++ it("has nothing to mark without a total", () => {+ expect(niceTicks(0)).toEqual([]);+ });+});++describe("timeTicks", () => {+ it("marks local midnights across a multi-day issue", () => {+ const ticks = timeTicks([+ new Date("2026-09-23T20:00:00").getTime(),+ new Date("2026-09-27T18:00:00").getTime(),+ ]);+ expect(ticks.every((t) => t.kind === "day")).toBe(true);+ expect(ticks.map((t) => new Date(t.t).getDate())).toEqual([24, 25, 26, 27]);+ expect(ticks.every((t) => new Date(t.t).getHours() === 0)).toBe(true);+ });++ it("marks whole hours when the issue fits in a day", () => {+ const ticks = timeTicks([+ new Date("2026-09-24T09:40:00").getTime(),+ new Date("2026-09-24T15:10:00").getTime(),+ ]);+ expect(ticks.every((t) => t.kind === "hour")).toBe(true);+ expect(ticks.map((t) => new Date(t.t).getHours())).toEqual([10, 11, 12, 13, 14, 15]);+ });++ it("thins daily ticks on a long issue", () => {+ const ticks = timeTicks([+ new Date("2026-08-01T00:00:00").getTime(),+ new Date("2026-09-27T00:00:00").getTime(),+ ]);+ expect(ticks.length).toBeLessThanOrEqual(8);+ });+});++describe("groupRunsByDay", () => {+ it("lists newest day first, newest run first, with day totals", () => {+ const { runs } = buildRunTimeline(+ [+ makeTask({ id: "d1-a", started_at: "2026-09-24T10:00:00", completed_at: "2026-09-24T10:30:00", usage: usage(200_000) }),+ makeTask({ id: "d1-b", started_at: "2026-09-24T15:00:00", completed_at: "2026-09-24T15:10:00", usage: usage(400_000) }),+ makeTask({ id: "d2-a", started_at: "2026-09-25T09:00:00", completed_at: "2026-09-25T09:20:00" }),+ ],+ NOW,+ );++ const groups = groupRunsByDay(runs);+ expect(groups.map((g) => g.runs.map((r) => r.task.id))).toEqual([["d2-a"], ["d1-b", "d1-a"]]);+ expect(groups[1]!.cost).toBe(15);+ expect(groups[1]!.agentMs).toBe(40 * 60 * 1000);+ });+});diff --git a/packages/views/issues/components/issue-run-timeline.ts b/packages/views/issues/components/issue-run-timeline.tsnew file mode 100644index 0000000000..8f44a1176f--- /dev/null+++ b/packages/views/issues/components/issue-run-timeline.ts@@ -0,0 +1,328 @@+import type { AgentTask } from "@multica/core/types";+import {+ estimateCostBreakdown,+ summarizeTaskUsage,+ type CostBreakdown,+ type TaskUsageSummary,+} 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.++const ACTIVE_STATUSES = new Set<AgentTask["status"]>([+ "queued",+ "dispatched",+ "waiting_local_directory",+ "running",+]);+const TERMINAL_STATUSES = new Set<AgentTask["status"]>([+ "completed",+ "failed",+ "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.+const PEAK_MIN_SHARE = 0.15;++export interface TimelineRun {+ task: AgentTask;+ /** When the run started working; falls back to dispatch, then creation. */+ startMs: number;+ /** When it finished, or `nowMs` for a run that is still active. */+ endMs: number;+ active: boolean;+ /** Finished-run wall time; null for active runs and runs that never started. */+ durationMs: number | null;+ /** Null when the run recorded no usage — "no figure", never "free". */+ usage: TaskUsageSummary | null;+ breakdown: CostBreakdown | null;+ /** The issue's running total once this run ended — what the curve reads there. */+ costSoFar: number;+}++export interface CumulativeStep {+ t: number;+ cost: number;+}++export interface TimelineLane {+ agentId: string;+ runs: TimelineRun[];+}++export interface RunTimeline {+ /** Oldest first. */+ runs: TimelineRun[];+ totalCost: number;+ pricedCount: number;+ /** Sum of finished runs' wall time. */+ agentMs: number;+ /** First start to last end (or now, while a run is active). */+ elapsedMs: number;+ failedCount: number;+ cancelledCount: number;+ activeCount: number;+ domain: [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;+ /** Highest single-run cost, for scaling per-run bars. */+ maxRunCost: number;+}++function parseMs(iso: string | null | undefined): number | null {+ if (!iso) return null;+ const ms = new Date(iso).getTime();+ return Number.isFinite(ms) ? ms : null;+}++function sumBreakdown(task: AgentTask): CostBreakdown | null {+ if (!task.usage || task.usage.length === 0) return null;+ const total: CostBreakdown = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };+ for (const slice of task.usage) {+ const b = estimateCostBreakdown(slice);+ total.input += b.input;+ total.output += b.output;+ total.cacheRead += b.cacheRead;+ total.cacheWrite += b.cacheWrite;+ }+ return total;+}++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;+ const startMs =+ parseMs(task.started_at) ?? parseMs(task.dispatched_at) ?? parseMs(task.created_at);+ if (startMs == null) return null;+ const completedMs = parseMs(task.completed_at);+ // A run cancelled before it ever started has no completion time on some+ // backends; pin it to its start so it still lands on the axis as a sliver.+ const endMs = active ? Math.max(nowMs, startMs) : Math.max(completedMs ?? startMs, startMs);+ const usage = summarizeTaskUsage(task.usage);+ return {+ task,+ startMs,+ endMs,+ active,+ durationMs: active ? null : taskDurationMs(task),+ usage,+ breakdown: usage ? sumBreakdown(task) : null,+ costSoFar: 0,+ };+}++export function buildRunTimeline(tasks: readonly AgentTask[], nowMs: number): RunTimeline {+ const runs = tasks+ .map((task) => toTimelineRun(task, nowMs))+ .filter((run): run is TimelineRun => run !== null)+ .toSorted((a, b) => a.startMs - b.startMs || a.endMs - b.endMs);++ let totalCost = 0;+ let pricedCount = 0;+ let agentMs = 0;+ let failedCount = 0;+ let cancelledCount = 0;+ let activeCount = 0;+ let maxRunCost = 0;+ const laneMap = new Map<string, TimelineRun[]>();++ for (const run of runs) {+ if (run.usage) {+ totalCost += run.usage.cost;+ pricedCount += 1;+ maxRunCost = Math.max(maxRunCost, run.usage.cost);+ }+ if (run.durationMs != null) agentMs += run.durationMs;+ if (run.task.status === "failed") failedCount += 1;+ if (run.task.status === "cancelled") cancelledCount += 1;+ if (run.active) activeCount += 1;+ const lane = laneMap.get(run.task.agent_id);+ if (lane) lane.push(run);+ else laneMap.set(run.task.agent_id, [run]);+ }++ // Usage is written when a run finishes, so the curve steps at completion —+ // and completion order is not start order when runs overlap.+ const cumulative: CumulativeStep[] = [];+ let running = 0;+ for (const run of runs.toSorted((a, b) => a.endMs - b.endMs)) {+ if (run.usage) {+ running += run.usage.cost;+ cumulative.push({ t: run.endMs, cost: running });+ }+ run.costSoFar = running;+ }++ const first = runs[0];+ const lastEnd = runs.reduce((m, r) => Math.max(m, r.endMs), first?.endMs ?? nowMs);+ const elapsedMs = first ? Math.max(0, lastEnd - first.startMs) : 0;++ let peak: TimelineRun | null = null;+ for (const run of runs) {+ if (run.usage && (!peak || run.usage.cost > peak.usage!.cost)) peak = run;+ }+ if (peak && (totalCost <= 0 || peak.usage!.cost / totalCost < PEAK_MIN_SHARE)) peak = null;++ return {+ runs,+ totalCost,+ pricedCount,+ agentMs,+ elapsedMs,+ failedCount,+ cancelledCount,+ activeCount,+ domain: paddedDomain(first?.startMs ?? nowMs, lastEnd),+ cumulative,+ lanes: Array.from(laneMap, ([agentId, laneRuns]) => ({ agentId, runs: laneRuns })),+ peak,+ maxRunCost,+ };+}++// 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;++function paddedDomain(start: number, end: number): [number, number] {+ let span = end - start;+ if (span < MIN_SPAN_MS) {+ const extra = (MIN_SPAN_MS - span) / 2;+ start -= extra;+ end += extra;+ span = MIN_SPAN_MS;+ }+ const pad = span * 0.02;+ return [start - pad, end + pad];+}++/**+ * Clean y-axis steps (1 / 2 / 2.5 / 5 × 10ⁿ), at most `maxCount` of them, the+ * last one at or above `max` — it doubles as the top of the scale.+ */+export function niceTicks(max: number, maxCount = 4): number[] {+ if (!(max > 0)) return [];+ const magnitude = 10 ** Math.floor(Math.log10(max / maxCount));+ // 10 × magnitude always satisfies the bound, so the fallback never fires.+ const step =+ [1, 2, 2.5, 5, 10].map((m) => m * magnitude).find((s) => max / s <= maxCount) ??+ 10 * magnitude;+ const ticks: number[] = [];+ for (let i = 1; ; i++) {+ const v = Number((step * i).toPrecision(12));+ ticks.push(v);+ if (v >= max) break;+ }+ return ticks;+}++/**+ * The run a pointer at time `t` is about: the one whose bar it is over, else+ * the one whose bar is nearest. Bars can be a few pixels wide, so the whole+ * chart snaps to runs rather than asking the pointer to land on one.+ *+ * Runs overlap — one agent's short run inside another's long one, or two+ * agents at once — so "the bar it is over" can be several. The shortest wins:+ * a bar fully inside another is otherwise unreachable, while the long one+ * still owns every moment the short one doesn't cover. `agentId` narrows the+ * choice to one lane when the pointer is over that lane.+ */+export function nearestRunIndex(+ runs: readonly TimelineRun[],+ t: number,+ agentId?: string,+): number {+ let best = -1;+ let bestDistance = Infinity;+ let bestSpan = Infinity;+ runs.forEach((run, i) => {+ if (agentId && run.task.agent_id !== agentId) return;+ const distance = t < run.startMs ? run.startMs - t : t > run.endMs ? t - run.endMs : 0;+ const span = run.endMs - run.startMs;+ if (distance < bestDistance || (distance === bestDistance && span < bestSpan)) {+ best = i;+ bestDistance = distance;+ bestSpan = span;+ }+ });+ return best;+}++export interface TimeTick {+ t: number;+ /** "day" ticks sit on local midnight; "hour" ticks on a whole hour. */+ kind: "day" | "hour";+}++const HOUR_MS = 60 * 60 * 1000;+const HOUR_STEPS = [1, 2, 3, 6, 12];++/**+ * X-axis ticks in local time. Past a day and a half the axis marks midnights+ * (labelled by weekday); shorter spans mark whole hours at a step that keeps+ * the count readable, because a single day label would leave the axis blank.+ */+export function timeTicks([start, end]: [number, number], maxTicks = 8): TimeTick[] {+ const span = end - start;+ if (!(span > 0)) return [];+ if (span > 36 * HOUR_MS) {+ const ticks: TimeTick[] = [];+ const d = new Date(start);+ d.setHours(0, 0, 0, 0);+ d.setDate(d.getDate() + 1);+ // Thin daily ticks for long issues so the labels never collide.+ const days = Math.ceil(span / (24 * HOUR_MS));+ const every = Math.max(1, Math.ceil(days / maxTicks));+ for (let i = 0; d.getTime() <= end; i++) {+ if (i % every === 0) ticks.push({ t: d.getTime(), kind: "day" });+ d.setDate(d.getDate() + 1);+ }+ return ticks;+ }+ const step = HOUR_STEPS.find((h) => span / (h * HOUR_MS) <= maxTicks) ?? 24;+ const d = new Date(start);+ d.setMinutes(0, 0, 0);+ while (d.getHours() % step !== 0 || d.getTime() <= start) d.setHours(d.getHours() + 1);+ const ticks: TimeTick[] = [];+ for (; d.getTime() < end; d.setHours(d.getHours() + step)) {+ ticks.push({ t: d.getTime(), kind: "hour" });+ }+ return ticks;+}++export interface RunDayGroup {+ /** Local midnight of the day. */+ dayMs: number;+ /** Newest first within the day. */+ runs: TimelineRun[];+ cost: number;+ agentMs: number;+}++/** Newest day first, newest run first — the order people scan a log in. */+export function groupRunsByDay(runs: readonly TimelineRun[]): RunDayGroup[] {+ const groups = new Map<number, RunDayGroup>();+ for (const run of runs.toSorted((a, b) => b.startMs - a.startMs)) {+ const day = new Date(run.startMs);+ day.setHours(0, 0, 0, 0);+ const key = day.getTime();+ let group = groups.get(key);+ if (!group) {+ group = { dayMs: key, runs: [], cost: 0, agentMs: 0 };+ groups.set(key, group);+ }+ group.runs.push(run);+ group.cost += run.usage?.cost ?? 0;+ group.agentMs += run.durationMs ?? 0;+ }+ return Array.from(groups.values());+}diff --git a/packages/views/issues/components/issue-runs-dialog.test.tsx b/packages/views/issues/components/issue-runs-dialog.test.tsxnew file mode 100644index 0000000000..14b6fcdb2a--- /dev/null+++ b/packages/views/issues/components/issue-runs-dialog.test.tsx@@ -0,0 +1,281 @@+// @vitest-environment jsdom++import { act, cleanup, fireEvent, screen, within } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { AgentTask, TaskUsage } from "@multica/core/types";+import { useCustomPricingStore } from "@multica/core/runtimes/custom-pricing-store";+import { renderWithI18n } from "../../test/i18n";++vi.mock("../../common/actor-avatar", () => ({+ ActorAvatar: () => <span data-testid="actor-avatar" />,+}));++vi.mock("../../common/task-transcript", () => ({+ TranscriptButton: ({ title }: { title?: string }) => (+ <button type="button">{title ?? "Transcript"}</button>+ ),+}));++vi.mock("@multica/core/workspace/hooks", () => ({+ useActorName: () => ({ getActorName: () => "Lambda" }),+}));++// The real label loads the issue's wakeup rules; the row only needs to use it.+vi.mock("./wakeup-source-chip", () => ({+ WakeupRunLabel: ({ render }: { render: (label: string) => React.ReactNode }) =>+ render("Wakeup · When CI finishes"),+}));++import { IssueRunsDialog } from "./issue-runs-dialog";++function makeTask(overrides: Partial<AgentTask> = {}): AgentTask {+ return {+ id: "task-1",+ agent_id: "agent-1",+ runtime_id: "runtime-1",+ issue_id: "issue-1",+ status: "completed",+ priority: 0,+ dispatched_at: null,+ started_at: "2026-09-27T09:00:00",+ completed_at: "2026-09-27T09:30:00",+ result: null,+ error: null,+ created_at: "2026-09-27T08:59:00",+ trigger_summary: "Initial run",+ ...overrides,+ };+}++// claude-opus-5 at 5 / 25 / 0.50 / 6.25 per million: 1M output = $25.+function usage(overrides: Partial<TaskUsage> = {}): TaskUsage {+ return {+ provider: "anthropic",+ model: "claude-opus-5",+ input_tokens: 0,+ output_tokens: 1_000_000,+ cache_read_tokens: 0,+ cache_write_tokens: 0,+ ...overrides,+ };+}++function open(tasks: AgentTask[], locale?: "zh-Hans") {+ return renderWithI18n(+ <IssueRunsDialog+ open+ onOpenChange={() => {}}+ issueId="issue-1"+ identifier="MUL-7680"+ issueTitle="Issue wakeups v2"+ tasks={tasks}+ />,+ { locale },+ );+}++beforeEach(() => {+ cleanup();+ vi.useFakeTimers({ toFake: ["Date"] });+ vi.setSystemTime(new Date("2026-09-27T18:00:00"));+});++afterEach(() => {+ vi.useRealTimers();+ useCustomPricingStore.setState({ pricings: {} });+ cleanup();+});++describe("IssueRunsDialog", () => {+ it("names the issue and sums what the runs spent and took", () => {+ open([+ makeTask({ id: "a", usage: [usage()] }),+ makeTask({+ id: "b",+ status: "failed",+ started_at: "2026-09-26T10:00:00",+ completed_at: "2026-09-26T10:15:00",+ usage: [usage({ output_tokens: 200_000 })],+ }),+ ]);++ 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!;+ expect(stat("Spent")).toHaveTextContent("$30.00");+ expect(stat("Agent time")).toHaveTextContent("45m");+ expect(stat("Elapsed")).toHaveTextContent("23h 30m");+ expect(screen.getByText(/1 failed/)).toBeInTheDocument();+ expect(+ screen.getByRole("img", { name: "Cumulative cost over time: $30.00 across 2 runs" }),+ ).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 })] }),+ makeTask({ id: "new", trigger_summary: "Newer run", usage: [usage()] }),+ ]);++ 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(yesterday).getByText("Older run")).toBeInTheDocument();+ expect(+ today.compareDocumentPosition(yesterday) & Node.DOCUMENT_POSITION_FOLLOWING,+ ).toBeTruthy();+ });++ it("quotes what a person said and cleans the snapshot's markdown", () => {+ open([+ makeTask({+ trigger_comment_id: "comment-1",+ trigger_summary: "@Lambda fix conflicts & ci",+ usage: [usage()],+ }),+ ]);++ expect(screen.getByText("“@Lambda fix conflicts & ci”")).toBeInTheDocument();+ });++ it("shows no figure — not $0 — for a run without usage", () => {+ open([+ makeTask({ id: "priced", usage: [usage()] }),+ makeTask({ id: "unpriced", status: "cancelled", started_at: "2026-09-27T10:00:00", completed_at: "2026-09-27T10:00:05" }),+ ]);++ expect(screen.getByTitle("No usage recorded")).toHaveTextContent("—");+ expect(screen.queryByText("$0.00")).not.toBeInTheDocument();+ expect(screen.getByText("Cancelled")).toBeInTheDocument();+ });++ it("gives every terminal run a status a screen reader can read", () => {+ // Completed rows show their duration; the status word must still be there.+ open([+ makeTask({ id: "ok", usage: [usage()] }),+ makeTask({ id: "bad", status: "failed", started_at: "2026-09-27T11:00:00", completed_at: "2026-09-27T11:05:00", usage: [usage()] }),+ ]);++ expect(screen.getByText("Completed")).toHaveClass("sr-only");+ expect(screen.getByText("Failed")).toBeInTheDocument();+ });++ it("flags models with no price on file", () => {+ open([makeTask({ usage: [usage({ provider: "acme", model: "made-up-model" })] })]);++ expect(screen.getByText(/No price on file for acme\/made-up-model/)).toBeInTheDocument();+ });++ it("re-prices when a custom model rate is saved", () => {+ // `estimateCost` reads the custom-rate store imperatively, so nothing+ // re-renders the dialog on a rate change unless it subscribes.+ open([+ makeTask({+ usage: [usage({ provider: "acme", model: "made-up-model", output_tokens: 0, input_tokens: 1_000_000 })],+ }),+ ]);+ expect(screen.queryByText("$7.00")).not.toBeInTheDocument();++ act(() => {+ useCustomPricingStore.getState().setCustomPricing("acme/made-up-model", {+ input: 7,+ output: 0,+ cacheRead: 0,+ cacheWrite: 0,+ });+ });++ expect(screen.getAllByText("$7.00").length).toBeGreaterThan(0);+ });++ it("answers a pointer anywhere on the chart with the nearest run", () => {+ 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 })] }),+ ]);+ // The plot column sits beside the lane labels; give it a width, which+ // jsdom does not lay out.+ const plot = screen.getByRole("img").children[1] as HTMLElement;+ plot.getBoundingClientRect = () => ({ left: 0, width: 1000, top: 0, height: 200, right: 1000, bottom: 200, x: 0, y: 0, toJSON: () => ({}) });++ // Far right, past the last bar: snaps to the last run.+ fireEvent.pointerMove(plot, { clientX: 995 });+ expect(within(plot).getByText("Late run")).toBeInTheDocument();+ expect(within(plot).getByText(/Total so far \$30\.00/)).toBeInTheDocument();++ // Far left: the first run, with the curve's reading there.+ fireEvent.pointerMove(plot, { clientX: 5 });+ expect(within(plot).getByText("Early run")).toBeInTheDocument();+ expect(within(plot).getByText(/Total so far \$25\.00/)).toBeInTheDocument();++ // Leaving hands the plot back to the peak label.+ fireEvent.pointerLeave(plot);+ expect(within(plot).queryByText(/Total so far/)).not.toBeInTheDocument();+ });++ it("picks the run on the lane under the pointer when runs overlap", () => {+ // Review repro: a short Emacs run inside a long Lambda run.+ open([+ 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 })] }),+ ]);+ const plot = screen.getByRole("img").children[1] as HTMLElement;+ plot.getBoundingClientRect = () => ({ left: 0, width: 1000, top: 0, height: 200, right: 1000, bottom: 200, x: 0, y: 0, toJSON: () => ({}) });+ const lane = (agentId: string) => plot.querySelector(`[data-lane="${agentId}"]`) as HTMLElement;+ // The x of 10:30 on the chart's padded domain.+ const [d0, d1] = [new Date("2026-09-27T09:00:00").getTime(), new Date("2026-09-27T12:00:00").getTime()];+ const pad = (d1 - d0) * 0.02;+ const x = ((new Date("2026-09-27T10:30:00").getTime() - (d0 - pad)) / (d1 - d0 + 2 * pad)) * 1000;++ fireEvent.pointerMove(lane("agent-lambda"), { clientX: x });+ expect(within(plot).getByText("Long run")).toBeInTheDocument();++ fireEvent.pointerMove(lane("agent-emacs"), { clientX: x });+ expect(within(plot).getByText("Short run")).toBeInTheDocument();+ });++ it("opens a run's cost split from a real button, not hover alone", () => {+ 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();++ fireEvent.click(button);+ expect(screen.getByText("claude-opus-5")).toBeInTheDocument();+ expect(screen.getByText("1M")).toBeInTheDocument();+ });++ it("names a wakeup run by its rule, not as a quote", () => {+ // A wakeup run carries the thread's comment id and the rule's instruction+ // as its summary; neither is something a person said.+ open([+ makeTask({+ wakeup_id: "wakeup-1",+ trigger_comment_id: "comment-1",+ trigger_summary: "Wakeup: check CI and fix it",+ usage: [usage()],+ }),+ ]);++ expect(screen.getByTitle("Wakeup · When CI finishes")).toHaveTextContent("Wakeup · When CI finishes");+ expect(screen.queryByText(/“/)).not.toBeInTheDocument();+ });++ it("keeps the whole trigger reachable when one line truncates it", () => {+ const long = "把之前拆出去的三个子任务都合并回这个 PR,conditions / history / runaway protection 一起做完再提交";+ open([makeTask({ trigger_comment_id: "comment-1", trigger_summary: long, usage: [usage()] })]);++ expect(screen.getByText(`“${long}”`)).toHaveAttribute("title", `“${long}”`);+ });++ it("renders in the member's language", () => {+ open([makeTask({ usage: [usage()] })], "zh-Hans");++ expect(screen.getByRole("heading", { name: "运行记录" })).toBeInTheDocument();+ expect(screen.getByRole("region", { name: "今天" })).toBeInTheDocument();+ });+});diff --git a/packages/views/issues/components/issue-runs-dialog.tsx b/packages/views/issues/components/issue-runs-dialog.tsxnew file mode 100644index 0000000000..1ed8362e74--- /dev/null+++ b/packages/views/issues/components/issue-runs-dialog.tsx@@ -0,0 +1,835 @@+"use client";++import { useMemo, useState } from "react";+import { ArrowRight, Ban, XCircle } from "lucide-react";+import type { AgentTask } from "@multica/core/types";+import { cn } from "@multica/ui/lib/utils";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ 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 { formatDuration } from "../../dashboard/utils";+import { useLocale, useT } from "../../i18n";+import {+ collectUnmappedModels,+ formatTokens,+ formatUsd,+ type CostBreakdown,+} from "../../runtimes/utils";+import { AttributionBadge } from "./attribution-badge";+import {+ buildRunTimeline,+ groupRunsByDay,+ nearestRunIndex,+ niceTicks,+ timeTicks,+ type RunTimeline,+ type TimelineRun,+} from "./issue-run-timeline";+import { canRetryRun, RetryRunButton } from "./retry-run-button";+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.+//+// 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.+//+// 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.+const COST_PARTS = [+ { key: "input", swatch: "bg-chart-1" },+ { key: "output", swatch: "bg-chart-2" },+ { key: "cacheRead", swatch: "bg-chart-4" },+ { key: "cacheWrite", swatch: "bg-chart-3" },+] as const satisfies readonly { key: keyof CostBreakdown; swatch: string }[];++type CostPartKey = (typeof COST_PARTS)[number]["key"];++function useCostPartLabel(): (key: CostPartKey) => string {+ const { t } = useT("issues");+ return (key) => {+ switch (key) {+ case "input": return t(($) => $.runs_timeline.cost_input);+ case "output": return t(($) => $.runs_timeline.cost_output);+ case "cacheRead": return t(($) => $.runs_timeline.cost_cache_read);+ case "cacheWrite": return t(($) => $.runs_timeline.cost_cache_write);+ }+ };+}++export function IssueRunsDialog({+ open,+ onOpenChange,+ issueId,+ identifier,+ issueTitle,+ tasks,+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ issueId: string;+ identifier: string;+ issueTitle?: string;+ tasks: AgentTask[];+}) {+ const { t } = useT("issues");+ // `estimateCost` reads custom rates imperatively out of the Zustand store,+ // so nothing re-renders this dialog when the user saves a new rate. Subscribe+ // to the snapshot and carry it into every memo that prices usage — same+ // reason the runtime usage page subscribes in usage-section.tsx.+ const pricings = useCustomPricingStore((s) => s.pricings);+ // Active runs stretch to "now". The clock is re-read when the task list+ // changes or the dialog reopens rather than ticking: the bars move by+ // minutes, and a live timer already runs in the sidebar row.+ const timeline = useMemo(+ () => buildRunTimeline(tasks, Date.now()),+ // `pricings` re-prices on a saved custom rate; `open` re-reads the clock.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ [tasks, pricings, open],+ );+ // Models with no rate-table entry and no provider-reported cost: their tokens+ // are counted but their spend is not, so the totals understate reality.+ const unmapped = useMemo(+ () => collectUnmappedModels(tasks.flatMap((task) => task.usage ?? [])),+ // eslint-disable-next-line react-hooks/exhaustive-deps -- `pricings` changes which models are priced+ [tasks, pricings],+ );++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ {/* DialogContent's base is `sm:max-w-sm`, which a same-specificity+ `max-w-5xl` does not beat — `!` wins it, matching the transcript+ dialog. Fixed height so the chart stays put while the list scrolls. */}+ <DialogContent className="flex !h-[min(56rem,calc(100dvh-4rem))] !w-[calc(100vw-4rem)] !max-w-5xl flex-col !gap-0 overflow-hidden !p-0">+ <DialogHeader className="px-6 pt-5 pb-4">+ <DialogTitle>{t(($) => $.runs_timeline.title)}</DialogTitle>+ <DialogDescription>+ {issueTitle ? `${identifier} · ${issueTitle}` : identifier}+ </DialogDescription>+ </DialogHeader>++ {timeline.runs.length > 0 && (+ <>+ <RunStats timeline={timeline} />+ <RunTimelineChart 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">+ <RunDayList timeline={timeline} issueId={issueId} />+ <div className="mt-4 space-y-1 text-micro text-muted-foreground">+ {unmapped.length > 0 && (+ <p>{t(($) => $.runs_timeline.note_unmapped, { models: unmapped.join(", ") })}</p>+ )}+ <p>{t(($) => $.runs_timeline.note_estimate)}</p>+ </div>+ </div>+ </>+ )}+ </DialogContent>+ </Dialog>+ );+}++// ─── Stats ─────────────────────────────────────────────────────────────────++function Stat({+ label,+ children,+}: {+ label: string;+ children: React.ReactNode;+}) {+ return (+ <div className="min-w-0">+ <div className="text-micro font-medium uppercase tracking-wider text-muted-foreground">+ {label}+ </div>+ <div className="mt-1">{children}</div>+ </div>+ );+}++// `formatDuration` falls back to this label only below one second.+const UNDER_A_SECOND = "0s";++function RunStats({ timeline }: { timeline: RunTimeline }) {+ const { t } = useT("issues");+ const breakdown = [+ timeline.failedCount > 0 &&+ t(($) => $.runs_timeline.count_failed, { count: timeline.failedCount }),+ timeline.cancelledCount > 0 &&+ t(($) => $.runs_timeline.count_cancelled, { count: timeline.cancelledCount }),+ timeline.activeCount > 0 &&+ t(($) => $.runs_timeline.count_active, { count: timeline.activeCount }),+ ].filter(Boolean);++ return (+ <div className="flex flex-wrap items-end gap-x-8 gap-y-3 px-6">+ <Stat label={t(($) => $.runs_timeline.stat_spent)}>+ {/* 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) : "—"}+ </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>+ </Stat>+ <Stat label={t(($) => $.runs_timeline.stat_runs)}>+ <span className="text-title-sm font-medium">{timeline.runs.length}</span>+ {breakdown.length > 0 && (+ <span className="ml-1.5 text-caption text-muted-foreground">+ · {breakdown.join(" · ")}+ </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;++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";+}++function RunTimelineChart({ timeline }: { timeline: RunTimeline }) {+ 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 tickFormat = 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 });+ return (tick: (typeof ticks)[number]) =>+ tick.kind === "day" ? day.format(tick.t) : hour.format(tick.t);+ }, [locale]);++ // 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;+ let line = `M0,100`;+ let prevY = 100;+ for (const step of steps) {+ const x = xPct(step.t) * 10;+ const y = yPct(step.cost);+ line += ` L${x.toFixed(2)},${prevY.toFixed(2)} L${x.toFixed(2)},${y.toFixed(2)}`;+ prevY = y;+ }+ line += ` L1000,${prevY.toFixed(2)}`;+ const area = `${line} L1000,100 L0,100 Z`;+ 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: anywhere over the plot column snaps to the nearest run — a+ // crosshair where it finished, the curve's reading there, and a card with the+ // run itself. Lane bars can be a few pixels wide, so asking the pointer to+ // land on one would make most of them unreachable. The list below carries the+ // same figures for keyboard and screen-reader users.+ const [hoverIndex, setHoverIndex] = useState<number | null>(null);+ const hovered = hoverIndex != null ? timeline.runs[hoverIndex] : undefined;+ const hoverX = hovered ? xPct(hovered.endMs) : 0;+ const trackPointer = (event: React.PointerEvent<HTMLDivElement>) => {+ const rect = event.currentTarget.getBoundingClientRect();+ if (rect.width <= 0) return;+ const t = 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]");+ const index = nearestRunIndex(timeline.runs, t, lane?.getAttribute("data-lane") ?? undefined);+ setHoverIndex(index >= 0 ? index : null);+ };+++ 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"+ >+ {/* 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("space-y-1.5", plotHeight > 0 && "mt-3")}>+ {timeline.lanes.map((lane) => (+ <div key={lane.agentId} className="flex h-3.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+ className="relative min-w-0 flex-1"+ onPointerMove={trackPointer}+ onPointerDown={trackPointer}+ onPointerLeave={() => setHoverIndex(null)}+ >+ {/* 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)}%` }}+ />+ )}+ {hovered && plotHeight > 0 && (+ <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: `${hoverX}%`, top: `${yPct(hovered.costSoFar)}%` }}+ />+ )}+ {peak && peakStep && !hovered && (+ <PeakLabel+ run={peak}+ style={{+ left: `${peakX}%`,+ top: `${yPct(peakStep.cost)}%`,+ transform:+ peakX >= 30+ ? "translate(calc(-100% - 6px), calc(-100% - 2px))"+ : "translate(6px, 4px)",+ }}+ />+ )}+ </div>++ <div className={cn("space-y-1.5", plotHeight > 0 && "mt-3")}>+ {timeline.lanes.map((lane) => (+ <div key={lane.agentId} data-lane={lane.agentId} 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",+ runBarTone(run, run === peak),+ hovered && run !== hovered && "opacity-35",+ )}+ style={{+ left: `${xPct(run.startMs)}%`,+ width: `${xPct(run.endMs) - xPct(run.startMs)}%`,+ }}+ />+ ))}+ </div>+ ))}+ </div>++ {hovered && (+ <>+ <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, so it never+ covers the point it describes. */}+ <div+ aria-hidden+ 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}%`,+ transform: hoverX > 55 ? "translateX(calc(-100% - 10px))" : "translateX(10px)",+ }}+ >+ <RunHoverCard run={hovered} />+ </div>+ </>+ )}++ <div className="relative mt-1 h-5" aria-hidden>+ {ticks.map((tick) => {+ const x = xPct(tick.t);+ 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>+ );+ })}+ </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>+ );+}++// 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);+}++/**+ * 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, style }: { run: TimelineRun; style: React.CSSProperties }) {+ const trigger = useTriggerText(run.task);+ return (+ <span+ className="absolute flex max-w-60 items-baseline gap-1 whitespace-nowrap text-micro"+ 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 }) {+ 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>+ );+}++// ─── List ──────────────────────────────────────────────────────────────────++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(() => {+ const fmt = new Intl.DateTimeFormat(locale, { weekday: "short", month: "short", day: "numeric" });+ const today = new Date();+ today.setHours(0, 0, 0, 0);+ const yesterday = new Date(today);+ yesterday.setDate(today.getDate() - 1);+ return (dayMs: number) => {+ if (dayMs === today.getTime()) return t(($) => $.runs_timeline.day_today);+ if (dayMs === yesterday.getTime()) return t(($) => $.runs_timeline.day_yesterday);+ return fmt.format(dayMs);+ };+ }, [locale, t]);++ 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>+ );+}++function RunListRow({+ run,+ issueId,+ maxCost,+}: {+ run: TimelineRun;+ issueId: string;+ maxCost: number;+}) {+ const { t } = useT("issues");+ const { t: tAgents } = useT("agents");+ const locale = useLocale();+ const { getActorName } = useActorName();+ const trigger = useTriggerText(run.task);+ const statusLabel = useStatusLabel(run.task.status);+ const task = run.task;+ const time = new Intl.DateTimeFormat(locale, {+ hour: "2-digit",+ minute: "2-digit",+ hour12: false,+ }).format(run.startMs);+ // Comment-triggered runs quote what the person said; structural triggers+ // (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;++ 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>+ ) : (+ <>+ <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>+ <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>+ <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>+ </div>+ );+}++function CostCell({ run, maxCost }: { run: TimelineRun; maxCost: number }) {+ const { t } = useT("issues");+ 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,+ };++ // 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>+ )}+ </PopoverContent>+ </Popover>+ );+}++// 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,+}: {+ breakdown: CostBreakdown;+ total: number;+ widthPx: number;+}) {+ 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>+ );+}diff --git a/packages/views/issues/components/issue-usage-dialog.test.tsx b/packages/views/issues/components/issue-usage-dialog.test.tsxdeleted file mode 100644index 1025a62121..0000000000--- a/packages/views/issues/components/issue-usage-dialog.test.tsx+++ /dev/null@@ -1,143 +0,0 @@-// @vitest-environment jsdom--import { cleanup, screen } from "@testing-library/react";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import type { AgentTask, TaskUsage } from "@multica/core/types";-import { renderWithI18n } from "../../test/i18n";--vi.mock("../../common/actor-avatar", () => ({- ActorAvatar: () => <span data-testid="actor-avatar" />,-}));--import { IssueUsageDialog } from "./issue-usage-dialog";--function makeTask(overrides: Partial<AgentTask> = {}): AgentTask {- return {- id: "task-1",- agent_id: "agent-1",- runtime_id: "runtime-1",- issue_id: "issue-1",- status: "completed",- priority: 0,- dispatched_at: null,- started_at: "2026-08-05T08:00:00Z",- completed_at: "2026-08-05T08:11:00Z",- result: null,- error: null,- created_at: "2026-08-05T08:00:00Z",- trigger_summary: "Initial run",- ...overrides,- };-}--function usage(overrides: Partial<TaskUsage> = {}): TaskUsage {- return {- provider: "anthropic",- model: "claude-opus-5",- input_tokens: 1_000,- output_tokens: 1_000,- cache_read_tokens: 1_000,- cache_write_tokens: 0,- ...overrides,- };-}--function open(tasks: AgentTask[]) {- renderWithI18n(- <IssueUsageDialog open onOpenChange={() => {}} identifier="ACM-1" tasks={tasks} />,- );-}--beforeEach(() => {- cleanup();- vi.clearAllMocks();-});--afterEach(cleanup);--describe("IssueUsageDialog", () => {- it("includes cache writes in the cache hit-rate denominator", () => {- open([- makeTask({- usage: [- usage({- input_tokens: 0,- output_tokens: 0,- cache_read_tokens: 72_000,- cache_write_tokens: 28_000,- }),- ],- }),- ]);-- expect(screen.getByText(/72% hit rate/)).toBeInTheDocument();- });-- it("does not round an incomplete cache hit rate up to 100%", () => {- // 99.55% — rounding would print "100% hit rate" and claim every token came- // from cache on an issue that plainly read some fresh input.- open([- makeTask({- usage: [usage({ input_tokens: 573_500, cache_read_tokens: 126_000_000 })],- }),- ]);-- expect(screen.getByText(/99% hit rate/)).toBeInTheDocument();- expect(screen.queryByText(/100% hit rate/)).not.toBeInTheDocument();- });-- it("still says 100% when the hit rate really is 100%", () => {- open([- makeTask({ usage: [usage({ input_tokens: 0, cache_read_tokens: 1_000 })] }),- ]);-- expect(screen.getByText(/100% hit rate/)).toBeInTheDocument();- });-- it("shows an unavailable hit rate when no input-side tokens were reported", () => {- open([- makeTask({- usage: [- usage({- input_tokens: 0,- output_tokens: 1_000,- cache_read_tokens: 0,- cache_write_tokens: 0,- }),- ],- }),- ]);-- expect(screen.getByText("—")).toBeInTheDocument();- expect(screen.queryByText(/0% hit rate/)).not.toBeInTheDocument();- });-- it("keeps the full model list reachable when the cell truncates", () => {- // A run that spilled across models carries ids long enough to set the- // table's width on their own; the cell is capped, so the untruncated list- // has to survive somewhere.- const models = "claude-haiku-4-5-20251001, claude-opus-5[1m]";- open([- makeTask({- usage: [- usage({ model: "claude-haiku-4-5-20251001" }),- usage({ model: "claude-opus-5[1m]" }),- ],- }),- ]);-- expect(screen.getByTitle(models)).toBeInTheDocument();- });-- it("gives every terminal run a status a screen reader can read", () => {- // The status glyph is aria-hidden, so without the paired label a failed- // run and a completed one are indistinguishable to assistive tech.- open([- makeTask({ id: "t-ok", usage: [usage()] }),- makeTask({ id: "t-bad", status: "failed", usage: [usage()] }),- ]);-- expect(screen.getByText("Completed")).toBeInTheDocument();- expect(screen.getByText("Failed")).toBeInTheDocument();- });-});diff --git a/packages/views/issues/components/issue-usage-dialog.tsx b/packages/views/issues/components/issue-usage-dialog.tsxdeleted file mode 100644index c55cfb050a..0000000000--- a/packages/views/issues/components/issue-usage-dialog.tsx+++ /dev/null@@ -1,396 +0,0 @@-"use client";--import { useMemo } from "react";-import type { AgentTask } from "@multica/core/types";-import {- Dialog,- DialogContent,- DialogDescription,- DialogHeader,- DialogTitle,-} from "@multica/ui/components/ui/dialog";-import { useActorName } from "@multica/core/workspace/hooks";-import { useCustomPricingStore } from "@multica/core/runtimes/custom-pricing-store";-import { ActorAvatar } from "../../common/actor-avatar";-import { useT } from "../../i18n";-import { formatDuration } from "../../agents/components/agent-activity-hover-content";-import {- cacheHitRatePercent,- collectUnmappedModels,- formatTokens,- formatUsd,- summarizeTaskUsage,- summarizeTaskUsageAcross,- type TaskUsageSummary,-} from "../../runtimes/utils";-import { KpiCard } from "../../runtimes/components/shared";-import { useStatusLabel, useTriggerText } from "./task-run-labels";-import { WakeupRunLabel } from "./wakeup-source-chip";-import { TaskStatusIcon } from "./task-status-icon";--// Per-run cost breakdown for one issue — the surface the execution log's-// header total opens.-//-// The execution log answers "how much did this run cost" one row at a time;-// this answers "which run cost the most, and why". That comparison needs the-// input / output / cache split side by side, which the 288px sidebar cannot-// hold, so it lives here instead of expanding the rows.-//-// Every figure comes from the same `summarizeTaskUsage` helpers the sidebar-// uses, so the total here can never disagree with the total that opened it.--export function IssueUsageDialog({- open,- onOpenChange,- identifier,- tasks,-}: {- open: boolean;- onOpenChange: (open: boolean) => void;- identifier: string;- tasks: AgentTask[];-}) {- const { t } = useT("issues");- // `estimateCost` reads custom rates imperatively out of the Zustand store,- // so nothing re-renders this dialog when the user saves a new rate. Subscribe- // to the snapshot and carry it into every memo that prices usage — otherwise- // the totals, the per-run costs, and the "unmapped model" notice all keep- // showing the old price until the task list happens to refetch. Same reason- // the runtime usage page subscribes in usage-section.tsx.- const pricings = useCustomPricingStore((s) => s.pricings);-- // Only runs that actually recorded usage earn a row: a run with no figure- // contributes nothing to compare and would just add an all-em-dash line.- // Their existence is still accounted for in the footnote below.- const priced = useMemo(- () => tasks.filter((task) => (task.usage?.length ?? 0) > 0),- [tasks],- );- const unpricedCount = tasks.length - priced.length;-- const total = useMemo(- () => summarizeTaskUsageAcross(priced.map((task) => task.usage)),- [priced, pricings],- );-- const agentIds = useMemo(- () => Array.from(new Set(priced.map((task) => task.agent_id).filter(Boolean))),- [priced],- );-- // Models with no rate-table entry and no provider-reported cost: their- // tokens are counted but their spend is not, so the totals below understate- // reality. Saying so is the difference between an estimate and a wrong number.- const unmapped = useMemo(- () => collectUnmappedModels(priced.flatMap((task) => task.usage ?? [])),- [priced, pricings],- );-- const cacheHitRate =- total == null- ? null- : cacheHitRatePercent(total.input, total.cacheRead, total.cacheWrite);-- return (- <Dialog open={open} onOpenChange={onOpenChange}>- {/* DialogContent's base is `sm:max-w-sm`, which the same-specificity- `max-w-4xl` does not beat — the table then overflows the box instead- of the box growing. `!` wins it, matching the transcript dialog.- 5xl rather than 4xl because nine columns plus the token bar need- ~920px: at 4xl the Cost column — the one people open this for —- landed outside the scroll viewport. */}- <DialogContent className="!max-w-5xl !w-[calc(100vw-4rem)]">- <DialogHeader>- <DialogTitle>{t(($) => $.usage_detail.title)}</DialogTitle>- <DialogDescription>- {t(($) => $.usage_detail.subtitle, {- identifier,- count: priced.length,- })}- </DialogDescription>- </DialogHeader>-- {total == null ? (- <p className="py-8 text-center text-body text-muted-foreground">- {t(($) => $.usage_detail.empty)}- </p>- ) : (- /* `min-w-0`: DialogContent is a grid, and a grid item defaults to- `min-width: auto` — it sizes to its content's minimum rather than- to the track. Without this the wide run table pushes this column- past the dialog's own max-width, and every sibling (KPI cards,- by-agent bars, footnotes) stretches with it and paints outside- the box. */- <div className="flex min-w-0 flex-col gap-5">- <div className="grid grid-cols-3 divide-x rounded-lg border bg-card">- <KpiCard- label={t(($) => $.usage_detail.kpi_cost)}- value={formatUsd(total.cost)}- hint={<CostConcentrationHint tasks={priced} total={total} />}- />- <KpiCard- label={t(($) => $.usage_detail.kpi_cache)}- value={formatUsd(total.cacheSavings)}- accent={total.cacheSavings > 0 ? "success" : "default"}- hint={- cacheHitRate == null- ? "—"- : t(($) => $.usage_detail.kpi_cache_hint, {- pct: cacheHitRate,- reads: formatTokens(total.cacheRead),- })- }- />- <KpiCard- label={t(($) => $.usage_detail.kpi_tokens)}- value={formatTokens(total.tokens)}- hint={t(($) => $.usage_detail.kpi_tokens_hint, {- input: formatTokens(total.input),- output: formatTokens(total.output),- })}- />- </div>-- {agentIds.length > 1 && (- <CostByAgent tasks={priced} agentIds={agentIds} total={total} />- )}-- <RunTable tasks={priced} total={total} />-- <div className="space-y-1 text-micro text-muted-foreground">- {unpricedCount > 0 && (- <p>{t(($) => $.usage_detail.note_unpriced, { count: unpricedCount })}</p>- )}- {unmapped.length > 0 && (- <p>- {t(($) => $.usage_detail.note_unmapped, { models: unmapped.join(", ") })}- </p>- )}- <p>{t(($) => $.usage_detail.note_estimate)}</p>- </div>- </div>- )}- </DialogContent>- </Dialog>- );-}--// "N failed runs account for X%" — the single most useful thing the total can-// say about itself, and the reason this dialog exists. Rendered only when-// there IS a failed run with a cost, so a healthy issue gets no scolding hint.-function CostConcentrationHint({- tasks,- total,-}: {- tasks: AgentTask[];- total: TaskUsageSummary;-}) {- const { t } = useT("issues");- const failed = tasks.filter((task) => task.status === "failed");- if (failed.length === 0 || total.cost <= 0) return null;-- const failedCost = failed.reduce(- (sum, task) => sum + (summarizeTaskUsage(task.usage)?.cost ?? 0),- 0,- );- if (failedCost <= 0) return null;-- return (- <span className="text-warning">- {t(($) => $.usage_detail.kpi_cost_hint, {- count: failed.length,- pct: Math.round((failedCost / total.cost) * 100),- })}- </span>- );-}--// Same bar language as the runtime usage page's "Cost by agent" block: one row-// per agent, bar scaled to the biggest spender. Hidden entirely for a-// single-agent issue, where a one-bar chart says nothing the total didn't.-function CostByAgent({- tasks,- agentIds,- total,-}: {- tasks: AgentTask[];- agentIds: string[];- total: TaskUsageSummary;-}) {- const { t } = useT("issues");- const { getActorName } = useActorName();- const pricings = useCustomPricingStore((s) => s.pricings);-- const rows = useMemo(() => {- return agentIds- .map((agentId) => {- const own = tasks.filter((task) => task.agent_id === agentId);- const summary = summarizeTaskUsageAcross(own.map((task) => task.usage));- return { agentId, cost: summary?.cost ?? 0, tokens: summary?.tokens ?? 0 };- })- .toSorted((a, b) => b.cost - a.cost);- }, [agentIds, tasks, pricings]);-- const maxCost = rows.reduce((m, r) => Math.max(m, r.cost), 0);-- return (- <div>- <div className="mb-2 text-caption font-medium">- {t(($) => $.usage_detail.by_agent)}- </div>- <div className="space-y-2">- {rows.map((row) => (- <div- key={row.agentId}- className="grid grid-cols-[minmax(0,1fr)_minmax(0,2fr)_5rem_4rem] items-center gap-3"- >- <div className="flex min-w-0 items-center gap-2">- <ActorAvatar actorType="agent" actorId={row.agentId} size="sm" enableHoverCard />- <span className="truncate text-caption">- {getActorName("agent", row.agentId)}- </span>- </div>- <div className="relative h-2 overflow-hidden rounded-full bg-muted">- <div- className="h-full rounded-full bg-chart-1"- style={{ width: `${maxCost > 0 ? (row.cost / maxCost) * 100 : 0}%` }}- />- </div>- <div className="text-right text-caption tabular-nums text-muted-foreground">- {formatTokens(row.tokens)}- </div>- <div className="text-right text-caption font-medium tabular-nums">- {formatUsd(row.cost)}- </div>- </div>- ))}- </div>- <div className="sr-only">- {t(($) => $.usage_detail.by_agent_total, { cost: formatUsd(total.cost) })}- </div>- </div>- );-}--function RunTable({ tasks, total }: { tasks: AgentTask[]; total: TaskUsageSummary }) {- const { t } = useT("issues");- const maxTokens = tasks.reduce(- (m, task) => Math.max(m, summarizeTaskUsage(task.usage)?.tokens ?? 0),- 0,- );-- return (- // Nine columns of numbers have a floor width; on a narrow window they- // scroll sideways rather than squeezing the trigger text to nothing or- // pushing the totals outside the dialog.- //- // `min-w-0` is what makes `overflow-auto` actually clip: as a flex item- // this box defaults to `min-width: auto`, so it grows to the table's- // min-content width and never scrolls. Removing it puts the table back- // outside the dialog.- <div className="max-h-[45vh] min-w-0 overflow-auto">- <table className="w-full min-w-[46rem]">- <thead className="sticky top-0 bg-popover">- <tr className="text-micro text-muted-foreground [&>th]:whitespace-nowrap [&>th]:px-2 [&>th]:pb-1.5 [&>th]:text-right [&>th]:font-normal">- <th className="!pl-0 !text-left">{t(($) => $.usage_detail.col_run)}</th>- <th>{t(($) => $.usage_detail.col_model)}</th>- <th>{t(($) => $.usage_detail.col_duration)}</th>- <th>{t(($) => $.usage_detail.col_input)}</th>- <th>{t(($) => $.usage_detail.col_output)}</th>- <th>{t(($) => $.usage_detail.col_cache_read)}</th>- <th>{t(($) => $.usage_detail.col_cache_write)}</th>- <th className="!pr-16">{t(($) => $.usage_detail.col_tokens)}</th>- <th className="!pr-0">{t(($) => $.usage_detail.col_cost)}</th>- </tr>- </thead>- <tbody>- {tasks.map((task) => (- <RunRow key={task.id} task={task} maxTokens={maxTokens} />- ))}- </tbody>- <tfoot>- <tr className="text-caption font-medium tabular-nums [&>td]:whitespace-nowrap [&>td]:border-t [&>td]:border-input [&>td]:px-2 [&>td]:py-2 [&>td]:text-right">- <td className="!pl-0 !text-left">{t(($) => $.usage_detail.total)}</td>- <td colSpan={2} />- <td>{formatTokens(total.input)}</td>- <td>{formatTokens(total.output)}</td>- <td>{formatTokens(total.cacheRead)}</td>- <td>{formatTokens(total.cacheWrite)}</td>- <td className="!pr-16">{formatTokens(total.tokens)}</td>- <td className="!pr-0">{formatUsd(total.cost)}</td>- </tr>- </tfoot>- </table>- </div>- );-}--function RunRow({ task, maxTokens }: { task: AgentTask; maxTokens: number }) {- const { t } = useT("issues");- const trigger = useTriggerText(task);- const statusLabel = useStatusLabel(task.status);- const summary = summarizeTaskUsage(task.usage);- if (!summary) return null;-- const duration =- task.started_at && task.completed_at- ? formatDuration(task.started_at, new Date(task.completed_at).getTime())- : "";-- return (- <tr className="text-caption tabular-nums transition-colors hover:bg-accent/40 [&>td]:whitespace-nowrap [&>td]:border-t [&>td]:px-2 [&>td]:py-1.5 [&>td]:text-right">- <td className="!pl-0 !text-left">- <div className="flex items-center gap-2">- <ActorAvatar actorType="agent" actorId={task.agent_id} size="sm" enableHoverCard />- <span className="max-w-[13rem] truncate">- {task.wakeup_id ? <WakeupRunLabel task={task} fallback={trigger} render={(label) => label} /> : trigger}- </span>- {task.status === "running" ? (- <span className="inline-flex shrink-0 items-center gap-1 text-micro text-info">- <span className="h-1.5 w-1.5 rounded-full bg-info" />- {t(($) => $.execution_log.status_running)}- </span>- ) : (- <>- {/* TaskStatusIcon is aria-hidden, so the glyph alone leaves a- screen reader with no way to tell a failed run from a- completed one. Same sr-only pairing the execution log rows- use. */}- <TaskStatusIcon status={task.status} />- <span className="sr-only">{statusLabel}</span>- </>- )}- </div>- </td>- {/* A run that spilled across models lists them all, and real model ids- are long (`claude-haiku-4-5-20251001, claude-opus-5[1m]`). Left- uncapped that single cell sets the table's width and forces every- other issue's dialog to scroll sideways, so cap it and keep the full- list in the title. `whitespace-nowrap` comes from the row, so the- cell needs its own width bound for `truncate` to have anything to- truncate against. */}- <td className="max-w-[11rem] text-micro text-muted-foreground">- <span className="block truncate" title={summary.models.join(", ")}>- {summary.models.join(", ") || "—"}- </span>- </td>- <td className="text-muted-foreground">{duration || "—"}</td>- <td>{formatTokens(summary.input)}</td>- <td>{formatTokens(summary.output)}</td>- <td>{formatTokens(summary.cacheRead)}</td>- <td>{formatTokens(summary.cacheWrite)}</td>- <td className="!pr-2">- <div className="flex items-center justify-end gap-2">- <span>{formatTokens(summary.tokens)}</span>- <span className="relative h-1 w-14 overflow-hidden rounded-full bg-muted">- <span- className="absolute inset-y-0 left-0 rounded-full bg-chart-1"- style={{ width: `${maxTokens > 0 ? (summary.tokens / maxTokens) * 100 : 0}%` }}- />- </span>- </div>- </td>- <td className="!pr-0 font-medium">{formatUsd(summary.cost)}</td>- </tr>- );-}diff --git a/packages/views/issues/components/retry-run-button.tsx b/packages/views/issues/components/retry-run-button.tsxnew file mode 100644index 0000000000..779c67ec3e--- /dev/null+++ b/packages/views/issues/components/retry-run-button.tsx@@ -0,0 +1,76 @@+"use client";++import { useState } from "react";+import { Loader2, RotateCcw } from "lucide-react";+import { toast } from "sonner";+import { api, dispatchReasonCode } from "@multica/core/api";+import type { AgentTask } from "@multica/core/types";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@multica/ui/components/ui/tooltip";+import { useT } from "../../i18n";++/** Retry only makes sense for terminal-but-not-success runs. */+export function canRetryRun(task: AgentTask): boolean {+ return task.status === "failed" || task.status === "cancelled";+}++// Re-runs one specific past run. Shared by the execution log's rows and the+// Runs dialog so a failed run retries the same way wherever it is listed.+export function RetryRunButton({ task, issueId }: { task: AgentTask; issueId: string }) {+ const { t } = useT("issues");+ const [retrying, setRetrying] = useState(false);++ const handleRetry = async () => {+ if (retrying) return;+ setRetrying(true);+ try {+ // Passing task.id targets this row's agent — without it, the rerun+ // endpoint would fall back to the issue's current assignee and the wrong+ // agent would fire on rows whose agent has since been displaced+ // (reassignment, squad worker, or a one-off @-mention agent).+ await api.rerunIssue(issueId, task.id);+ } catch (e) {+ // A rerun is re-gated on the operator's invoke permission (MUL-4525): a+ // structured 403 means the agent can't be triggered, not a transient+ // failure — localize it instead of echoing the server's generic message.+ toast.error(+ dispatchReasonCode(e) === "invocation_not_allowed"+ ? t(($) => $.execution_log.retry_blocked)+ : e instanceof Error+ ? e.message+ : t(($) => $.execution_log.retry_failed),+ );+ } finally {+ // Reset on both success and failure: the row stays mounted (its task.id+ // is unchanged), so leaving `retrying` true on success would pin the+ // button as a permanent spinner.+ setRetrying(false);+ }+ };++ return (+ <Tooltip>+ <TooltipTrigger+ render={+ <button+ type="button"+ onClick={handleRetry}+ disabled={retrying}+ aria-label={t(($) => $.execution_log.retry_task_aria)}+ />+ }+ className="flex items-center justify-center rounded-xs p-1 text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50"+ >+ {retrying ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <RotateCcw className="h-3.5 w-3.5" />+ )}+ </TooltipTrigger>+ <TooltipContent>{t(($) => $.execution_log.retry_task_tooltip)}</TooltipContent>+ </Tooltip>+ );+}diff --git a/packages/views/issues/components/task-run-labels.test.ts b/packages/views/issues/components/task-run-labels.test.tsnew file mode 100644index 0000000000..4b6bd449a9--- /dev/null+++ b/packages/views/issues/components/task-run-labels.test.ts@@ -0,0 +1,47 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import { plainTriggerSummary } from "./task-run-labels";++const IMAGE = "[Image]";++describe("plainTriggerSummary", () => {+ it("decodes the entities the editor escapes", () => {+ expect(plainTriggerSummary("@Lambda fix conflicts & ci", IMAGE)).toBe(+ "@Lambda fix conflicts & ci",+ );+ expect(plainTriggerSummary("a <b> "c" 'd'", IMAGE)).toBe(+ `a <b> "c" 'd'`,+ );+ });++ it("decodes in one pass, so an escaped entity reads as typed", () => {+ expect(plainTriggerSummary("write &lt; for <", IMAGE)).toBe("write < for <");+ });++ it("replaces a whole image with the image label", () => {+ expect(+ plainTriggerSummary(" 这里的间距不对", IMAGE),+ ).toBe("[Image] 这里的间距不对");+ });++ it("replaces an image the snapshot cut mid-way", () => {+ // The server cuts at ~200 runes and appends "…", usually inside the URL.+ expect(+ plainTriggerSummary("看看这个 ![CleanShot 2026-09-26 at [email protected]](https://multica-app.example/api/attach…", IMAGE),+ ).toBe("看看这个 [Image]");+ expect(plainTriggerSummary("![CleanShot 2026-09-26 at 23.2…", IMAGE)).toBe("[Image]");+ });++ it("keeps a link's text and a mention's name", () => {+ expect(+ plainTriggerSummary("@[docs](https://example.com) and [@Lambda](mention://agent/abc) please", IMAGE),+ ).toBe("@docs and @Lambda please");+ expect(plainTriggerSummary("see [the spec](https://example.com/very/lo…", IMAGE)).toBe(+ "see the spec…",+ );+ });++ it("collapses whitespace into one line", () => {+ expect(plainTriggerSummary(" first line\n\nsecond ", IMAGE)).toBe("first line second");+ });+});diff --git a/packages/views/issues/components/task-run-labels.ts b/packages/views/issues/components/task-run-labels.tsindex 371d043c4e..64576acf98 100644--- a/packages/views/issues/components/task-run-labels.ts+++ b/packages/views/issues/components/task-run-labels.ts@@ -3,9 +3,9 @@ import { useT } from "../../i18n";import { stripMentionMarkdown } from "../utils/strip-mention-markdown";// Display labels shared by every surface that lists an issue's agent runs:-// the execution log rows and the usage-detail dialog. They live here rather-// than in either component so the two can't drift — a run must read the same-// in the sidebar and in the table it opens.+// the execution log rows and the Runs dialog. They live here rather than in+// either component so the two can't drift — a run must read the same in the+// sidebar and in the timeline it opens./*** Human label for what caused this run.@@ -37,7 +37,12 @@ export function useTriggerText(task: AgentTask): string {// the wakeup instead. WakeupRunLabel adds the rule's condition.if (task.wakeup_id) return retryPrefix + t(($) => $.wakeups.triggered_by_wakeup);- if (task.trigger_summary) return retryPrefix + stripMentionMarkdown(task.trigger_summary);+ if (task.trigger_summary) {+ return (+ retryPrefix ++ plainTriggerSummary(task.trigger_summary, t(($) => $.execution_log.trigger_image))+ );+ }if (isRetry) {return task.attempt && task.attempt > 1? t(($) => $.execution_log.trigger_retry_attempt, { attempt: task.attempt })@@ -48,6 +53,38 @@ export function useTriggerText(task: AgentTask): string {return t(($) => $.execution_log.trigger_initial);}+const HTML_ENTITIES: Record<string, string> = {+ amp: "&",+ lt: "<",+ gt: ">",+ quot: '"',+ "#39": "'",+ "#x27": "'",+ nbsp: " ",+};++/**+ * One-line plain text for a trigger snapshot.+ *+ * The snapshot is the comment's raw Markdown cut at ~200 runes (with a+ * trailing "…"), so a list row rendering it verbatim showed `&` for an+ * ampersand the editor escaped, and a comment that opens with a screenshot as+ * `![CleanShot 2026-…` — the cut usually lands inside the image's URL. Images+ * become `imageLabel` (whole or cut), links become their text, mentions their+ * name, entities their character. Decoding is a single pass, so `&lt;`+ * reads `<` exactly as the author typed it.+ */+export function plainTriggerSummary(raw: string, imageLabel: string): string {+ return stripMentionMarkdown(raw)+ .replace(/!\[[^\]]*\]\([^)]*\)/g, imageLabel)+ .replace(/!\[[^\]]*(?:\]\([^)]*)?…?$/, imageLabel)+ .replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")+ .replace(/\[([^\]]*)\]\([^)]*…$/, "$1…")+ .replace(/&(amp|lt|gt|quot|#39|#x27|nbsp);/g, (_, name: string) => HTML_ENTITIES[name] ?? "")+ .replace(/\s+/g, " ")+ .trim();+}+export function useStatusLabel(status: AgentTask["status"]): string {const { t } = useT("issues");switch (status) {diff --git a/packages/views/issues/components/task-status-icon.tsx b/packages/views/issues/components/task-status-icon.tsxindex a45f119874..93a659f4c2 100644--- a/packages/views/issues/components/task-status-icon.tsx+++ b/packages/views/issues/components/task-status-icon.tsx@@ -2,7 +2,7 @@ import { Ban, CheckCircle2, XCircle } from "lucide-react";import type { AgentTask } from "@multica/core/types";// Terminal-status glyph for one agent run. Shared by the execution log rows-// and the usage-detail dialog so a failed run carries the same mark wherever+// and the Runs dialog so a failed run carries the same mark wherever// it is listed. Non-terminal statuses render nothing: those rows carry a live// timer or a status word instead, and a glyph next to either reads as a// second, contradictory status.diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.jsonindex 34e41b9d04..102c533f45 100644--- a/packages/views/locales/en/agents.json+++ b/packages/views/locales/en/agents.json@@ -850,6 +850,7 @@"status_cancelled": "Cancelled","status_waiting": "Waiting","trigger_initial": "Initial run",+ "trigger_text": "Trigger","trigger_comment": "From a comment","trigger_autopilot": "Autopilot","trigger_retry": "Retry",diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex 8d11947b2d..50c6917939 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -712,8 +712,6 @@},"execution_log": {"section": "Execution log",- "show_past": "Show past runs ({{count}})",- "hide_past": "Hide past runs ({{count}})","cancel_task_tooltip": "Cancel run","cancel_task_aria": "Cancel run","retry_task_tooltip": "Retry run",@@ -750,35 +748,48 @@"source_backfill": "Backfilled attribution","source_unattributed": "No responsible member resolved"},- "usage_total_tooltip": "Token usage for this issue — click for the per-run breakdown",- "trigger_wakeup": "Wakeup · {{condition}}"+ "usage_total_tooltip": "Open the run timeline",+ "trigger_wakeup": "Wakeup · {{condition}}",+ "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": "Cost of each run, oldest to newest — open the run timeline",+ "strip_no_usage": "No usage recorded"},- "usage_detail": {- "title": "Usage breakdown",- "subtitle_one": "{{identifier}} · {{count}} run",- "subtitle_other": "{{identifier}} · {{count}} runs",- "empty": "No run on this issue has recorded token usage yet.",- "kpi_cost": "Cost",- "kpi_cost_hint_one": "{{count}} failed run accounts for {{pct}}%",- "kpi_cost_hint_other": "{{count}} failed runs account for {{pct}}%",- "kpi_cache": "Cache savings",- "kpi_cache_hint": "{{pct}}% hit rate · {{reads}} read",- "kpi_tokens": "Tokens",- "kpi_tokens_hint": "{{input}} in · {{output}} out",- "by_agent": "By agent",- "by_agent_total": "Total {{cost}}",- "col_run": "Run",- "col_model": "Model",- "col_duration": "Duration",- "col_input": "In",- "col_output": "Out",- "col_cache_read": "Cache R",- "col_cache_write": "Cache W",- "col_tokens": "Tokens",- "col_cost": "Cost",- "total": "Total",- "note_unpriced_one": "{{count}} run has no recorded usage and is not counted in the total.",- "note_unpriced_other": "{{count}} runs have no recorded usage and are not counted in the total.",+ "runs_timeline": {+ "title": "Runs",+ "stat_spent": "Spent",+ "stat_agent_time": "Agent time",+ "stat_elapsed": "Elapsed",+ "stat_runs": "Runs",+ "count_failed_one": "{{count}} failed",+ "count_failed_other": "{{count}} failed",+ "count_cancelled_one": "{{count}} cancelled",+ "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",+ "day_today": "Today",+ "day_yesterday": "Yesterday",+ "day_runs_one": "{{count}} run",+ "day_runs_other": "{{count}} runs",+ "quoted": "“{{text}}”",+ "cost_input": "Input",+ "cost_output": "Output",+ "cost_cache_read": "Cache read",+ "cost_cache_write": "Cache write",+ "cost_breakdown_aria": "Cost breakdown: {{cost}}",+ "no_usage": "No usage recorded",+ "tooltip_total": "Total so far {{cost}}","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."},diff --git a/packages/views/locales/fr/agents.json b/packages/views/locales/fr/agents.jsonindex 3f40cc016c..d8da015ac9 100644--- a/packages/views/locales/fr/agents.json+++ b/packages/views/locales/fr/agents.json@@ -850,6 +850,7 @@"status_cancelled": "Annulée","status_waiting": "En attente","trigger_initial": "Exécution initiale",+ "trigger_text": "Déclencheur","trigger_comment": "Depuis un commentaire","trigger_autopilot": "Automatisation","trigger_retry": "Relance",diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.jsonindex fb77576c08..3692209d3e 100644--- a/packages/views/locales/fr/issues.json+++ b/packages/views/locales/fr/issues.json@@ -712,8 +712,6 @@},"execution_log": {"section": "Journal d'exécution",- "show_past": "Afficher les exécutions passées ({{count}})",- "hide_past": "Masquer les exécutions passées ({{count}})","cancel_task_tooltip": "Annuler l'exécution","cancel_task_aria": "Annuler l'exécution","retry_task_tooltip": "Relancer l'exécution",@@ -750,35 +748,48 @@"source_backfill": "Attribution reconstituée","source_unattributed": "Aucun membre responsable identifié"},- "usage_total_tooltip": "Consommation de tokens pour cette tâche — cliquez pour le détail par exécution",- "trigger_wakeup": "Réveil · {{condition}}"+ "usage_total_tooltip": "Ouvrir la chronologie des exécutions",+ "trigger_wakeup": "Réveil · {{condition}}",+ "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 de chaque exécution, de la plus ancienne à la plus récente — ouvrir la chronologie",+ "strip_no_usage": "Aucune consommation enregistrée"},- "usage_detail": {- "title": "Détail de la consommation",- "subtitle_one": "{{identifier}} · {{count}} exécution",- "subtitle_other": "{{identifier}} · {{count}} exécutions",- "empty": "Aucune exécution de cette tâche n'a encore enregistré de consommation de tokens.",- "kpi_cost": "Coût",- "kpi_cost_hint_one": "{{count}} exécution en échec représente {{pct}} %",- "kpi_cost_hint_other": "{{count}} exécutions en échec représentent {{pct}} %",- "kpi_cache": "Économies de cache",- "kpi_cache_hint": "{{pct}} % de succès · {{reads}} lecture",- "kpi_tokens": "Tokens",- "kpi_tokens_hint": "{{input}} entrée · {{output}} sortie",- "by_agent": "Par agent",- "by_agent_total": "Total {{cost}}",- "col_run": "Exécution",- "col_model": "Modèle",- "col_duration": "Durée",- "col_input": "Entrée",- "col_output": "Sortie",- "col_cache_read": "Cache L",- "col_cache_write": "Cache É",- "col_tokens": "Tokens",- "col_cost": "Coût",- "total": "Total",- "note_unpriced_one": "{{count}} exécution n'a aucune consommation enregistrée et n'est pas comptée dans le total.",- "note_unpriced_other": "{{count}} exécutions n'ont aucune consommation enregistrée et ne sont pas comptées dans le total.",+ "runs_timeline": {+ "title": "Exécutions",+ "stat_spent": "Dépensé",+ "stat_agent_time": "Travail d'agent",+ "stat_elapsed": "Écoulé",+ "stat_runs": "Exécutions",+ "count_failed_one": "{{count}} en échec",+ "count_failed_other": "{{count}} en échec",+ "count_cancelled_one": "{{count}} annulée",+ "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",+ "day_today": "Aujourd'hui",+ "day_yesterday": "Hier",+ "day_runs_one": "{{count}} exécution",+ "day_runs_other": "{{count}} exécutions",+ "quoted": "« {{text}} »",+ "cost_input": "Entrée",+ "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",+ "tooltip_total": "Cumul : {{cost}}","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."},diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.jsonindex f4d31a5465..fa15b07f02 100644--- a/packages/views/locales/ja/agents.json+++ b/packages/views/locales/ja/agents.json@@ -733,6 +733,7 @@"status_cancelled": "キャンセル","status_waiting": "待機中","trigger_initial": "初回実行",+ "trigger_text": "トリガー","trigger_comment": "コメントから","trigger_autopilot": "オートパイロット","trigger_retry": "再試行",diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.jsonindex e6598b4e31..2529c638be 100644--- a/packages/views/locales/ja/issues.json+++ b/packages/views/locales/ja/issues.json@@ -685,8 +685,6 @@},"execution_log": {"section": "実行ログ",- "show_past": "過去の実行を表示 ({{count}})",- "hide_past": "過去の実行を非表示 ({{count}})","cancel_task_tooltip": "実行をキャンセル","cancel_task_aria": "実行をキャンセル","retry_task_tooltip": "実行を再試行",@@ -722,32 +720,41 @@"source_backfill": "バックフィルされた帰属","source_unattributed": "責任メンバーを解決できません"},- "usage_total_tooltip": "このタスクのトークン使用量 — クリックで実行ごとの内訳",- "trigger_wakeup": "起動 · {{condition}}"+ "usage_total_tooltip": "実行タイムラインを開く",+ "trigger_wakeup": "起動 · {{condition}}",+ "trigger_image": "[画像]",+ "summary_runs_other": "{{count}} 回の実行",+ "agent_time": "エージェント作業 {{duration}}",+ "elapsed": "経過 {{duration}}",+ "latest": "最新",+ "open_timeline": "タイムラインを開く",+ "more_runs_other": "他 {{count}} 件",+ "strip_aria": "各実行の費用(古い順)— 実行タイムラインを開く",+ "strip_no_usage": "使用量の記録なし"},- "usage_detail": {- "title": "使用量の内訳",- "subtitle_other": "{{identifier}} · {{count}} 回の実行",- "empty": "このタスクでは、まだトークン使用量が記録された実行はありません。",- "kpi_cost": "費用",- "kpi_cost_hint_other": "失敗した {{count}} 回の実行が {{pct}}% を占めます",- "kpi_cache": "キャッシュ削減",- "kpi_cache_hint": "ヒット率 {{pct}}% · 読み取り {{reads}}",- "kpi_tokens": "トークン",- "kpi_tokens_hint": "入力 {{input}} · 出力 {{output}}",- "by_agent": "エージェント別",- "by_agent_total": "合計 {{cost}}",- "col_run": "実行",- "col_model": "モデル",- "col_duration": "所要時間",- "col_input": "入力",- "col_output": "出力",- "col_cache_read": "キャッシュ読",- "col_cache_write": "キャッシュ書",- "col_tokens": "トークン",- "col_cost": "費用",- "total": "合計",- "note_unpriced_other": "{{count}} 回の実行は使用量が記録されておらず、合計に含まれません。",+ "runs_timeline": {+ "title": "実行履歴",+ "stat_spent": "費用",+ "stat_agent_time": "エージェント作業",+ "stat_elapsed": "経過時間",+ "stat_runs": "実行回数",+ "count_failed_other": "失敗 {{count}}",+ "count_cancelled_other": "キャンセル {{count}}",+ "count_active_other": "進行中 {{count}}",+ "legend_cumulative": "累計費用",+ "legend_run": "実行 · 幅は所要時間",+ "chart_aria_other": "累計費用の推移:{{count}} 回の実行で {{cost}}",+ "day_today": "今日",+ "day_yesterday": "昨日",+ "day_runs_other": "{{count}} 回",+ "quoted": "「{{text}}」",+ "cost_input": "入力",+ "cost_output": "出力",+ "cost_cache_read": "キャッシュ読み取り",+ "cost_cache_write": "キャッシュ書き込み",+ "cost_breakdown_aria": "費用の内訳:{{cost}}",+ "no_usage": "使用量の記録なし",+ "tooltip_total": "累計 {{cost}}","note_unmapped": "{{models}} は価格が未登録です。トークンは集計されますが費用は含まれません。","note_estimate": "費用は公開モデル料金からの概算です(プロバイダーが独自の費用を返した分を除く)。"},diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.jsonindex ddbc3087c7..ce16757513 100644--- a/packages/views/locales/ko/agents.json+++ b/packages/views/locales/ko/agents.json@@ -741,6 +741,7 @@"status_cancelled": "취소됨","status_waiting": "대기 중","trigger_initial": "최초 실행",+ "trigger_text": "트리거","trigger_comment": "댓글에서","trigger_autopilot": "오토파일럿","trigger_retry": "재시도",diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.jsonindex adcf98d0de..a5b92ff6a1 100644--- a/packages/views/locales/ko/issues.json+++ b/packages/views/locales/ko/issues.json@@ -685,8 +685,6 @@},"execution_log": {"section": "실행 로그",- "show_past": "이전 실행 보기 ({{count}})",- "hide_past": "이전 실행 숨기기 ({{count}})","cancel_task_tooltip": "실행 취소","cancel_task_aria": "실행 취소","retry_task_tooltip": "실행 다시 시도",@@ -722,32 +720,41 @@"source_backfill": "백필된 귀속","source_unattributed": "책임 멤버를 확인할 수 없음"},- "usage_total_tooltip": "이 태스크의 토큰 사용량 — 클릭하면 실행별 내역",- "trigger_wakeup": "깨우기 · {{condition}}"+ "usage_total_tooltip": "실행 타임라인 열기",+ "trigger_wakeup": "깨우기 · {{condition}}",+ "trigger_image": "[이미지]",+ "summary_runs_other": "실행 {{count}}회",+ "agent_time": "에이전트 작업 {{duration}}",+ "elapsed": "경과 {{duration}}",+ "latest": "최근",+ "open_timeline": "타임라인 열기",+ "more_runs_other": "{{count}}개 더",+ "strip_aria": "실행별 비용(오래된 순) — 실행 타임라인 열기",+ "strip_no_usage": "사용량 기록 없음"},- "usage_detail": {- "title": "사용량 내역",- "subtitle_other": "{{identifier}} · 실행 {{count}}회",- "empty": "이 태스크에서 토큰 사용량이 기록된 실행이 아직 없습니다.",- "kpi_cost": "비용",- "kpi_cost_hint_other": "실패한 실행 {{count}}회가 {{pct}}%를 차지합니다",- "kpi_cache": "캐시 절감",- "kpi_cache_hint": "적중률 {{pct}}% · 읽기 {{reads}}",- "kpi_tokens": "토큰",- "kpi_tokens_hint": "입력 {{input}} · 출력 {{output}}",- "by_agent": "에이전트별",- "by_agent_total": "합계 {{cost}}",- "col_run": "실행",- "col_model": "모델",- "col_duration": "소요 시간",- "col_input": "입력",- "col_output": "출력",- "col_cache_read": "캐시 읽기",- "col_cache_write": "캐시 쓰기",- "col_tokens": "토큰",- "col_cost": "비용",- "total": "합계",- "note_unpriced_other": "실행 {{count}}회는 사용량 기록이 없어 합계에 포함되지 않습니다.",+ "runs_timeline": {+ "title": "실행 기록",+ "stat_spent": "비용",+ "stat_agent_time": "에이전트 작업",+ "stat_elapsed": "경과 시간",+ "stat_runs": "실행",+ "count_failed_other": "실패 {{count}}회",+ "count_cancelled_other": "취소 {{count}}회",+ "count_active_other": "진행 중 {{count}}회",+ "legend_cumulative": "누적 비용",+ "legend_run": "실행 · 너비는 소요 시간",+ "chart_aria_other": "시간에 따른 누적 비용: 실행 {{count}}회, 총 {{cost}}",+ "day_today": "오늘",+ "day_yesterday": "어제",+ "day_runs_other": "실행 {{count}}회",+ "quoted": "“{{text}}”",+ "cost_input": "입력",+ "cost_output": "출력",+ "cost_cache_read": "캐시 읽기",+ "cost_cache_write": "캐시 쓰기",+ "cost_breakdown_aria": "비용 내역: {{cost}}",+ "no_usage": "사용량 기록 없음",+ "tooltip_total": "누적 {{cost}}","note_unmapped": "{{models}}의 가격 정보가 없어 토큰은 집계되지만 비용은 포함되지 않습니다.","note_estimate": "비용은 공개된 모델 요금 기준 추정치이며, 제공자가 자체 비용을 보고한 경우는 그 값을 사용합니다."},diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.jsonindex b679f65d9c..69c29cf472 100644--- a/packages/views/locales/zh-Hans/agents.json+++ b/packages/views/locales/zh-Hans/agents.json@@ -835,6 +835,7 @@"status_cancelled": "已取消","status_waiting": "等待中","trigger_initial": "初次运行",+ "trigger_text": "触发内容","trigger_comment": "评论触发","trigger_autopilot": "自动化","trigger_retry": "重试",diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.jsonindex 99ec88b06d..07cfb8030a 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -685,8 +685,6 @@},"execution_log": {"section": "执行日志",- "show_past": "显示历史运行({{count}})",- "hide_past": "隐藏历史运行({{count}})","cancel_task_tooltip": "取消运行","cancel_task_aria": "取消运行","retry_task_tooltip": "重试运行",@@ -722,32 +720,41 @@"source_backfill": "回填的归因","source_unattributed": "未解析到责任成员"},- "usage_total_tooltip": "这个任务的 token 用量——点击查看每次运行的明细",- "trigger_wakeup": "由唤醒触发 · {{condition}}"+ "usage_total_tooltip": "打开运行时间线",+ "trigger_wakeup": "由唤醒触发 · {{condition}}",+ "trigger_image": "[图片]",+ "summary_runs_other": "{{count}} 次运行",+ "agent_time": "智能体工作 {{duration}}",+ "elapsed": "历时 {{duration}}",+ "latest": "最近",+ "open_timeline": "打开时间线",+ "more_runs_other": "还有 {{count}} 次",+ "strip_aria": "每次运行的费用,从早到晚——打开运行时间线",+ "strip_no_usage": "没有用量记录"},- "usage_detail": {- "title": "用量明细",- "subtitle_other": "{{identifier}} · {{count}} 次运行",- "empty": "这个任务还没有任何一次运行记录到 token 用量。",- "kpi_cost": "费用",- "kpi_cost_hint_other": "{{count}} 次失败运行占 {{pct}}%",- "kpi_cache": "缓存节省",- "kpi_cache_hint": "命中率 {{pct}}% · 读取 {{reads}}",- "kpi_tokens": "Token",- "kpi_tokens_hint": "输入 {{input}} · 输出 {{output}}",- "by_agent": "按智能体分摊",- "by_agent_total": "合计 {{cost}}",- "col_run": "运行",- "col_model": "模型",- "col_duration": "时长",- "col_input": "输入",- "col_output": "输出",- "col_cache_read": "缓存读",- "col_cache_write": "缓存写",- "col_tokens": "Token",- "col_cost": "费用",- "total": "合计",- "note_unpriced_other": "有 {{count}} 次运行没有用量记录,不计入合计。",+ "runs_timeline": {+ "title": "运行记录",+ "stat_spent": "已花费",+ "stat_agent_time": "智能体工作",+ "stat_elapsed": "历时",+ "stat_runs": "运行次数",+ "count_failed_other": "{{count}} 次失败",+ "count_cancelled_other": "{{count}} 次取消",+ "count_active_other": "{{count}} 次进行中",+ "legend_cumulative": "累计费用",+ "legend_run": "运行 · 宽度为时长",+ "chart_aria_other": "累计费用随时间的变化:{{count}} 次运行,共 {{cost}}",+ "day_today": "今天",+ "day_yesterday": "昨天",+ "day_runs_other": "{{count}} 次运行",+ "quoted": "“{{text}}”",+ "cost_input": "输入",+ "cost_output": "输出",+ "cost_cache_read": "缓存读",+ "cost_cache_write": "缓存写",+ "cost_breakdown_aria": "费用明细:{{cost}}",+ "no_usage": "没有用量记录",+ "tooltip_total": "累计 {{cost}}","note_unmapped": "{{models}} 没有维护价格,token 已计入,费用未计入。","note_estimate": "费用按各模型公开价目估算;供应商回报实际费用时以回报值为准。"},