diff --git a/components/ChatWindow-transcript-group-row.tsx b/components/ChatWindow-transcript-group-row.tsx
index 8d78ef59e..b4ab92f5b 100644
--- a/components/ChatWindow-transcript-group-row.tsx
+++ b/components/ChatWindow-transcript-group-row.tsx
@@ -5,6 +5,8 @@ import { ChevronDown, Layers } from "lucide-react";
import type { AgentMessage, AssistantContentBlock, AssistantMessage } from "@/lib/types";
import { useI18n } from "@/lib/i18n";
import type { ActivityPiece, TranscriptRow } from "@/lib/chat-transcript-plan";
+import { formatTokens } from "@/lib/subagent-format";
+import { formatTurnDuration, summarizeTurnStats, type TurnStats } from "@/lib/turn-stats";
/** Renders one committed message, optionally as a partial/overridden view under its own key prefix. */
export type RenderMessage = (idx: number, options?: { attachRef?: boolean; keyPrefix?: string; messageOverride?: AgentMessage; showTimestamp?: boolean; sourceBlockIndices?: number[] }) => ReactNode;
@@ -32,13 +34,25 @@ function withAssistantBlocks(
return next;
}
-function ProcessDetailsGroup({ messageCount, toolCallCount, children }: { messageCount: number; toolCallCount: number; children: () => ReactNode }) {
+function ProcessDetailsGroup({ messageCount, toolCallCount, turnStats, children }: { messageCount: number; toolCallCount: number; turnStats?: TurnStats | null; children: () => ReactNode }) {
const { t, tn } = useI18n();
const [expanded, setExpanded] = useState(false);
// A finished turn folds to one summary row ("Completed N steps · M tool
// calls"); the final reply stays expanded above it. Live turns stay flat.
const parts = [tn("chatWindow.completedSteps", messageCount)];
if (toolCallCount > 0) parts.push(tn("chatWindow.toolCallCount", toolCallCount));
+ // First slice of #392: the turn's duration and token totals ride on the
+ // same summary line. Either part is omitted when its data is unavailable,
+ // so a missing timestamp or missing usage never renders as zero.
+ const duration = formatTurnDuration(turnStats?.durationMs ?? null);
+ if (duration) parts.push(duration);
+ if (turnStats && turnStats.inputTokens !== null) {
+ parts.push(t("chatWindow.turnTokens", {
+ input: formatTokens(turnStats.inputTokens) ?? "0",
+ output: formatTokens(turnStats.outputTokens ?? 0) ?? "0",
+ cached: formatTokens(turnStats.cacheReadTokens ?? 0) ?? "0",
+ }));
+ }
return (
@@ -108,6 +122,10 @@ export function renderTranscriptGroupRow(row: TranscriptGroupRow, { messages, re
}
rendered.push(renderMessage(userIdx));
+ // Per-turn duration/token totals for the Process details summary (#392,
+ // first slice): one aggregate for the whole turn, shown on each of its
+ // folded rows.
+ const turnStats = summarizeTurnStats(messages, userIdx, endIdx);
// A message split across segments keeps its navigation ref on the first one.
const attached = new Set
();
segments.forEach((segment, segmentIdx) => {
@@ -136,7 +154,7 @@ export function renderTranscriptGroupRow(row: TranscriptGroupRow, { messages, re
key={`activity-${userIdx}-${segmentIdx}`}
ref={refIdx === undefined ? undefined : (el) => { messageRefs.current[refIdx] = el; }}
>
-
+
{() => renderActivityPieces(messages, segment.pieces, renderMessage)}
,
diff --git a/components/ChatWindow.activity.test.mjs b/components/ChatWindow.activity.test.mjs
index 1eabff18a..9b37ed6f0 100644
--- a/components/ChatWindow.activity.test.mjs
+++ b/components/ChatWindow.activity.test.mjs
@@ -36,6 +36,61 @@ test("folded activity keeps tool calls from separate messages as separate entrie
assert.equal(new Set(calls.map(({ idx, options }) => `${options.keyPrefix}-${idx}`)).size, calls.length);
});
+test("a finished turn shows duration and token totals in the Process details summary", async () => {
+ const React = (await import("react")).default;
+ const { renderToStaticMarkup } = await import("react-dom/server");
+ const { renderTranscriptGroupRow } = await import("./ChatWindow-transcript-group-row.tsx");
+ const { planTranscriptRows } = await import("../lib/chat-transcript-plan.ts");
+ const zeroCost = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 };
+ const messages = [
+ { role: "user", content: "go", timestamp: 1_000_000 },
+ { ...assistant([call("a")]), timestamp: 1_005_000, usage: { input: 12_000, output: 3_000, cacheRead: 8_000, cacheWrite: 0, cost: zeroCost } },
+ { ...assistant([{ type: "text", text: "done" }]), timestamp: 1_072_000, usage: { input: 500, output: 200, cacheRead: 100, cacheWrite: 0, cost: zeroCost } },
+ ];
+ const rows = planTranscriptRows(messages, {});
+ const group = rows.find((row) => row.kind === "group");
+ assert.ok(group, "a turn with tool activity must plan as a group row");
+ const rendered = renderTranscriptGroupRow(group, {
+ messages,
+ renderMessage: (idx) => React.createElement("div", { key: `msg-${idx}` }, `msg-${idx}`),
+ flat: false,
+ messageRefs: { current: [] },
+ visibleRefIndexByMessage: new Map(),
+ });
+ const html = renderToStaticMarkup(React.createElement(React.Fragment, null, ...rendered));
+ // 72 s from the user message to the final reply, 13k in / 3.2k out /
+ // 8.1k cached across both model requests in the turn.
+ assert.match(html, /1m 12s/, `the folded row must show the turn duration, got: ${html.slice(0, 400)}`);
+ assert.match(html, /13k in · 3\.2k out · 8\.1k cached|chatWindow\.turnTokens/, `the folded row must show the turn token totals, got: ${html.slice(0, 400)}`);
+});
+
+test("a finished turn without timestamps or usage shows no stats in the summary", async () => {
+ const React = (await import("react")).default;
+ const { renderToStaticMarkup } = await import("react-dom/server");
+ const { renderTranscriptGroupRow } = await import("./ChatWindow-transcript-group-row.tsx");
+ const { planTranscriptRows } = await import("../lib/chat-transcript-plan.ts");
+ const messages = [
+ { role: "user", content: "go" },
+ assistant([call("a")]),
+ assistant([{ type: "text", text: "done" }]),
+ ];
+ const rows = planTranscriptRows(messages, {});
+ const group = rows.find((row) => row.kind === "group");
+ assert.ok(group, "a turn with tool activity must plan as a group row");
+ const rendered = renderTranscriptGroupRow(group, {
+ messages,
+ renderMessage: (idx) => React.createElement("div", { key: `msg-${idx}` }, `msg-${idx}`),
+ flat: false,
+ messageRefs: { current: [] },
+ visibleRefIndexByMessage: new Map(),
+ });
+ const html = renderToStaticMarkup(React.createElement(React.Fragment, null, ...rendered));
+ // Missing data renders as nothing, never as zero.
+ assert.doesNotMatch(html, /chatWindow\.turnTokens/);
+ assert.doesNotMatch(html, /\d+(\.\d+)?k in/);
+ assert.match(html, /Completed \d+ steps?|chatWindow\.completedSteps/);
+});
+
test("a finished turn folds its activity into one Completed N steps row", async () => {
const React = (await import("react")).default;
const { renderToStaticMarkup } = await import("react-dom/server");
diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json
index 214a4de5a..1b5df6830 100644
--- a/lib/i18n/locales/en.json
+++ b/lib/i18n/locales/en.json
@@ -663,6 +663,7 @@
"chatWindow.todoStatus.pending": "Pending",
"chatWindow.toolCallCount.one": "{count} tool call",
"chatWindow.toolCallCount.other": "{count} tool calls",
+ "chatWindow.turnTokens": "{input} in · {output} out · {cached} cached",
"chatWindow.versionNotFound": "not found",
"chatWindow.waitingModel": "Waiting for model...",
"subagentTranscript.title": "Subagent transcript",
diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json
index c81980bd9..4a090aa01 100644
--- a/lib/i18n/locales/ja.json
+++ b/lib/i18n/locales/ja.json
@@ -642,6 +642,7 @@
"chatWindow.todoStatus.pending": "未着手",
"chatWindow.toolCallCount.one": "{count} 件のツール呼び出し",
"chatWindow.toolCallCount.other": "{count} 件のツール呼び出し",
+ "chatWindow.turnTokens": "入力 {input} · 出力 {output} · キャッシュ読取 {cached}",
"chatWindow.versionNotFound": "見つかりません",
"chatWindow.waitingModel": "モデルの応答を待機中...",
"subagentTranscript.title": "サブエージェントのトランスクリプト",
diff --git a/lib/i18n/locales/zh-CN.json b/lib/i18n/locales/zh-CN.json
index 6a9e39c6d..799f9a094 100644
--- a/lib/i18n/locales/zh-CN.json
+++ b/lib/i18n/locales/zh-CN.json
@@ -642,6 +642,7 @@
"chatWindow.todoStatus.pending": "待处理",
"chatWindow.toolCallCount.one": "{count} 次工具调用",
"chatWindow.toolCallCount.other": "{count} 次工具调用",
+ "chatWindow.turnTokens": "输入 {input} · 输出 {output} · 缓存 {cached}",
"chatWindow.versionNotFound": "未找到",
"chatWindow.waitingModel": "等待模型响应...",
"subagentTranscript.title": "子代理对话记录",
diff --git a/lib/i18n/locales/zh-TW.json b/lib/i18n/locales/zh-TW.json
index 7ddbbc268..26887fb8f 100644
--- a/lib/i18n/locales/zh-TW.json
+++ b/lib/i18n/locales/zh-TW.json
@@ -663,6 +663,7 @@
"chatWindow.todoStatus.pending": "等待中",
"chatWindow.toolCallCount.one": "{count} 次工具呼叫",
"chatWindow.toolCallCount.other": "{count} 次工具呼叫",
+ "chatWindow.turnTokens": "輸入 {input} · 輸出 {output} · 快取 {cached}",
"chatWindow.versionNotFound": "找不到",
"chatWindow.waitingModel": "正在等待模型...",
"subagentTranscript.title": "子代理逐字記錄",
diff --git a/lib/turn-stats.test.mjs b/lib/turn-stats.test.mjs
new file mode 100644
index 000000000..60ae5234f
--- /dev/null
+++ b/lib/turn-stats.test.mjs
@@ -0,0 +1,122 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+const { summarizeTurnStats, formatTurnDuration } = await import("./turn-stats.ts");
+
+const zeroCost = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 };
+const assistant = (content, extra = {}) => ({ role: "assistant", provider: "p", model: "m", content, ...extra });
+const usage = (input, output, cacheRead, cacheWrite = 0) => ({ input, output, cacheRead, cacheWrite, cost: zeroCost });
+const text = (text) => ({ type: "text", text });
+const call = (id) => ({ type: "toolCall", toolCallId: id, toolName: "bash", input: { command: id } });
+
+test("sums usage across every assistant message in the turn", () => {
+ const messages = [
+ { role: "user", content: "go", timestamp: 1_000_000 },
+ assistant([call("a")], { timestamp: 1_005_000, usage: usage(12_000, 3_000, 8_000) }),
+ assistant([text("done")], { timestamp: 1_010_000, usage: usage(500, 200, 100, 50) }),
+ ];
+ const stats = summarizeTurnStats(messages, 0, 3);
+ assert.equal(stats.modelRequestCount, 2);
+ assert.equal(stats.inputTokens, 12_500);
+ assert.equal(stats.outputTokens, 3_200);
+ assert.equal(stats.cacheReadTokens, 8_100);
+ assert.equal(stats.cacheWriteTokens, 50);
+ assert.equal(stats.durationMs, 10_000);
+});
+
+test("ignores messages outside the turn range and messages without usage", () => {
+ const messages = [
+ assistant([text("earlier")], { timestamp: 900_000, usage: usage(999_000, 999_000, 999_000) }),
+ { role: "user", content: "go", timestamp: 1_000_000 },
+ assistant([call("a")], { timestamp: 1_005_000 }),
+ assistant([text("done")], { timestamp: 1_010_000, usage: usage(100, 50, 25) }),
+ assistant([text("later")], { timestamp: 2_000_000, usage: usage(777_000, 777_000, 777_000) }),
+ ];
+ const stats = summarizeTurnStats(messages, 1, 4);
+ assert.equal(stats.modelRequestCount, 1);
+ assert.equal(stats.inputTokens, 100);
+ assert.equal(stats.outputTokens, 50);
+ assert.equal(stats.cacheReadTokens, 25);
+ assert.equal(stats.durationMs, 10_000);
+});
+
+test("returns nulls, not zeros, when the turn reports no usage", () => {
+ const messages = [
+ { role: "user", content: "go", timestamp: 1_000_000 },
+ assistant([call("a")], { timestamp: 1_005_000 }),
+ assistant([text("done")], { timestamp: 1_010_000 }),
+ ];
+ const stats = summarizeTurnStats(messages, 0, 3);
+ assert.equal(stats.modelRequestCount, 0);
+ assert.equal(stats.inputTokens, null);
+ assert.equal(stats.outputTokens, null);
+ assert.equal(stats.cacheReadTokens, null);
+ assert.equal(stats.cacheWriteTokens, null);
+ assert.equal(stats.durationMs, 10_000);
+});
+
+test("an all-zero usage record does not count as reported usage", () => {
+ const messages = [
+ { role: "user", content: "go", timestamp: 1_000_000 },
+ assistant([text("done")], { timestamp: 1_010_000, usage: usage(0, 0, 0, 0) }),
+ ];
+ const stats = summarizeTurnStats(messages, 0, 2);
+ assert.equal(stats.modelRequestCount, 0);
+ assert.equal(stats.inputTokens, null);
+});
+
+test("duration runs to the last timestamped message in the turn", () => {
+ const messages = [
+ { role: "user", content: "go", timestamp: 1_000_000 },
+ assistant([call("a")], { timestamp: 1_005_000, usage: usage(10, 5, 0) }),
+ { role: "toolResult", toolCallId: "a", content: [{ type: "text", text: "ok" }], timestamp: 1_030_000 },
+ ];
+ const stats = summarizeTurnStats(messages, 0, 3);
+ assert.equal(stats.durationMs, 30_000);
+});
+
+test("duration is null without an anchor timestamp, or when the turn does not advance", () => {
+ const noAnchorTs = [
+ { role: "user", content: "go" },
+ assistant([text("done")], { timestamp: 1_010_000, usage: usage(10, 5, 0) }),
+ ];
+ assert.equal(summarizeTurnStats(noAnchorTs, 0, 2).durationMs, null);
+
+ const noEndTs = [
+ { role: "user", content: "go", timestamp: 1_000_000 },
+ assistant([text("done")], { usage: usage(10, 5, 0) }),
+ ];
+ assert.equal(summarizeTurnStats(noEndTs, 0, 2).durationMs, null);
+
+ const backwards = [
+ { role: "user", content: "go", timestamp: 1_010_000 },
+ assistant([text("done")], { timestamp: 1_000_000, usage: usage(10, 5, 0) }),
+ ];
+ assert.equal(summarizeTurnStats(backwards, 0, 2).durationMs, null);
+});
+
+test("an empty range returns nulls", () => {
+ const stats = summarizeTurnStats([{ role: "user", content: "go" }], 0, 0);
+ assert.deepEqual(stats, {
+ durationMs: null,
+ inputTokens: null,
+ outputTokens: null,
+ cacheReadTokens: null,
+ cacheWriteTokens: null,
+ modelRequestCount: 0,
+ });
+});
+
+test("formatTurnDuration keeps seconds precision below an hour", () => {
+ assert.equal(formatTurnDuration(null), null);
+ assert.equal(formatTurnDuration(undefined), null);
+ assert.equal(formatTurnDuration(0), null);
+ assert.equal(formatTurnDuration(999), null);
+ assert.equal(formatTurnDuration(1_000), "1s");
+ assert.equal(formatTurnDuration(45_000), "45s");
+ assert.equal(formatTurnDuration(72_000), "1m 12s");
+ assert.equal(formatTurnDuration(120_000), "2m");
+ assert.equal(formatTurnDuration(3_599_000), "59m 59s");
+ assert.equal(formatTurnDuration(3_600_000), "1h 0m");
+ assert.equal(formatTurnDuration(3_720_000), "1h 2m");
+});
diff --git a/lib/turn-stats.ts b/lib/turn-stats.ts
new file mode 100644
index 000000000..cd74a2a25
--- /dev/null
+++ b/lib/turn-stats.ts
@@ -0,0 +1,131 @@
+// Per-turn duration and token totals for one user turn, computed from the
+// transcript messages already in memory. Pure: no new data collection, no
+// settings, no API calls.
+//
+// A "turn" is the anchored range planTranscriptRows hands to
+// renderTranscriptGroupRow: the user message at startIndex and every message
+// up to (not including) endIndex.
+//
+// Duration is the elapsed time from the anchor message to the last timestamped
+// message in the turn, so it covers waiting, model requests and tool
+// execution — not just generation. It is null when either end lacks a
+// timestamp, which is the honest answer for imported or live-streaming turns
+// that do not carry timestamps yet.
+//
+// Token totals sum the provider-reported `usage` of every assistant message in
+// the turn, so a turn with several model requests (tool calls) counts all of
+// them, not only the final response. This follows the same accounting as
+// usage-service.ts: `input` and `cacheRead` are separate additive fields, so
+// cached input is not counted twice. That convention holds for the providers
+// omp-web records today; a provider whose `input` already includes cached
+// tokens would need provider-specific handling, which this module cannot
+// detect from the data — see the #392 follow-up, not this slice.
+//
+// A usage record only counts when it reports a positive token total, mirroring
+// usage-service.ts: a present-but-empty record must not turn into a
+// "0 in · 0 out · 0 cached" line. When no record counts, the token totals are
+// null (unavailable), never zero.
+import type { AgentMessage, AssistantMessage } from "./types";
+
+export interface TurnStats {
+ /** Elapsed ms from the anchor message to the last timestamped message in the turn, or null when unavailable. */
+ durationMs: number | null;
+ /** Uncached input tokens summed over the turn, or null when no usage was reported. */
+ inputTokens: number | null;
+ /** Output tokens summed over the turn, or null when no usage was reported. */
+ outputTokens: number | null;
+ /** Cache-read tokens summed over the turn, or null when no usage was reported. */
+ cacheReadTokens: number | null;
+ /** Cache-write tokens summed over the turn, or null when no usage was reported. */
+ cacheWriteTokens: number | null;
+ /** How many assistant messages in the turn reported usage. */
+ modelRequestCount: number;
+}
+
+function numericTimestamp(message: AgentMessage): number | undefined {
+ const ts = (message as { timestamp?: unknown }).timestamp;
+ return typeof ts === "number" && Number.isFinite(ts) ? ts : undefined;
+}
+
+function positiveNumber(value: unknown): number {
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0;
+}
+
+export function summarizeTurnStats(
+ messages: AgentMessage[],
+ startIndex: number,
+ endIndex: number,
+): TurnStats {
+ const start = Math.max(0, startIndex);
+ const end = Math.min(messages.length, Math.max(start, endIndex));
+ const empty: TurnStats = {
+ durationMs: null,
+ inputTokens: null,
+ outputTokens: null,
+ cacheReadTokens: null,
+ cacheWriteTokens: null,
+ modelRequestCount: 0,
+ };
+ if (end - start < 1) return empty;
+
+ const startTs = numericTimestamp(messages[start]);
+ let endTs: number | undefined;
+ for (let idx = start + 1; idx < end; idx += 1) {
+ const ts = numericTimestamp(messages[idx]);
+ if (ts !== undefined && (endTs === undefined || ts > endTs)) endTs = ts;
+ }
+ const durationMs =
+ startTs !== undefined && endTs !== undefined && endTs > startTs
+ ? endTs - startTs
+ : null;
+
+ let input = 0;
+ let output = 0;
+ let cacheRead = 0;
+ let cacheWrite = 0;
+ let modelRequestCount = 0;
+ for (let idx = start; idx < end; idx += 1) {
+ const msg = messages[idx];
+ if (msg.role !== "assistant") continue;
+ const usage = (msg as AssistantMessage).usage;
+ if (!usage || typeof usage !== "object") continue;
+ const total =
+ positiveNumber(usage.input) +
+ positiveNumber(usage.output) +
+ positiveNumber(usage.cacheRead) +
+ positiveNumber(usage.cacheWrite);
+ if (total <= 0) continue;
+ modelRequestCount += 1;
+ input += positiveNumber(usage.input);
+ output += positiveNumber(usage.output);
+ cacheRead += positiveNumber(usage.cacheRead);
+ cacheWrite += positiveNumber(usage.cacheWrite);
+ }
+
+ return {
+ durationMs,
+ inputTokens: modelRequestCount > 0 ? input : null,
+ outputTokens: modelRequestCount > 0 ? output : null,
+ cacheReadTokens: modelRequestCount > 0 ? cacheRead : null,
+ cacheWriteTokens: modelRequestCount > 0 ? cacheWrite : null,
+ modelRequestCount,
+ };
+}
+
+/**
+ * Short elapsed time for the Process details summary: "45s", "1m 12s",
+ * "2h 3m". Sub-second turns show nothing, matching formatDuration: a
+ * duration that short is noise in a summary line.
+ */
+export function formatTurnDuration(ms: number | null | undefined): string | null {
+ if (ms == null || !Number.isFinite(ms) || ms < 1_000) return null;
+ const totalSeconds = Math.floor(ms / 1000);
+ if (totalSeconds < 60) return `${totalSeconds}s`;
+ const minutes = Math.floor(totalSeconds / 60);
+ if (minutes < 60) {
+ const seconds = totalSeconds % 60;
+ return seconds > 0 ? `${minutes}m ${seconds}s` : `${minutes}m`;
+ }
+ const hours = Math.floor(minutes / 60);
+ return `${hours}h ${minutes % 60}m`;
+}