Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

Durations split into model-API time and tool wall time (#598)

Yaowei Zheng98a3b5127513
diff --git a/changelog/unreleased/2026-09-03-duration-breakdown.md b/changelog/unreleased/2026-09-03-duration-breakdown.md
new file mode 100644
index 00000000..36bf3427
--- /dev/null
+++ b/changelog/unreleased/2026-09-03-duration-breakdown.md
@@ -0,0 +1,33 @@
+# Durations split into model-API time and tool wall time
+
+- **Date:** 2026-09-03
+- **Type:** feature
+- **Scope:** `web`, `server`
+- **PR:** [#598](https://github.com/Prism-Shadow/penguin-harness/pull/598)
+
+[中文版](2026-09-03-duration-breakdown.zh.md)
+
+The chat header's details card and the Trace view now print each duration with its two components
+in parentheses — `Elapsed 10.3s (API 5s, tools 5.3s)` — so a slow turn says whether it was slow
+waiting on the model or running tools.
+
+## Details
+
+- **API time** is the time inside LLM requests with the human approval wait deducted. The wait
+ falls inside a request span because core awaits approval in the streaming loop, and it is not
+ time the model spent working.
+- **Tool wall time** is the union of the tool execution intervals, so tools running in parallel
+ count once instead of being summed. It excludes the approval wait, and excludes the segment
+ where the model streams a tool's arguments — that segment is API time.
+- The two are measurements of the same span, not a split of it: a background tool keeps running
+ while the model decodes, and approval waits and harness overhead belong to neither. They may
+ therefore exceed or fall short of the duration they follow, and neither is derived from it.
+- The Trace analysis response carries `apiMs` and `toolMs` file-wide and per turn, each global
+ figure being the sum of the per-turn figures exactly as `elapsedMs` already is. The Trace
+ view prints the breakdown inline in the file summary and in each turn's elapsed tooltip.
+- In the chat header the parentheses are omitted while both components are zero, so a
+ conversation that has not run shows the bare time. The components advance as each Request and
+ tool closes rather than ticking, so mid-turn they trail the running total.
+- A windowed history load seeds the breakdown alongside the total it belongs to: the message
+ window's prior stats gained the same two figures, and its cached per-shard scan records were
+ versioned up so stale ones recompute.
diff --git a/changelog/unreleased/2026-09-03-duration-breakdown.zh.md b/changelog/unreleased/2026-09-03-duration-breakdown.zh.md
new file mode 100644
index 00000000..3e6872a3
--- /dev/null
+++ b/changelog/unreleased/2026-09-03-duration-breakdown.zh.md
@@ -0,0 +1,19 @@
+# 用时拆出模型 API 时间与工具 wall time
+
+- **Date:** 2026-09-03
+- **Type:** feature
+- **Scope:** `web`, `server`
+- **PR:** [#598](https://github.com/Prism-Shadow/penguin-harness/pull/598)
+
+[English](2026-09-03-duration-breakdown.md)
+
+对话页详情卡与轨迹观测的每处用时,现在都在括号里带上两个分项——`用时 10.3s(API 5s,工具 5.3s)`——一轮慢在哪里,是等模型还是跑工具,一眼可读。
+
+## 细节
+
+- **API 时间**是 LLM 请求内的时间,已扣除人工审批等待。审批等待落在请求区间之内(core 在流式循环里等待审批),那不是模型在工作的时间。
+- **工具 wall time** 是各工具执行区间的并集,并行工具只计一次而不是相加。它不含审批等待,也不含模型吐工具参数的那一段——那段属于 API 时间。
+- 二者是对同一段用时的两项实测,不是对它的切分:后台工具会在模型解码时继续运行,而审批等待与 harness 开销不属于任何一项。故其和可能大于也可能小于所跟随的用时,任一项都不由用时减去另一项得出。
+- 轨迹分析响应新增 `apiMs` 与 `toolMs`,全局与逐轮各一份,全局值同 `elapsedMs` 一样是各轮之和。轨迹观测在文件摘要处内联展示分项,逐轮则放在用时的悬停提示里。
+- 对话页在两个分项皆为零时不显示括号,未跑过的对话只显示裸的用时。分项随每个 Request 与工具收尾而推进、不逐秒跳动,因此一轮进行中会略落后于总用时。
+- 分窗加载历史时,分项与它所属的总用时一同回填:消息窗口的 prior 统计同样新增了这两个值,其按分片缓存的扫描记录也随之升版,旧记录会重算。
diff --git a/packages/docs/content/web-app.en.md b/packages/docs/content/web-app.en.md
index 2e66077e..b2714417 100644
--- a/packages/docs/content/web-app.en.md
+++ b/packages/docs/content/web-app.en.md
@@ -61,7 +61,7 @@ Pinning is offered only in the active list — the archived, subagent and schedu
### Header Stats and the Details Card
-The toolbar's right edge shows the Session's cumulative stats (tokens, cost, elapsed time); clicking them opens the details card — model, Session id (with a copy button beside it), Workspace, creation time and per-line statistics. Right of the elapsed time, while the conversation still owns background tasks, a small pill shows their count — the same figure the conversation list's mark carries. Below those:
+The toolbar's right edge shows the Session's cumulative stats (tokens, cost, elapsed time); clicking them opens the details card — model, Session id (with a copy button beside it), Workspace, creation time and per-line statistics. The elapsed line carries its two components in parentheses, `Elapsed 10.3s (API 5s, tools 5.3s)`: time inside model requests with the human approval wait deducted, and tool wall time as the union of the tool executions, so tools running in parallel count once. They are two measurements of that span rather than a split of it — a background tool overlaps the model's decoding, while approval waits and harness overhead belong to neither — so they may exceed or fall short of the total, and neither is derived from it. Below those: Right of the elapsed time, while the conversation still owns background tasks, a small pill shows their count — the same figure the conversation list's mark carries. Below those:
- **Processes** — background processes the conversation started (`exec_command`s promoted past their yield window), one row each with the command, start time and pid — plus, on running rows, a link to the service the process serves when one was detected (the last local URL its output printed, else a listen-port probe of its process group). Running rows carry a **Stop** button (kills the whole process group and drops the row) — the conversation is told the process is down, as **stopped** rather than failed, so the model knows the dev server is gone without reading it as a crash to restart; exited rows keep their "exited" label and carry a **Remove** button that deletes the entry from the list. Removal is immediate and final: the entry leaves the runtime registry together with the output captured from that process, so afterwards the model can no longer be asked to read it — keep the row until you are done with its output.
diff --git a/packages/docs/content/web-app.zh.md b/packages/docs/content/web-app.zh.md
index 950c6532..e7b5c919 100644
--- a/packages/docs/content/web-app.zh.md
+++ b/packages/docs/content/web-app.zh.md
@@ -61,7 +61,7 @@ penguin web
### 头部统计与详情卡
-工具行最右侧显示会话累计统计(Token、费用、用时),点击即打开详情卡——模型、Session id(旁附复制按钮)、Workspace、创建时间与逐行统计。会话仍有后台任务时,用时右侧有一枚小胶囊显示其数量——与会话列表行上那枚标记同一个数。其下还有一节:
+工具行最右侧显示会话累计统计(Token、费用、用时),点击即打开详情卡——模型、Session id(旁附复制按钮)、Workspace、创建时间与逐行统计。用时一行在括号里带两个分项,形如 `用时 10.3s(API 5s,工具 5.3s)`:一项是模型请求内的时间(已扣除人工审批等待),另一项是工具的 wall time(各工具执行区间的并集,并行工具只计一次)。二者是对这段用时的两项实测,不是对它的切分——后台工具会与模型解码重叠,审批等待与 harness 开销又不属于任何一项——故其和可能大于也可能小于总用时,任一项都不由总用时减去另一项得出。其下还有一节:会话仍有后台任务时,用时右侧有一枚小胶囊显示其数量——与会话列表行上那枚标记同一个数。其下还有一节:
- **会话进程**——对话启动的后台进程(超过 yield 窗口转入后台的 `exec_command`),逐行显示命令、启动时间与 pid;运行中的行在检测到进程所服务的地址时,还会附上可点击的服务链接(取其输出打印的最后一个本机 URL,否则对其进程组做监听端口探测)。运行中的行带「停止」按钮(杀停整个进程组并把该行从列表移除)——对话会收到该进程已结束的回报,措辞是「已停止」而非失败,模型因此知道 dev server 没了,却不会把它读成需要重启的崩溃;已退出的行保留「已退出」标注,并带「移除」按钮,可把该条目从列表删除。移除立即生效且不可撤销:条目连同该进程已捕获的输出一起离开运行时注册表,之后无法再让模型读取那段输出——输出还有用时请先留着这一行。
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index d24ca830..c201adde 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -1427,6 +1427,14 @@ export interface MessagesPageInfo {
prior: {
subagentTokens: number;
elapsedMs: number;
+ /**
+ * Model-API time and tool wall time accrued before this window, the breakdown of
+ * `elapsedMs` the chat header shows under it. Seeded together with their total: seeding
+ * one alone would put a full elapsed time beside components covering only the window.
+ * The two may overlap and do not partition `elapsedMs` (see `TraceTaskStats.toolMs`).
+ */
+ apiMs: number;
+ toolMs: number;
sessionTokens: number;
contextTokens: number;
};
@@ -2492,6 +2500,21 @@ export interface TraceTaskStats {
* output — there's no second figure to reconcile.
*/
llmMs: number;
+ /**
+ * Wall-clock time this turn spent executing tools: the **union** of its tool spans'
+ * execution intervals (`approvalTs ?? callTs` to `outputTs`), so tools running in parallel
+ * are counted once instead of summed. Two exclusions, both deliberate: the human approval
+ * wait (`callTs` to `approvalTs`) is not tool work, and the argument-generation segment is
+ * the model streaming arguments, already counted in `llmMs`. A span with no `outputTs` —
+ * still running when the file ended, or interrupted — contributes nothing rather than being
+ * extrapolated to now.
+ *
+ * This and `llmMs` may **overlap**: a tool started in the background keeps running while the
+ * model decodes. They are two measured components of the turn's duration, not a partition of
+ * it, and they need not add up to the turn's span (approval waits and harness overhead belong
+ * to neither). Never derive one by subtracting the other from the duration.
+ */
+ toolMs: number;
}
/** Duration span of a single tool call (complete tool_call message → paired tool_call_output). */
@@ -2595,6 +2618,18 @@ export interface TraceAnalysisResponse {
* frontend's events are paginated, so self-aggregation would undercount.
*/
elapsedMs: number;
+ /**
+ * The file's model-API time: the sum of the turns' `llmMs` (human approval wait deducted,
+ * compaction requests included, so the scope matches `elapsedMs`).
+ */
+ apiMs: number;
+ /**
+ * The file's tool wall time: the sum of the turns' `toolMs` (parallel tools counted once
+ * within a turn). Summed per turn rather than unioned across the file, so the global figure
+ * stays the sum of the per-turn figures, exactly as `elapsedMs` is. May overlap `apiMs` —
+ * see `TraceTaskStats.toolMs`.
+ */
+ toolMs: number;
requests: RequestSpan[];
/** Token / duration aggregated per Task (used directly by the Trace page's context ring and per-turn TPS). */
tasks: TraceTaskStats[];
diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.ts
index 2219c44d..1dd4a62d 100644
--- a/packages/server/src/http/routes/sessions.ts
+++ b/packages/server/src/http/routes/sessions.ts
@@ -822,6 +822,8 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {
prior: {
subagentTokens: result.prior.subagentTokens,
elapsedMs: result.prior.elapsedMs,
+ apiMs: result.prior.apiMs,
+ toolMs: result.prior.toolMs,
sessionTokens: result.prior.sessionTokens,
contextTokens: result.prior.contextTokens,
},
diff --git a/packages/server/src/services/message-window.ts b/packages/server/src/services/message-window.ts
index 2549ec5a..634ff136 100644
--- a/packages/server/src/services/message-window.ts
+++ b/packages/server/src/services/message-window.ts
@@ -45,7 +45,7 @@ import {
import type { OmniMessage } from "@prismshadow/penguin-core";
/** Bump when any counting/boundary rule changes: cached page_stats records with an older version are recomputed. */
-export const CACHE_VERSION = 3;
+export const CACHE_VERSION = 4;
/** Cumulative totals at a point in the trace (all values are "before this point"). */
export interface WindowPriorStats {
@@ -55,6 +55,18 @@ export interface WindowPriorStats {
subagentTokens: number;
/** Sum of finished Tasks' elapsed time before this point (the Web's sessionElapsedMs basis). */
elapsedMs: number;
+ /**
+ * Sum of finished Tasks' model-API time before this point (the Web's sessionLlmMs basis):
+ * paired request spans with the human approval wait deducted, compaction requests excluded —
+ * the same scope `elapsedMs` uses, so the component and its total cover the same turns.
+ */
+ apiMs: number;
+ /**
+ * Sum of finished Tasks' tool wall time before this point (the Web's sessionToolMs basis):
+ * per Task the union of its tool execution intervals, so parallel tools count once. Overlaps
+ * `apiMs` when a tool runs on while the model decodes; the two never partition `elapsedMs`.
+ */
+ toolMs: number;
/** The last main-session token_usage `session.total` seen before this point (0 = none). */
sessionTokens: number;
/** The last main-session NON-compaction token_usage `request.total` before this point (context occupancy basis). */
@@ -82,6 +94,43 @@ interface TaskCarry {
* written by a pre-stamp core (see the user-text branch).
*/
turnToolOutputs: boolean;
+ /** Open Request's begin timestamp (ms), null between Requests (mirrors StreamModel.openRequestBeginMs). */
+ reqBeginMs: number | null;
+ /** Approval wait accumulated inside the open Request (ms), deducted at its end (mirrors StreamModel.openApprovalWaitMs). */
+ reqApprovalWaitMs: number;
+ /** This Task's model-API time so far (ms; mirrors task-stats taskLlmMs). */
+ apiMs: number;
+ /**
+ * Tool executions still open, keyed by tool_call_id, holding each one's execution start (ms):
+ * the tool_call's own timestamp, moved forward to the approval moment once one arrives. A
+ * plain object rather than a Map because a shard is cached mid-Task and this state is JSON.
+ */
+ openTools: Record<string, number>;
+ /** This Task's settled tool execution intervals (ms), unioned when it closes (mirrors task-stats taskToolIntervals). */
+ toolIntervals: Array<[number, number]>;
+}
+
+/**
+ * Total length of the **union** of the given intervals (ms): overlapping and nested runs count
+ * once, so parallel tool calls yield wall time rather than a sum of durations. Shared with
+ * trace-service, which decomposes finished Trace files the same way.
+ */
+export function mergedIntervalMs(intervals: ReadonlyArray<readonly [number, number]>): number {
+ if (intervals.length === 0) return 0;
+ const sorted = [...intervals].sort((a, b) => a[0] - b[0]);
+ let total = 0;
+ let [openStart, openEnd] = sorted[0]!;
+ for (let i = 1; i < sorted.length; i++) {
+ const [start, end] = sorted[i]!;
+ if (start > openEnd) {
+ total += openEnd - openStart;
+ openStart = start;
+ openEnd = end;
+ } else if (end > openEnd) {
+ openEnd = end;
+ }
+ }
+ return total + (openEnd - openStart);
}
/** Full scanner state, serializable into a shard's cached prefix record. */
@@ -104,7 +153,15 @@ export interface ScanState {
export function initialScanState(): ScanState {
return {
- totals: { turns: 0, subagentTokens: 0, elapsedMs: 0, sessionTokens: 0, contextTokens: 0 },
+ totals: {
+ turns: 0,
+ subagentTokens: 0,
+ elapsedMs: 0,
+ apiMs: 0,
+ toolMs: 0,
+ sessionTokens: 0,
+ contextTokens: 0,
+ },
task: {
open: false,
firstTsMs: 0,
@@ -114,6 +171,11 @@ export function initialScanState(): ScanState {
sawReply: false,
pendingCompactionUsage: false,
turnToolOutputs: false,
+ reqBeginMs: null,
+ reqApprovalWaitMs: 0,
+ apiMs: 0,
+ openTools: {},
+ toolIntervals: [],
},
compactionActive: false,
steeringOpen: false,
@@ -156,6 +218,10 @@ function finalizeTask(state: ScanState): void {
t.open = false;
const endMs = t.lastReqEndMs ?? t.lastTsMs;
state.totals.elapsedMs += Math.max(0, endMs - t.firstTsMs);
+ // The elapsed breakdown folds on the same boundary as the total (mirrors task-stats endTask).
+ // Tools still open at the close never finished within this trace and contribute nothing.
+ state.totals.apiMs += t.apiMs;
+ state.totals.toolMs += mergedIntervalMs(t.toolIntervals);
t.pendingCompactionUsage = false;
}
@@ -171,6 +237,11 @@ function startTask(state: ScanState, ms: number | null): void {
t.sawReply = false;
t.pendingCompactionUsage = false;
t.turnToolOutputs = false;
+ t.reqBeginMs = null;
+ t.reqApprovalWaitMs = 0;
+ t.apiMs = 0;
+ t.openTools = {};
+ t.toolIntervals = [];
}
/** A non-user item entered the stream: the user-item run breaks (buildOutline's lastWasUser = false). */
@@ -318,6 +389,11 @@ export async function scanMessages(
}
if (p.type === "tool_call") {
touchTask(state, ms);
+ // Execution starts here unless an approval follows and moves it (mirrors
+ // stream-model's settleToolDuration, which prefers approvalAtMs over callStartedAtMs).
+ if (ms !== null && typeof p.tool_call_id === "string" && p.tool_call_id !== "") {
+ state.task.openTools[p.tool_call_id] = ms;
+ }
breakRuns(state);
continue;
}
@@ -325,6 +401,13 @@ export async function scanMessages(
// Updates an existing card (no new item); the turn now owes the model its results
// — the window a positionally-recognized notice keys on (see turnToolOutputs).
touchTask(state, ms);
+ if (ms !== null && typeof p.tool_call_id === "string") {
+ const startMs = state.task.openTools[p.tool_call_id];
+ if (startMs !== undefined) {
+ delete state.task.openTools[p.tool_call_id];
+ if (ms > startMs) state.task.toolIntervals.push([startMs, ms]);
+ }
+ }
state.task.turnToolOutputs = true;
continue;
}
@@ -354,6 +437,17 @@ export async function scanMessages(
continue;
}
if (t === "request_end") {
+ // Pair with request_begin for this Task's API time, deducting the approval wait that
+ // falls inside the span (core awaits approval inside the streaming loop). Settled
+ // before the compaction guard below so a compaction Request still clears the pairing;
+ // its time is excluded here exactly as it is from the Chat page's elapsed.
+ const reqBeginMs = state.task.reqBeginMs;
+ const reqWaitMs = state.task.reqApprovalWaitMs;
+ state.task.reqBeginMs = null;
+ state.task.reqApprovalWaitMs = 0;
+ if (!state.compactionActive && reqBeginMs !== null && ms !== null) {
+ state.task.apiMs += Math.max(0, ms - reqBeginMs - reqWaitMs);
+ }
if (state.compactionActive) continue; // compaction requests render nothing
if (ms !== null) state.task.lastReqEndMs = ms;
// Pending compaction usage commits at a later non-compaction request_end
@@ -405,9 +499,24 @@ export async function scanMessages(
// outputs have been sent with it (mirrors stream-model's request_begin reset;
// compaction requests don't consume the pending turn state).
if (!state.compactionActive) state.task.turnToolOutputs = false;
+ if (ms !== null) state.task.reqBeginMs = ms;
+ continue;
+ }
+ if (t === "approval_decision") {
+ // The human wait ran inside the open Request (core awaits approval in the streaming
+ // loop), so it is deducted from API time; execution only begins now, so the tool's
+ // interval start moves here (mirrors stream-model noteApprovalWait + settleToolDuration).
+ const id = (p as { tool_call_id?: unknown }).tool_call_id;
+ if (ms !== null && typeof id === "string") {
+ const calledMs = state.task.openTools[id];
+ if (calledMs !== undefined) {
+ if (ms > calledMs) state.task.reqApprovalWaitMs += ms - calledMs;
+ state.task.openTools[id] = ms;
+ }
+ }
continue;
}
- // approval_decision / unexpanded pointers: no items, no run change.
+ // Unexpanded pointers: no items, no run change.
continue;
}
// session_meta: no item (steering window already closed above).
diff --git a/packages/server/src/services/trace-service.ts b/packages/server/src/services/trace-service.ts
index 7b2e87e7..685ab131 100644
--- a/packages/server/src/services/trace-service.ts
+++ b/packages/server/src/services/trace-service.ts
@@ -61,6 +61,7 @@ import {
encodeCursor,
finalizeScan,
initialScanState,
+ mergedIntervalMs,
scanMessages,
serializePrefix,
} from "./message-window.js";
@@ -206,6 +207,24 @@ function subagentPointer(msg: OmniMessage): string | null {
return p.session_id;
}
+/**
+ * The interval a tool span actually spent **executing**, as epoch milliseconds, or null when
+ * it never produced one.
+ *
+ * Starts at the approval moment when there was one and at the call otherwise, so the human
+ * approval wait stays out; the argument-generation segment is before `callTs` entirely and is
+ * model time, counted in the turn's `llmMs`. A span with no `outputTs` never finished within
+ * this file — still running when it ended, or interrupted — and contributes nothing rather
+ * than being extrapolated to the present.
+ */
+export function toolExecutionInterval(span: TraceToolSpan): [number, number] | null {
+ if (span.outputTs === undefined) return null;
+ const end = Date.parse(span.outputTs);
+ const start = Date.parse(span.approvalTs ?? span.callTs);
+ if (!Number.isFinite(start) || !Number.isFinite(end)) return null;
+ return [start, Math.max(start, end)];
+}
+
/**
* Read-only slice of the Session index the paginated listing consults (SessionsRepo
* structurally satisfies it; injected so service tests need no full app): one indexed
@@ -896,6 +915,7 @@ export class TraceService {
endTs: "",
tokens: { cacheRead: 0, cacheWrite: 0, output: 0 },
llmMs: 0,
+ toolMs: 0,
};
taskStats.set(ti, t);
}
@@ -1325,8 +1345,26 @@ export class TraceService {
const span = Date.parse(t.endTs) - Date.parse(t.startTs);
return sum + (Number.isFinite(span) ? Math.max(0, span) : 0);
}, 0);
+ // Tool wall time per turn: the union of that turn's execution intervals, so tools running
+ // in parallel are counted once. `llmMs` is already accumulated per turn as each Request
+ // ends, so the two components need no second pass here.
+ const toolIntervalsByTask = new Map<number, Array<[number, number]>>();
+ for (const span of toolSpans) {
+ const interval = toolExecutionInterval(span);
+ if (interval === null) continue;
+ const list = toolIntervalsByTask.get(span.taskIndex);
+ if (list === undefined) toolIntervalsByTask.set(span.taskIndex, [interval]);
+ else list.push(interval);
+ }
+ for (const t of tasks) t.toolMs = mergedIntervalMs(toolIntervalsByTask.get(t.taskIndex) ?? []);
+ // Both global figures are the sum of the per-turn figures, the same convention `elapsedMs`
+ // follows above, so a reader adding up the turn cards lands on the totals.
+ const apiMs = tasks.reduce((sum, t) => sum + t.llmMs, 0);
+ const toolMs = tasks.reduce((sum, t) => sum + t.toolMs, 0);
return {
elapsedMs,
+ apiMs,
+ toolMs,
requests,
tasks,
toolCalls,
diff --git a/packages/server/test/messages-page.test.ts b/packages/server/test/messages-page.test.ts
index 65c4805c..dba8d3d0 100644
--- a/packages/server/test/messages-page.test.ts
+++ b/packages/server/test/messages-page.test.ts
@@ -22,6 +22,7 @@ import {
imageUrlMessage,
requestBegin,
requestEnd,
+ approvalDecision,
sessionMeta,
subagentEvent,
tokenUsage,
@@ -141,6 +142,8 @@ describe("messages windowed reads", () => {
turns: 0,
subagentTokens: 0,
elapsedMs: 0,
+ apiMs: 0,
+ toolMs: 0,
sessionTokens: 0,
contextTokens: 0,
});
@@ -574,10 +577,50 @@ describe("messages windowed reads", () => {
expect(harness.shardReads.some((p) => p.includes(`${S}_001.jsonl`))).toBe(true);
});
+ it("prior stats carry the elapsed breakdown, unioning parallel tools like trace-service does", async () => {
+ // The window scanner mirrors stream-model so a windowed reload lands on the same header
+ // figures as a full load. The breakdown has to be mirrored too: seeding a full elapsed time
+ // beside components covering only the loaded window would under-report against their total.
+ await writeTraceFile(root, P, A, "2026-07-20", S, 1, [
+ sessionMeta(metaPayload()),
+ at("2026-07-20T10:00:00.000Z", userText("q1")),
+ at("2026-07-20T10:00:01.000Z", requestBegin()),
+ at("2026-07-20T10:00:02.000Z", toolCall({ name: "exec", arguments: "{}", toolCallId: "t1" })),
+ at("2026-07-20T10:00:02.000Z", toolCall({ name: "read", arguments: "{}", toolCallId: "t2" })),
+ at("2026-07-20T10:00:03.000Z", approvalDecision("allow", "t1")),
+ at("2026-07-20T10:00:04.000Z", approvalDecision("allow", "t2")),
+ at("2026-07-20T10:00:05.000Z", requestEnd("completed")),
+ at("2026-07-20T10:00:09.000Z", toolCallOutput({ output: "a", toolCallId: "t1" })),
+ at("2026-07-20T10:00:11.000Z", toolCallOutput({ output: "b", toolCallId: "t2" })),
+ at("2026-07-20T10:00:11.000Z", requestBegin()),
+ at("2026-07-20T10:00:13.000Z", assistantText("a1")),
+ at("2026-07-20T10:00:13.000Z", requestEnd("completed")),
+ at("2026-07-20T10:00:13.500Z", tokenUsage(counts(1000), counts(100))),
+ ...turn(1, 2, 2000),
+ ]);
+
+ // A tail window holding only the SECOND turn: the first turn's figures ride prior.
+ const tail = await service.readMessagesPage(P, A, S, { kind: "tail", limit: 1 });
+ expect(userTexts(tail.messages)).toEqual(["q2"]);
+ // API: 01→05 less the two approval waits (1s + 2s), plus 11→13.
+ expect(tail.prior.apiMs).toBe(1_000 + 2_000);
+ // Tools: the union of [03,09] and [04,11] — 8s of wall time, not 6s + 7s summed.
+ expect(tail.prior.toolMs).toBe(8_000);
+ expect(tail.prior.elapsedMs).toBe(13_000);
+ });
+
it("cursor edge cases: unknown shard yields an empty end-of-history page; empty sessions page cleanly", async () => {
expect(await service.readMessagesPage(P, A, S, { kind: "tail", limit: 5 })).toEqual({
messages: [],
- prior: { turns: 0, subagentTokens: 0, elapsedMs: 0, sessionTokens: 0, contextTokens: 0 },
+ prior: {
+ turns: 0,
+ subagentTokens: 0,
+ elapsedMs: 0,
+ apiMs: 0,
+ toolMs: 0,
+ sessionTokens: 0,
+ contextTokens: 0,
+ },
});
await writeTraceFile(root, P, A, "2026-07-20", S, 1, [
sessionMeta(metaPayload()),
diff --git a/packages/server/test/trace-service.test.ts b/packages/server/test/trace-service.test.ts
index 1d616ae6..bd1b8834 100644
--- a/packages/server/test/trace-service.test.ts
+++ b/packages/server/test/trace-service.test.ts
@@ -267,6 +267,69 @@ describe("trace-service", () => {
expect(a.tasks[0]!.tokens.output).toBe(1_000); // → 500 tok/s, not 31 tok/s
});
+ it("splits a turn's duration into API time and tool wall time, counting parallel tools once", async () => {
+ // Two tools run concurrently: 10:00:03→10:00:09 and 10:00:04→10:00:11. Summing their
+ // durations would claim 13s of tool work; the clock only ever spent 8s (03→11), which is
+ // what "wall time" has to mean once tools can overlap.
+ await writeTraceFile(root, P, A, "2026-07-05", S, 1, [
+ sessionMeta(metaPayload()),
+ at("2026-07-05T10:00:00.000Z", userText("hi")),
+ at("2026-07-05T10:00:01.000Z", requestBegin()),
+ at(
+ "2026-07-05T10:00:02.000Z",
+ toolCall({ name: "exec_command", arguments: "{}", toolCallId: "tc-1" }),
+ ),
+ at(
+ "2026-07-05T10:00:02.000Z",
+ toolCall({ name: "read_file", arguments: "{}", toolCallId: "tc-2" }),
+ ),
+ // Approvals land inside the Request span (core awaits them in the streaming loop), so the
+ // waits come off API time; execution then starts at each approval, not at the call.
+ at("2026-07-05T10:00:03.000Z", approvalDecision("allow", "tc-1")),
+ at("2026-07-05T10:00:04.000Z", approvalDecision("allow", "tc-2")),
+ at("2026-07-05T10:00:05.000Z", requestEnd("completed")),
+ at("2026-07-05T10:00:09.000Z", toolCallOutput({ output: "a", toolCallId: "tc-1" })),
+ at("2026-07-05T10:00:11.000Z", toolCallOutput({ output: "b", toolCallId: "tc-2" })),
+ at("2026-07-05T10:00:11.000Z", requestBegin()),
+ at("2026-07-05T10:00:13.000Z", requestEnd("completed")),
+ at("2026-07-05T10:00:13.100Z", tokenUsage(counts(1000), buckets(0, 0, 1_000))),
+ ]);
+ const a = await service.analyze(P, A, S, 1);
+ const t = a.tasks[0]!;
+
+ // API: 01→05 minus the two approval waits (1s + 2s), plus 11→13.
+ expect(t.llmMs).toBe(1_000 + 2_000);
+ // Tools: the union of [03,09] and [04,11] — 8s, not the 6s + 7s the two spans add up to.
+ expect(t.toolMs).toBe(8_000);
+ // The components are measurements, not a partition: here they overlap nothing, but they
+ // still fall short of the turn's span, which also covers the gap the harness spent.
+ expect(t.llmMs + t.toolMs).toBeLessThanOrEqual(a.elapsedMs);
+ // The file-wide figures are the sum of the per-turn ones, exactly as elapsedMs is.
+ expect(a.apiMs).toBe(a.tasks.reduce((sum, x) => sum + x.llmMs, 0));
+ expect(a.toolMs).toBe(a.tasks.reduce((sum, x) => sum + x.toolMs, 0));
+ });
+
+ it("a tool still running when the trace ends contributes no tool time", async () => {
+ // No tool_call_output ever arrives: the execution has no measured end, and extrapolating it
+ // to "now" would grow a finished file's figures every time it is read.
+ await writeTraceFile(root, P, A, "2026-07-05", S, 1, [
+ sessionMeta(metaPayload()),
+ at("2026-07-05T10:00:00.000Z", userText("hi")),
+ at("2026-07-05T10:00:01.000Z", requestBegin()),
+ at(
+ "2026-07-05T10:00:02.000Z",
+ toolCall({ name: "exec_command", arguments: "{}", toolCallId: "tc-1" }),
+ ),
+ at("2026-07-05T10:00:03.000Z", requestEnd("completed")),
+ at("2026-07-05T10:00:03.100Z", tokenUsage(counts(1000), buckets(0, 0, 1_000))),
+ ]);
+ const a = await service.analyze(P, A, S, 1);
+
+ expect(a.tasks[0]!.toolMs).toBe(0);
+ expect(a.toolMs).toBe(0);
+ expect(a.tasks[0]!.llmMs).toBe(2_000);
+ });
+
it("compaction is its own turn: its TPS is its own and doesn't pollute user turns; the context snapshot still takes only non-compaction Requests", async () => {
// Compaction's request_begin/end and token_usage all sit between
// compaction_begin and compaction_end (see core's context-engine summarize
diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsx
index 7f5a747f..9d3fc321 100644
--- a/packages/web/src/features/chat/chat-page.tsx
+++ b/packages/web/src/features/chat/chat-page.tsx
@@ -52,7 +52,11 @@ import {
import type { StreamModel } from "../../lib/omni/stream-model";
import { aggregateMemoryChanges, sameMemoryChanges } from "../../lib/omni/memory-changes";
import type { MemoryLocateTarget } from "../../lib/omni/memory-changes";
-import { bucketCostUsd, liveSessionElapsedMs } from "../../lib/omni/task-stats";
+import {
+ bucketCostUsd,
+ liveSessionElapsedMs,
+ sessionElapsedBreakdown,
+} from "../../lib/omni/task-stats";
import type { TaskStatsTracker } from "../../lib/omni/task-stats";
import { useAuth } from "../../state/auth";
import { useTheme } from "../../state/theme";
@@ -206,6 +210,12 @@ interface HeaderStats {
/** Server-reported "some usage had no pricing" flag riding the shown figure (the chip's `*`). */
costUncosted: boolean;
elapsedNode: ReactNode;
+ /**
+ * The elapsed time's API / tool breakdown, already parenthesised, or null when neither
+ * component has anything to report yet (a conversation that has not run shows the bare
+ * time rather than a row of zeroes).
+ */
+ elapsedSplit: string | null;
}
/**
@@ -231,9 +241,27 @@ function headerStats(model: StreamModel, cost: CostStatDisplay): HeaderStats {
taskStartLocalMs={model.taskStartLocalMs}
/>
),
+ elapsedSplit: elapsedSplitText(stats),
};
}
+/**
+ * The parenthesised API / tool breakdown of the elapsed time, or null when both components are
+ * still zero. A component that is genuinely zero beside a non-zero one still prints: "no tool
+ * time" is worth reading. Unlike the total beside it this does not tick — it advances as each
+ * Request and tool closes, so mid-turn it trails the running total, and the two components can
+ * also overlap each other. Both are why it is rendered as two measurements, not as a split of
+ * the total (see sessionElapsedBreakdown).
+ */
+function elapsedSplitText(stats: TaskStatsTracker): string | null {
+ const { apiMs, toolMs } = sessionElapsedBreakdown(stats);
+ if (apiMs <= 0 && toolMs <= 0) return null;
+ return `${S.chat.statParenOpen}${S.chat.statElapsedSplit(
+ humanizeDuration(apiMs),
+ humanizeDuration(toolMs),
+ )}${S.chat.statParenClose}`;
+}
+
/**
* Route id for a draft chat (`/chat/new`): the Session hasn't been persisted yet — the user may
* still want to change the model or configure a key first. The actual Session is only created
@@ -1751,7 +1779,7 @@ export function ChatPage() {
<StatChip
icon={STAT_ICONS.elapsed}
value={hs.elapsedNode}
- label={S.chat.statElapsed}
+ label={`${S.chat.statElapsed}${hs.elapsedSplit ?? ""}`}
/>
{/* Right of the time, only while the conversation still owns background
work — command processes past their yield window, background subagents
@@ -1842,6 +1870,7 @@ export function ChatPage() {
)}
<li>
{S.chat.statElapsed} {hs.elapsedNode}
+ {hs.elapsedSplit}
</li>
</ul>
</div>
diff --git a/packages/web/src/features/traces/trace-file-view.tsx b/packages/web/src/features/traces/trace-file-view.tsx
index 0a697891..3a0ade63 100644
--- a/packages/web/src/features/traces/trace-file-view.tsx
+++ b/packages/web/src/features/traces/trace-file-view.tsx
@@ -169,6 +169,21 @@ function InputChip({ buckets }: { buckets: Buckets }) {
);
}
+/**
+ * The parenthesised API / tool breakdown printed after a duration, or the empty string when
+ * neither component has anything. The two are measurements of the same span, not a partition
+ * of it: a tool running in the background overlaps the model's decoding, while approval waits
+ * and harness overhead belong to neither — so they may exceed or fall short of the duration
+ * they follow, and neither is ever derived from the other.
+ */
+function durationSplit(apiMs: number, toolMs: number): string {
+ if (apiMs <= 0 && toolMs <= 0) return "";
+ return `${S.chat.statParenOpen}${S.chat.statElapsedSplit(
+ humanizeDuration(apiMs),
+ humanizeDuration(toolMs),
+ )}${S.chat.statParenClose}`;
+}
+
export function TraceFileView({
projectId,
agentId,
@@ -497,7 +512,10 @@ export function TraceFileView({
/>
<SummaryRow
label={S.chat.statElapsed}
- value={humanizeDuration(Math.max(0, globalMs))}
+ value={`${humanizeDuration(Math.max(0, globalMs))}${durationSplit(
+ analysis.apiMs,
+ analysis.toolMs,
+ )}`}
/>
{/* Global TPS = the output of every round (including compaction
rounds) ÷ the sum of LLM generation time, same scope as the
@@ -572,7 +590,7 @@ export function TraceFileView({
<StatChip
icon={STAT_ICONS.elapsed}
value={humanizeDuration(t.durationMs)}
- label={S.chat.statElapsed}
+ label={`${S.chat.statElapsed}${durationSplit(st?.llmMs ?? 0, st?.toolMs ?? 0)}`}
/>
<StatChip
icon={STAT_ICONS.tps}
diff --git a/packages/web/src/lib/omni/stream-model.ts b/packages/web/src/lib/omni/stream-model.ts
index 1e63be81..6ce43f96 100644
--- a/packages/web/src/lib/omni/stream-model.ts
+++ b/packages/web/src/lib/omni/stream-model.ts
@@ -70,6 +70,7 @@ import type {
import type { TracePosition } from "@prismshadow/penguin-server/api";
import {
addLlmDuration,
+ addToolExecution,
beginCompaction,
commitPendingCompaction,
createTaskStatsTracker,
@@ -1105,7 +1106,7 @@ function handlePartial(model: StreamModel, p: PartialModelPayload, tsMs?: number
if (p.event_type === "stop") {
card.outputStreaming = false;
if (p.stop_reason !== undefined) card.outputStopReason = p.stop_reason;
- settleToolDuration(card, tsMs);
+ settleToolDuration(card, tsMs, model.stats);
}
return;
}
@@ -1371,7 +1372,7 @@ function handleComplete(
card.outputStreaming = false;
card.outputComplete = true;
if (p.stop_reason !== undefined) card.outputStopReason = p.stop_reason;
- settleToolDuration(card, tsOf(timestamp));
+ settleToolDuration(card, tsOf(timestamp), model.stats);
// This turn owes the model its results, so a compaction triggering now is mid-Task
// and the round is not over (see turnToolOutputs).
model.turnToolOutputs = true;
@@ -1437,7 +1438,11 @@ function settleThinkingDuration(item: ThinkingItem, endMs: number | undefined):
* the already-settled generation segment.
* Degrades to a pure execution segment when the start point is missing, still never negative.
*/
-function settleToolDuration(card: ToolCallItem, endMs: number | undefined): void {
+function settleToolDuration(
+ card: ToolCallItem,
+ endMs: number | undefined,
+ stats?: TaskStatsTracker,
+): void {
if (endMs === undefined) return;
const execStart = card.approvalAtMs ?? card.callStartedAtMs;
if (execStart === undefined) return;
@@ -1446,6 +1451,10 @@ function settleToolDuration(card: ToolCallItem, endMs: number | undefined): void
? Math.max(0, card.callStartedAtMs - card.argStartedAtMs)
: 0;
card.durationMs = genMs + Math.max(0, endMs - execStart);
+ // The execution half alone feeds the session's tool wall time: the generation half above is
+ // the model streaming arguments and is already inside taskLlmMs. Settling twice (a streamed
+ // stop, then the complete message) is harmless — the intervals are unioned, not summed.
+ if (stats) addToolExecution(stats, execStart, endMs);
}
/**
diff --git a/packages/web/src/lib/omni/task-stats.ts b/packages/web/src/lib/omni/task-stats.ts
index 96c7c128..1bbb7f9a 100644
--- a/packages/web/src/lib/omni/task-stats.ts
+++ b/packages/web/src/lib/omni/task-stats.ts
@@ -95,6 +95,14 @@ export interface TaskStatsTracker {
taskMainOutput: number;
/** This Task's main-session LLM generation duration cumulative (ms, request_begin↔request_end wall clock; compaction requests excluded). */
taskLlmMs: number;
+ /**
+ * This Task's main-session tool EXECUTION intervals (epoch ms), merged into `sessionToolMs`
+ * when the Task closes. Kept as intervals rather than a running sum because tool calls run in
+ * parallel: summing their durations would report more tool time than the clock ever spent.
+ * Only the execution half is recorded — the argument-generation half is the model streaming
+ * arguments and is already inside `taskLlmMs`, and the human approval wait belongs to neither.
+ */
+ taskToolIntervals: Array<[number, number]>;
/**
* **Pending** bucket for compaction request usage: when compaction arrives, it's not yet known
* whether it's **mid-round** (a normal Request still follows in this round → usage belongs to
@@ -112,6 +120,19 @@ export interface TaskStatsTracker {
hasUsage: boolean;
/** Session total elapsed time (sum of each Task's elapsed time, ms). */
sessionElapsedMs: number;
+ /**
+ * Session cumulative model-API time (ms): the sum of the finished Tasks' `taskLlmMs`. Same
+ * scope as `sessionElapsedMs` beside it — main session only, compaction excluded — so the
+ * component and the total the header shows it under are measured over the same turns.
+ */
+ sessionLlmMs: number;
+ /**
+ * Session cumulative tool wall time (ms): per Task the union of `taskToolIntervals`, summed
+ * across Tasks. May **overlap** `sessionLlmMs`, since a background tool keeps running while
+ * the model decodes: the two are measured components of the elapsed time, not a partition of
+ * it, and the display must never derive one from the other.
+ */
+ sessionToolMs: number;
/** Compaction in progress (between compaction_begin and end). */
compactionActive: boolean;
}
@@ -129,16 +150,54 @@ export function createTaskStatsTracker(): TaskStatsTracker {
taskOutput: 0,
taskMainOutput: 0,
taskLlmMs: 0,
+ taskToolIntervals: [],
pendingCompactionTokens: 0,
pendingCompactionCacheRead: 0,
pendingCompactionCacheWrite: 0,
pendingCompactionOutput: 0,
hasUsage: false,
sessionElapsedMs: 0,
+ sessionLlmMs: 0,
+ sessionToolMs: 0,
compactionActive: false,
};
}
+/**
+ * Total length of the **union** of the given intervals (ms): overlapping and nested runs count
+ * once, so parallel tool calls yield wall time instead of a sum of durations. Input order does
+ * not matter, and repeating an identical interval changes nothing — which is what lets a tool
+ * whose duration settles twice (a streamed stop and then the complete message) be recorded
+ * twice without inflating the figure.
+ */
+export function mergedIntervalMs(intervals: ReadonlyArray<readonly [number, number]>): number {
+ if (intervals.length === 0) return 0;
+ const sorted = [...intervals].sort((a, b) => a[0] - b[0]);
+ let total = 0;
+ let [openStart, openEnd] = sorted[0]!;
+ for (let i = 1; i < sorted.length; i++) {
+ const [start, end] = sorted[i]!;
+ if (start > openEnd) {
+ total += openEnd - openStart;
+ openStart = start;
+ openEnd = end;
+ } else if (end > openEnd) {
+ openEnd = end;
+ }
+ }
+ return total + (openEnd - openStart);
+}
+
+/**
+ * Records one settled tool EXECUTION interval into the open Task (called by stream-model when a
+ * tool's output closes). Zero-length and reversed intervals are dropped rather than clamped:
+ * they carry no wall time, and keeping them would only grow the array.
+ */
+export function addToolExecution(t: TaskStatsTracker, startMs: number, endMs: number): void {
+ if (!Number.isFinite(startMs) || !Number.isFinite(endMs) || endMs <= startMs) return;
+ t.taskToolIntervals.push([startMs, endMs]);
+}
+
/**
* Seed the tracker with the cumulative stats accrued BEFORE a partial history window
* (MessagesPageInfo.prior from a windowed GET /messages): finished-Task elapsed,
@@ -153,12 +212,18 @@ export function seedPriorStats(
prior: {
subagentTokens: number;
elapsedMs: number;
+ apiMs: number;
+ toolMs: number;
sessionTokens: number;
contextTokens: number;
},
): void {
t.subagentTotal = prior.subagentTokens;
t.sessionElapsedMs = prior.elapsedMs;
+ // The elapsed breakdown is seeded alongside its total: seeding one without the others would
+ // show a windowed reload a full elapsed time next to components covering only the window.
+ t.sessionLlmMs = prior.apiMs;
+ t.sessionToolMs = prior.toolMs;
t.sessionTotal = prior.sessionTokens;
t.contextNow = prior.contextTokens;
// The first in-window stats row's context delta measures against the pre-window
@@ -279,6 +344,9 @@ export function resetTaskCounters(t: TaskStatsTracker): void {
t.taskOutput = 0;
t.taskMainOutput = 0;
t.taskLlmMs = 0;
+ // Dropped, not folded into the session cumulative — the same treatment sessionElapsedMs gets
+ // here: time measured outside a Task boundary belongs to no Task and enters no total.
+ t.taskToolIntervals = [];
// Unsettled pending compaction usage is discarded here: the round has ended and no further
// Request follows in this round → compaction after round end, doesn't belong to this round.
clearPendingCompaction(t);
@@ -307,6 +375,14 @@ export interface TaskStats {
*/
export function endTask(t: TaskStatsTracker, elapsedMs: number): TaskStats | null {
t.sessionElapsedMs += elapsedMs;
+ // The two components fold on the same boundary as the total above and are cleared here, so
+ // the early return below (a Task with no usage) cannot leave them to be folded a second time.
+ // taskLlmMs is still the TPS denominator further down, so it is read out before clearing.
+ const taskLlmMs = t.taskLlmMs;
+ t.sessionLlmMs += taskLlmMs;
+ t.sessionToolMs += mergedIntervalMs(t.taskToolIntervals);
+ t.taskLlmMs = 0;
+ t.taskToolIntervals = [];
// Unsettled pending compaction usage is discarded at close: the round's end is fixed and no
// further Request follows in this round → compaction after round end, doesn't belong to this round.
clearPendingCompaction(t);
@@ -326,7 +402,7 @@ export function endTask(t: TaskStatsTracker, elapsedMs: number): TaskStats | nul
cacheWrite: t.taskCacheWrite,
output: t.taskOutput,
},
- outputTps: computeTps(t.taskMainOutput, t.taskLlmMs),
+ outputTps: computeTps(t.taskMainOutput, taskLlmMs),
};
t.contextAtLastStats = t.contextNow;
t.taskTokens = 0;
@@ -334,12 +410,34 @@ export function endTask(t: TaskStatsTracker, elapsedMs: number): TaskStats | nul
t.taskCacheWrite = 0;
t.taskOutput = 0;
t.taskMainOutput = 0;
- t.taskLlmMs = 0;
t.hasUsage = false;
t.compactionActive = false;
return stats;
}
+/** The two measured components of a Session's elapsed time (see sessionElapsedBreakdown). */
+export interface ElapsedBreakdown {
+ apiMs: number;
+ toolMs: number;
+}
+
+/**
+ * The elapsed time's breakdown for display: the settled cross-Task cumulative plus whatever the
+ * OPEN Task has settled so far, so the parts keep pace with the ticking total instead of lagging
+ * a whole Task behind it. Both are exact at every moment — a Request or tool still in flight
+ * joins only when it closes, which is why the parts trail the total slightly mid-turn.
+ *
+ * They are two measurements, not a partition: they can overlap (a background tool running while
+ * the model decodes) and they can undershoot (approval waits and harness overhead belong to
+ * neither), so a caller must never derive one from the elapsed total minus the other.
+ */
+export function sessionElapsedBreakdown(t: TaskStatsTracker): ElapsedBreakdown {
+ return {
+ apiMs: t.sessionLlmMs + t.taskLlmMs,
+ toolMs: t.sessionToolMs + mergedIntervalMs(t.taskToolIntervals),
+ };
+}
+
/**
* Session elapsed time for live display (the header chip): the settled cross-Task cumulative
* plus the currently running Task's wall clock so far. While no Task is open this is exactly
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 16fd18ed..2e677c6a 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -1720,6 +1720,7 @@ Scenarios:
statTotalTokens: "Total Tokens",
statCacheHit: (pct: string) => `cache hit rate ${pct}`,
statElapsed: "Elapsed",
+ statElapsedSplit: (apiMs: string, toolMs: string): string => `API ${apiMs}, tools ${toolMs}`,
statInput: "Input tokens",
statCached: "cached",
statOutput: "Output tokens",
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 81203805..e7c1592c 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -1685,6 +1685,12 @@ Benchmark:
statTotalTokens: "总 Token",
statCacheHit: (pct: string) => `缓存命中率 ${pct}`,
statElapsed: "用时",
+ /**
+ * The elapsed time's two measured components, shown in parentheses after it. They may
+ * overlap (a background tool runs while the model decodes) and may leave a remainder
+ * (approval waits, harness overhead), so this reads as two measurements, never as a split.
+ */
+ statElapsedSplit: (apiMs: string, toolMs: string): string => `API ${apiMs},工具 ${toolMs}`,
statInput: "输入 tokens",
statCached: "已缓存",
statOutput: "输出 tokens",
diff --git a/packages/web/test/stream-controller.test.ts b/packages/web/test/stream-controller.test.ts
index defc6606..a93094a3 100644
--- a/packages/web/test/stream-controller.test.ts
+++ b/packages/web/test/stream-controller.test.ts
@@ -127,7 +127,14 @@ function createHarness(): Harness {
function pageInfo(over: Partial<MessagesPageInfo> = {}): MessagesPageInfo {
return {
earlierTurns: 0,
- prior: { subagentTokens: 0, elapsedMs: 0, sessionTokens: 0, contextTokens: 0 },
+ prior: {
+ subagentTokens: 0,
+ elapsedMs: 0,
+ apiMs: 0,
+ toolMs: 0,
+ sessionTokens: 0,
+ contextTokens: 0,
+ },
...over,
};
}
@@ -529,7 +536,14 @@ describe("windowed history: tail-first load + scroll-up backfill", () => {
pageInfo({
before: "2:10",
earlierTurns: 7,
- prior: { subagentTokens: 500, elapsedMs: 60_000, sessionTokens: 900, contextTokens: 800 },
+ prior: {
+ subagentTokens: 500,
+ elapsedMs: 60_000,
+ apiMs: 25_000,
+ toolMs: 20_000,
+ sessionTokens: 900,
+ contextTokens: 800,
+ },
}),
);
await p;
@@ -538,6 +552,10 @@ describe("windowed history: tail-first load + scroll-up backfill", () => {
// Header basis: prior elapsed + the loaded turn's own span (usage at +5s of a turn
// starting at 0s); token cumulative = in-window session.total + prior subagent total.
expect(h.controller.model.stats.sessionElapsedMs).toBe(60_000 + 5_000);
+ // The breakdown reloads with its total, so a windowed load never shows a full elapsed time
+ // beside components covering only the window.
+ expect(h.controller.model.stats.sessionLlmMs).toBe(25_000);
+ expect(h.controller.model.stats.sessionToolMs).toBe(20_000);
const stats = h.controller.model.items.find((i) => i.kind === "task_stats") as TaskStatsItem;
expect(stats.stats!.tokens).toBe(1000 + 500);
});
diff --git a/packages/web/test/task-stats.test.ts b/packages/web/test/task-stats.test.ts
index 8f6e9fe5..66348f65 100644
--- a/packages/web/test/task-stats.test.ts
+++ b/packages/web/test/task-stats.test.ts
@@ -6,6 +6,10 @@ import { describe, expect, it } from "vitest";
import type { TokenUsagePayload } from "@prismshadow/penguin-core/omnimessage";
import {
addLlmDuration,
+ addToolExecution,
+ mergedIntervalMs,
+ seedPriorStats,
+ sessionElapsedBreakdown,
beginCompaction,
bucketCostUsd,
commitPendingCompaction,
@@ -329,3 +333,115 @@ describe("formatTaskStats", () => {
).toBe("[统计信息] 输入 tokens 4k(已缓存 3k) · 输出 tokens 1.2k · 42.5 tok/s");
});
});
+
+describe("elapsed breakdown: API time and tool wall time", () => {
+ it("unions intervals so parallel tools count once", () => {
+ expect(mergedIntervalMs([])).toBe(0);
+ // Overlapping, nested, adjacent and out-of-order all reduce to the covered span.
+ expect(
+ mergedIntervalMs([
+ [3000, 9000],
+ [4000, 11000],
+ ]),
+ ).toBe(8000);
+ expect(
+ mergedIntervalMs([
+ [0, 10000],
+ [2000, 3000],
+ ]),
+ ).toBe(10000);
+ expect(
+ mergedIntervalMs([
+ [5000, 6000],
+ [0, 5000],
+ ]),
+ ).toBe(6000);
+ expect(
+ mergedIntervalMs([
+ [8000, 9000],
+ [0, 1000],
+ ]),
+ ).toBe(2000);
+ // Recording the same execution twice (a streamed stop, then the complete message) is what
+ // lets stream-model settle a duration twice without inflating the figure.
+ expect(
+ mergedIntervalMs([
+ [1000, 4000],
+ [1000, 4000],
+ ]),
+ ).toBe(3000);
+ });
+
+ it("drops executions that carry no wall time", () => {
+ const t = createTaskStatsTracker();
+ addToolExecution(t, 1000, 1000);
+ addToolExecution(t, 2000, 1000);
+ addToolExecution(t, Number.NaN, 5000);
+ expect(t.taskToolIntervals).toEqual([]);
+ });
+
+ it("folds both components into the session totals at the Task boundary", () => {
+ const t = createTaskStatsTracker();
+ addLlmDuration(t, 2000);
+ addToolExecution(t, 3000, 9000);
+ addToolExecution(t, 4000, 11000);
+ // Before the boundary the open Task's parts are already visible, so the breakdown keeps
+ // pace with the ticking total instead of lagging a whole Task behind it.
+ expect(sessionElapsedBreakdown(t)).toEqual({ apiMs: 2000, toolMs: 8000 });
+
+ endTask(t, 12000);
+ expect(t.sessionLlmMs).toBe(2000);
+ expect(t.sessionToolMs).toBe(8000);
+ expect(t.taskToolIntervals).toEqual([]);
+ expect(t.taskLlmMs).toBe(0);
+ expect(sessionElapsedBreakdown(t)).toEqual({ apiMs: 2000, toolMs: 8000 });
+
+ // A second Task accumulates on top rather than restarting.
+ addLlmDuration(t, 1000);
+ addToolExecution(t, 20000, 21000);
+ endTask(t, 3000);
+ expect(sessionElapsedBreakdown(t)).toEqual({ apiMs: 3000, toolMs: 9000 });
+ });
+
+ it("keeps the components' TPS denominator intact across the fold", () => {
+ const t = createTaskStatsTracker();
+ trackMainUsage(t, {
+ type: "token_usage",
+ session: { cache_read: 0, cache_write: 0, output: 1000, total: 1000 },
+ request: { cache_read: 0, cache_write: 0, output: 1000, total: 1000 },
+ });
+ addLlmDuration(t, 2000);
+ // endTask folds taskLlmMs into the session total AND still reports it as the TPS
+ // denominator: 1000 output tokens over 2s.
+ expect(endTask(t, 2000)?.outputTps).toBe(500);
+ expect(t.sessionLlmMs).toBe(2000);
+ });
+
+ it("drops a Task's components when its counters reset outside a boundary", () => {
+ const t = createTaskStatsTracker();
+ addLlmDuration(t, 2000);
+ addToolExecution(t, 1000, 5000);
+ // resetTaskCounters is the "usage outside a Task" path: it leaves sessionElapsedMs alone,
+ // so the components it discards must not reach the session totals either.
+ resetTaskCounters(t);
+ expect(sessionElapsedBreakdown(t)).toEqual({ apiMs: 0, toolMs: 0 });
+ expect(t.sessionLlmMs).toBe(0);
+ expect(t.sessionToolMs).toBe(0);
+ });
+
+ it("seeds the breakdown from a windowed load's prior stats", () => {
+ const t = createTaskStatsTracker();
+ seedPriorStats(t, {
+ subagentTokens: 0,
+ elapsedMs: 30000,
+ apiMs: 12000,
+ toolMs: 9000,
+ sessionTokens: 0,
+ contextTokens: 0,
+ });
+ // Total and components are seeded together: seeding one alone would show a full elapsed
+ // time beside components covering only the loaded window.
+ expect(t.sessionElapsedMs).toBe(30000);
+ expect(sessionElapsedBreakdown(t)).toEqual({ apiMs: 12000, toolMs: 9000 });
+ });
+});