Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

feat(context-usage): split session timing metrics (#1625)

Lanaf6da4d5f429
diff --git a/apps/desktop/src/components/ContextUsageInspector.tsx b/apps/desktop/src/components/ContextUsageInspector.tsx
index d9b79f220..261e027d5 100644
--- a/apps/desktop/src/components/ContextUsageInspector.tsx
+++ b/apps/desktop/src/components/ContextUsageInspector.tsx
@@ -113,20 +113,28 @@ export function ContextUsageInspector({
usage.inputTokens,
usage.cacheReadTokens,
);
- const modelResponseDuration = formatToolDuration(
- (sessionTiming.timing?.modelResponseMs ?? 0) / 1_000,
+ const formatTimingValue = (durationMs?: number, percent?: number) => {
+ if (sessionTiming.historyStatus === "loading") return "…";
+ if (sessionTiming.historyStatus === "error" || durationMs === undefined) {
+ return t("chat.usageTimingUnavailable");
+ }
+ return `${formatToolDuration(durationMs / 1_000)}${
+ percent === undefined ? "" : ` · ${percent}%`
+ }`;
+ };
+ const timingBreakdown = sessionTiming.breakdown;
+ const networkRequestValue = formatTimingValue(
+ timingBreakdown?.networkRequestMs,
+ timingBreakdown?.networkRequestPercent,
+ );
+ const modelResponseValue = formatTimingValue(
+ timingBreakdown?.modelResponseMs,
+ timingBreakdown?.modelResponsePercent,
+ );
+ const toolCallValue = formatTimingValue(
+ timingBreakdown?.toolCallMs,
+ timingBreakdown?.toolCallPercent,
);
- const modelResponsePercent = sessionTiming.timing?.modelResponsePercent;
- const modelResponseValue =
- sessionTiming.historyStatus === "loading"
- ? "…"
- : sessionTiming.historyStatus === "error"
- ? t("chat.usageTimingUnavailable")
- : `${modelResponseDuration}${
- modelResponsePercent === undefined
- ? ""
- : ` · ${modelResponsePercent}%`
- }`;
const toolRows = aggregateToolTokenUsage(tools);
const toolTotal = toolRows.reduce(
(total, row) => total + row.totalTokens,
@@ -350,19 +358,43 @@ export function ContextUsageInspector({
</div>
</div>
{sessionTiming.timing ? (
- <div
- className="context-inspector-kpis"
- aria-busy={sessionTiming.historyStatus === "loading"}
- >
+ <div className="context-inspector-kpis">
<div>
<span>{t("chat.usageSessionTime")}</span>
<strong>
{formatToolDuration(sessionTiming.timing.elapsedMs / 1_000)}
</strong>
</div>
- <div>
- <span>{t("chat.usageModelResponse")}</span>
- <strong>{modelResponseValue}</strong>
+ </div>
+ ) : null}
+ {sessionTiming.timing ? (
+ <div
+ className="context-inspector-summary"
+ aria-busy={sessionTiming.historyStatus === "loading"}
+ >
+ <div className="context-inspector-summary-row">
+ <strong title={t("chat.usageNetworkRequestHelp")}>
+ {t("chat.usageNetworkRequest")}
+ </strong>
+ <span className="context-inspector-summary-values">
+ {networkRequestValue}
+ </span>
+ </div>
+ <div className="context-inspector-summary-row">
+ <strong title={t("chat.usageModelResponseHelp")}>
+ {t("chat.usageModelResponse")}
+ </strong>
+ <span className="context-inspector-summary-values">
+ {modelResponseValue}
+ </span>
+ </div>
+ <div className="context-inspector-summary-row">
+ <strong title={t("chat.usageToolCallsHelp")}>
+ {t("chat.usageToolCalls")}
+ </strong>
+ <span className="context-inspector-summary-values">
+ {toolCallValue}
+ </span>
</div>
</div>
) : null}
diff --git a/apps/desktop/src/features/chat/context-usage/useSessionTiming.ts b/apps/desktop/src/features/chat/context-usage/useSessionTiming.ts
index 62f3ec530..0dc7ee8ae 100644
--- a/apps/desktop/src/features/chat/context-usage/useSessionTiming.ts
+++ b/apps/desktop/src/features/chat/context-usage/useSessionTiming.ts
@@ -6,27 +6,31 @@ import type {
} from "@pi-desktop/shared";
import { api } from "../../../lib/api";
import {
+ calculateSessionTimingBreakdown,
calculateSessionTiming,
- loadEarlierModelResponseDuration,
+ loadEarlierSessionTiming,
+ type SessionTimingBreakdown,
type SessionTiming,
+ type SessionTimingTotals,
} from "../../../lib/session-timing";
import type { SessionHistoryWindow } from "../../../stores/app-state";
type HistoryLoadState = {
key: string;
status: "loading" | "ready" | "error";
- durationMs: number;
+ totals?: SessionTimingTotals;
};
type CachedSessionTiming = {
key: string;
- durationMs: number;
+ totals: SessionTimingTotals;
};
const MAX_CACHED_SESSION_TIMINGS = 16;
export type SessionTimingView = {
timing?: SessionTiming;
+ breakdown?: SessionTimingBreakdown;
historyStatus: "loading" | "ready" | "error";
};
@@ -51,49 +55,9 @@ export function useSessionTiming({
const hasMoreBefore = history?.hasMoreBefore === true;
const historyKey = `${sessionId ?? ""}:${messageStart}:${session?.updatedAt ?? ""}`;
const historyCache = useRef(new Map<string, CachedSessionTiming>());
- const [retainedRequest, setRetainedRequest] = useState<
- { sessionId: string; startedAt: number } | undefined
- >();
const [historyLoad, setHistoryLoad] = useState<HistoryLoadState>();
const [now, setNow] = useState(() => Date.now());
- const streamingMessageStartedAt = [...messages]
- .reverse()
- .find(
- (message) =>
- message.role === "assistant" &&
- !message.parentToolCallId &&
- !message.nestedParentToolCallId &&
- message.status === "streaming",
- )?.createdAt;
- const waitingRequestStartedAt =
- modelRequestActivity?.phase === "waiting-model"
- ? modelRequestActivity.since
- : undefined;
- useEffect(() => {
- if (!isRunning || !sessionId) {
- setRetainedRequest(undefined);
- } else if (
- typeof waitingRequestStartedAt === "number" &&
- Number.isFinite(waitingRequestStartedAt)
- ) {
- setRetainedRequest({ sessionId, startedAt: waitingRequestStartedAt });
- }
- }, [isRunning, sessionId, waitingRequestStartedAt]);
-
- const retainedRequestStartedAt =
- sessionId && retainedRequest?.sessionId === sessionId
- ? retainedRequest.startedAt
- : undefined;
- const currentRequestStartedAt =
- waitingRequestStartedAt ??
- (modelRequestActivity?.phase === "retrying"
- ? retainedRequestStartedAt ?? modelRequestActivity.since
- : undefined) ??
- (streamingMessageStartedAt
- ? retainedRequestStartedAt ?? Date.parse(streamingMessageStartedAt)
- : undefined);
-
useEffect(() => {
if (!enabled) return;
setNow(Date.now());
@@ -111,14 +75,14 @@ export function useSessionTiming({
setHistoryLoad({
key: historyKey,
status: "ready",
- durationMs: cachedTiming.durationMs,
+ totals: cachedTiming.totals,
});
return;
}
const controller = new AbortController();
- setHistoryLoad({ key: historyKey, status: "loading", durationMs: 0 });
- void loadEarlierModelResponseDuration(
+ setHistoryLoad({ key: historyKey, status: "loading" });
+ void loadEarlierSessionTiming(
messageStart,
async (options) => {
const result = await api.getSession(sessionId, options);
@@ -132,7 +96,7 @@ export function useSessionTiming({
},
controller.signal,
).then(
- (durationMs) => {
+ (totals) => {
if (controller.signal.aborted) return;
if (
!historyCache.current.has(sessionId) &&
@@ -141,12 +105,12 @@ export function useSessionTiming({
const oldestSessionId = historyCache.current.keys().next().value;
if (oldestSessionId) historyCache.current.delete(oldestSessionId);
}
- historyCache.current.set(sessionId, { key: historyKey, durationMs });
- setHistoryLoad({ key: historyKey, status: "ready", durationMs });
+ historyCache.current.set(sessionId, { key: historyKey, totals });
+ setHistoryLoad({ key: historyKey, status: "ready", totals });
},
() => {
if (controller.signal.aborted) return;
- setHistoryLoad({ key: historyKey, status: "error", durationMs: 0 });
+ setHistoryLoad({ key: historyKey, status: "error" });
},
);
@@ -158,6 +122,10 @@ export function useSessionTiming({
: historyLoad?.key === historyKey
? historyLoad.status
: "loading";
+ const earlierTotals =
+ historyStatus === "ready" && historyLoad?.key === historyKey
+ ? historyLoad.totals
+ : undefined;
const timing = enabled && session
? calculateSessionTiming({
createdAt: session.createdAt,
@@ -165,13 +133,20 @@ export function useSessionTiming({
isRunning,
messages,
now,
- earlierModelResponseMs:
- historyStatus === "ready" && historyLoad?.key === historyKey
- ? historyLoad.durationMs
- : 0,
- activeModelRequestStartedAt: currentRequestStartedAt,
+ earlierModelResponseMs: earlierTotals?.modelResponseMs ?? 0,
+ })
+ : undefined;
+ const breakdown = timing
+ ? calculateSessionTimingBreakdown({
+ elapsedMs: timing.elapsedMs,
+ messages,
+ now,
+ ...(earlierTotals ? { earlierTotals } : {}),
+ ...(modelRequestActivity?.phase === "waiting-model"
+ ? { activeNetworkRequestStartedAt: modelRequestActivity.since }
+ : {}),
})
: undefined;
- return { timing, historyStatus };
+ return { timing, breakdown, historyStatus };
}
diff --git a/apps/desktop/src/lib/session-timing.ts b/apps/desktop/src/lib/session-timing.ts
index 6dc5c40eb..ee66d6b9f 100644
--- a/apps/desktop/src/lib/session-timing.ts
+++ b/apps/desktop/src/lib/session-timing.ts
@@ -2,7 +2,17 @@ import type { UiMessage } from "@pi-desktop/shared";
export type SessionTimingMessage = Pick<
UiMessage,
- "role" | "responseDurationMs" | "parentToolCallId" | "nestedParentToolCallId" | "status" | "createdAt"
+ | "role"
+ | "responseDurationMs"
+ | "providerWaitMs"
+ | "modelStreamDurationMs"
+ | "toolDurationMs"
+ | "toolCompletedAt"
+ | "toolStatus"
+ | "parentToolCallId"
+ | "nestedParentToolCallId"
+ | "status"
+ | "createdAt"
>;
export type SessionTimingPage = {
@@ -17,6 +27,26 @@ export type SessionTiming = {
modelResponsePercent?: number;
};
+export type SessionTimingTotals = {
+ providerWaitMs: number;
+ hasProviderWait: boolean;
+ modelResponseMs: number;
+ hasModelResponse: boolean;
+ toolMessageCount: number;
+ toolTimingCount: number;
+ toolIntervals: Array<{ start: number; end: number }>;
+ unplacedToolDurationMs: number;
+};
+
+export type SessionTimingBreakdown = {
+ networkRequestMs?: number;
+ networkRequestPercent?: number;
+ modelResponseMs?: number;
+ modelResponsePercent?: number;
+ toolCallMs?: number;
+ toolCallPercent?: number;
+};
+
const SESSION_TIMING_PAGE_SIZE = 1_000;
const SESSION_TIMING_CONTENT_LIMIT = 256;
@@ -39,6 +69,188 @@ export function sumModelResponseDuration(
}, 0);
}
+function finiteDuration(value: number | undefined): number | undefined {
+ return typeof value === "number" && Number.isFinite(value) && value >= 0
+ ? value
+ : undefined;
+}
+
+function emptySessionTimingTotals(): SessionTimingTotals {
+ return {
+ providerWaitMs: 0,
+ hasProviderWait: false,
+ modelResponseMs: 0,
+ hasModelResponse: false,
+ toolMessageCount: 0,
+ toolTimingCount: 0,
+ toolIntervals: [],
+ unplacedToolDurationMs: 0,
+ };
+}
+
+export function combineSessionTimingTotals(
+ left: SessionTimingTotals,
+ right: SessionTimingTotals,
+): SessionTimingTotals {
+ return {
+ providerWaitMs: left.providerWaitMs + right.providerWaitMs,
+ hasProviderWait: left.hasProviderWait || right.hasProviderWait,
+ modelResponseMs: left.modelResponseMs + right.modelResponseMs,
+ hasModelResponse: left.hasModelResponse || right.hasModelResponse,
+ toolMessageCount: left.toolMessageCount + right.toolMessageCount,
+ toolTimingCount: left.toolTimingCount + right.toolTimingCount,
+ toolIntervals: [...left.toolIntervals, ...right.toolIntervals],
+ unplacedToolDurationMs:
+ left.unplacedToolDurationMs + right.unplacedToolDurationMs,
+ };
+}
+
+/** Sum persisted timing signals without double-counting nested delegate work. */
+export function sumSessionTiming(
+ messages: readonly SessionTimingMessage[],
+ now = Date.now(),
+): SessionTimingTotals {
+ const totals = emptySessionTimingTotals();
+
+ for (const message of messages) {
+ const isNested =
+ Boolean(message.parentToolCallId) || Boolean(message.nestedParentToolCallId);
+ if (isNested) continue;
+
+ if (message.role === "assistant") {
+ const providerWaitMs = finiteDuration(message.providerWaitMs);
+ if (providerWaitMs !== undefined) {
+ totals.providerWaitMs += providerWaitMs;
+ totals.hasProviderWait = true;
+ }
+
+ const modelResponseMs =
+ finiteDuration(message.modelStreamDurationMs) ??
+ finiteDuration(message.responseDurationMs);
+ if (modelResponseMs !== undefined) {
+ totals.modelResponseMs += modelResponseMs;
+ totals.hasModelResponse = true;
+ }
+
+ if (message.status === "streaming") {
+ const startedAt = Date.parse(message.createdAt);
+ if (Number.isFinite(startedAt)) {
+ totals.modelResponseMs += Math.max(0, now - startedAt);
+ totals.hasModelResponse = true;
+ }
+ }
+ continue;
+ }
+
+ if (message.role !== "tool") continue;
+ totals.toolMessageCount += 1;
+ const storedDurationMs = finiteDuration(message.toolDurationMs);
+ const startedAt = Date.parse(message.createdAt);
+ const isRunning = message.toolStatus === "running" || message.status === "streaming";
+ const durationMs =
+ isRunning && Number.isFinite(startedAt)
+ ? Math.max(storedDurationMs ?? 0, now - startedAt)
+ : storedDurationMs;
+ if (durationMs === undefined) continue;
+
+ totals.toolTimingCount += 1;
+ if (Number.isFinite(startedAt)) {
+ const completedAt = message.toolCompletedAt
+ ? Date.parse(message.toolCompletedAt)
+ : Number.NaN;
+ totals.toolIntervals.push({
+ start: startedAt,
+ end:
+ Number.isFinite(completedAt) && completedAt >= startedAt
+ ? completedAt
+ : startedAt + durationMs,
+ });
+ } else {
+ totals.unplacedToolDurationMs += durationMs;
+ }
+ }
+
+ return totals;
+}
+
+function unionDurationMs(intervals: readonly { start: number; end: number }[]): number {
+ const sorted = intervals
+ .filter((interval) => Number.isFinite(interval.start) && interval.end > interval.start)
+ .slice()
+ .sort((left, right) => left.start - right.start);
+ if (sorted.length === 0) return 0;
+
+ let total = 0;
+ let start = sorted[0].start;
+ let end = sorted[0].end;
+ for (const interval of sorted.slice(1)) {
+ if (interval.start <= end) {
+ end = Math.max(end, interval.end);
+ } else {
+ total += end - start;
+ start = interval.start;
+ end = interval.end;
+ }
+ }
+ return total + end - start;
+}
+
+export function calculateSessionTimingBreakdown({
+ elapsedMs,
+ messages,
+ now,
+ earlierTotals = emptySessionTimingTotals(),
+ activeNetworkRequestStartedAt,
+}: {
+ elapsedMs: number;
+ messages: readonly SessionTimingMessage[];
+ now: number;
+ earlierTotals?: SessionTimingTotals;
+ activeNetworkRequestStartedAt?: number;
+}): SessionTimingBreakdown {
+ const totals = combineSessionTimingTotals(
+ earlierTotals,
+ sumSessionTiming(messages, now),
+ );
+ const activeNetworkWaitMs =
+ typeof activeNetworkRequestStartedAt === "number" &&
+ Number.isFinite(activeNetworkRequestStartedAt)
+ ? Math.max(0, now - activeNetworkRequestStartedAt)
+ : 0;
+ const networkRequestMs = totals.providerWaitMs + activeNetworkWaitMs;
+ const hasNetworkRequest = totals.hasProviderWait || activeNetworkWaitMs > 0;
+ const toolCallMs =
+ totals.toolMessageCount === 0 ||
+ totals.toolTimingCount === totals.toolMessageCount
+ ? unionDurationMs(totals.toolIntervals) + totals.unplacedToolDurationMs
+ : undefined;
+ const percent = (durationMs: number | undefined) =>
+ durationMs !== undefined && elapsedMs > 0
+ ? Math.round((durationMs / elapsedMs) * 100)
+ : undefined;
+
+ return {
+ ...(hasNetworkRequest
+ ? {
+ networkRequestMs,
+ networkRequestPercent: percent(networkRequestMs),
+ }
+ : {}),
+ ...(totals.hasModelResponse
+ ? {
+ modelResponseMs: totals.modelResponseMs,
+ modelResponsePercent: percent(totals.modelResponseMs),
+ }
+ : {}),
+ ...(toolCallMs !== undefined
+ ? {
+ toolCallMs,
+ toolCallPercent: percent(toolCallMs),
+ }
+ : {}),
+ };
+}
+
/**
* Read earlier transcript pages for the response durations omitted from the
* renderer's bounded transcript window. The callback keeps this helper
@@ -84,6 +296,49 @@ export async function loadEarlierModelResponseDuration(
return total;
}
+export async function loadEarlierSessionTiming(
+ messageBefore: number,
+ readPage: (options: {
+ messageBefore: number;
+ messageLimit: number;
+ contentLimit: number;
+ }) => Promise<SessionTimingPage | null>,
+ signal?: AbortSignal,
+): Promise<SessionTimingTotals> {
+ let before = messageBefore;
+ let totals = emptySessionTimingTotals();
+
+ while (before > 0) {
+ if (signal?.aborted) return totals;
+ const page = await readPage({
+ messageBefore: before,
+ messageLimit: SESSION_TIMING_PAGE_SIZE,
+ contentLimit: SESSION_TIMING_CONTENT_LIMIT,
+ });
+ if (signal?.aborted) return totals;
+ if (!page) throw new Error("Session timing history is unavailable");
+
+ totals = combineSessionTimingTotals(
+ totals,
+ sumSessionTiming(page.messages ?? []),
+ );
+ if (page.hasMoreBefore !== true) return totals;
+
+ const nextBefore = page.messageStart;
+ if (
+ typeof nextBefore !== "number" ||
+ !Number.isInteger(nextBefore) ||
+ nextBefore < 0 ||
+ nextBefore >= before
+ ) {
+ throw new Error("Session timing history did not advance");
+ }
+ before = nextBefore;
+ }
+
+ return totals;
+}
+
export function calculateSessionTiming({
createdAt,
updatedAt,
diff --git a/apps/desktop/test/session-timing.test.mjs b/apps/desktop/test/session-timing.test.mjs
index 8c4c231b5..26fc596d1 100644
--- a/apps/desktop/test/session-timing.test.mjs
+++ b/apps/desktop/test/session-timing.test.mjs
@@ -1,8 +1,10 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
+ calculateSessionTimingBreakdown,
calculateSessionTiming,
loadEarlierModelResponseDuration,
+ loadEarlierSessionTiming,
sumModelResponseDuration,
} from "../src/lib/session-timing.ts";
@@ -111,3 +113,130 @@ test("earlier timing pages fail visibly when their cursor does not advance", asy
/did not advance/,
);
});
+
+test("session timing separates provider wait, streamed response, and overlapping tools", () => {
+ const start = Date.parse("2026-10-01T00:00:00.000Z");
+ const at = (offsetMs) => new Date(start + offsetMs).toISOString();
+
+ assert.deepEqual(
+ calculateSessionTimingBreakdown({
+ elapsedMs: 20_000,
+ now: start + 20_000,
+ messages: [
+ {
+ role: "assistant",
+ createdAt: at(0),
+ providerWaitMs: 1_000,
+ modelStreamDurationMs: 2_000,
+ },
+ {
+ role: "assistant",
+ createdAt: at(0),
+ providerWaitMs: 500,
+ modelStreamDurationMs: 1_000,
+ parentToolCallId: "delegate-1",
+ },
+ {
+ role: "tool",
+ createdAt: at(5_000),
+ toolCompletedAt: at(9_000),
+ toolDurationMs: 4_000,
+ },
+ {
+ role: "tool",
+ createdAt: at(7_000),
+ toolCompletedAt: at(11_000),
+ toolDurationMs: 4_000,
+ },
+ {
+ role: "tool",
+ createdAt: at(5_000),
+ toolCompletedAt: at(19_000),
+ toolDurationMs: 14_000,
+ nestedParentToolCallId: "delegate-1",
+ },
+ ],
+ }),
+ {
+ networkRequestMs: 1_000,
+ networkRequestPercent: 5,
+ modelResponseMs: 2_000,
+ modelResponsePercent: 10,
+ toolCallMs: 6_000,
+ toolCallPercent: 30,
+ },
+ );
+});
+
+test("session timing uses legacy model durations and live request/stream timers", () => {
+ const start = Date.parse("2026-10-01T00:00:00.000Z");
+ const breakdown = calculateSessionTimingBreakdown({
+ elapsedMs: 10_000,
+ now: start + 10_000,
+ activeNetworkRequestStartedAt: start + 8_000,
+ messages: [
+ {
+ role: "assistant",
+ createdAt: new Date(start + 7_000).toISOString(),
+ status: "streaming",
+ providerWaitMs: 250,
+ modelStreamDurationMs: 500,
+ },
+ {
+ role: "assistant",
+ createdAt: new Date(start).toISOString(),
+ responseDurationMs: 1_000,
+ },
+ ],
+ });
+
+ assert.deepEqual(breakdown, {
+ networkRequestMs: 2_250,
+ networkRequestPercent: 23,
+ modelResponseMs: 4_500,
+ modelResponsePercent: 45,
+ toolCallMs: 0,
+ toolCallPercent: 0,
+ });
+});
+
+test("earlier timing pages include request, response, and tool metadata", async () => {
+ const pages = new Map([
+ [2_000, {
+ messages: [{
+ role: "assistant",
+ createdAt: "2026-10-01T00:00:00.000Z",
+ providerWaitMs: 700,
+ modelStreamDurationMs: 1_200,
+ }],
+ messageStart: 1_000,
+ hasMoreBefore: true,
+ }],
+ [1_000, {
+ messages: [{
+ role: "tool",
+ createdAt: "2026-10-01T00:00:01.000Z",
+ toolCompletedAt: "2026-10-01T00:00:03.000Z",
+ toolDurationMs: 2_000,
+ }],
+ messageStart: 0,
+ hasMoreBefore: false,
+ }],
+ ]);
+ const reads = [];
+
+ const totals = await loadEarlierSessionTiming(2_000, async (options) => {
+ reads.push(options);
+ return pages.get(options.messageBefore) ?? null;
+ });
+
+ assert.equal(totals.providerWaitMs, 700);
+ assert.equal(totals.modelResponseMs, 1_200);
+ assert.equal(totals.toolMessageCount, 1);
+ assert.equal(totals.toolTimingCount, 1);
+ assert.deepEqual(totals.toolIntervals, [{
+ start: Date.parse("2026-10-01T00:00:01.000Z"),
+ end: Date.parse("2026-10-01T00:00:03.000Z"),
+ }]);
+ assert.deepEqual(reads.map((read) => read.messageBefore), [2_000, 1_000]);
+});
diff --git a/apps/desktop/test/transcript-style.test.mjs b/apps/desktop/test/transcript-style.test.mjs
index a93665903..13a8b7d13 100644
--- a/apps/desktop/test/transcript-style.test.mjs
+++ b/apps/desktop/test/transcript-style.test.mjs
@@ -477,8 +477,11 @@ test("assistant context inspector keeps a compact summary and retry action wired
assert.match(inspectorSource, /context-inspector-kpis/);
assert.match(inspectorSource, /useSessionTiming/);
assert.match(inspectorSource, /chat\.usageSessionTime/);
+ assert.match(inspectorSource, /chat\.usageNetworkRequest/);
assert.match(inspectorSource, /chat\.usageModelResponse/);
- assert.match(inspectorSource, /modelResponsePercent/);
+ assert.match(inspectorSource, /chat\.usageToolCalls/);
+ assert.match(inspectorSource, /networkRequestPercent/);
+ assert.match(inspectorSource, /toolCallPercent/);
assert.match(inspectorSource, /context-inspector-window-percent/);
assert.match(inspectorSource, /chat\.usageContextLeft/);
assert.match(inspectorSource, /chat\.usageThroughput/);
diff --git a/docs/adr/0047-context-usage-inspector.md b/docs/adr/0047-context-usage-inspector.md
index 40da1bb44..046480336 100644
--- a/docs/adr/0047-context-usage-inspector.md
+++ b/docs/adr/0047-context-usage-inspector.md
@@ -30,9 +30,11 @@ anchor, but providers do not expose exact per-tool allocation.
3. Estimate each tool's argument and result footprint with the existing
pi-agent-core token heuristic. Persist the estimate on the tool message,
mark it as estimated in the UI, and never add it to the provider total.
-4. Carry `responseDurationMs` on assistant messages and `toolUsage` on tool
- messages. Add `toolUsage` to `tool_end` as an optional event field so live,
- persisted, and restored transcripts use the same values.
+4. Carry `responseDurationMs` on assistant messages for throughput, plus
+ `providerWaitMs` and `modelStreamDurationMs` for session timing. Carry
+ `toolUsage` and `toolDurationMs` on tool messages. Add `toolUsage` to
+ `tool_end` as an optional event field so live, persisted, and restored
+ transcripts use the same values.
5. Preserve additive compatibility: missing fields use the renderer fallback
estimate or omit throughput when no stream duration is available.
6. Render the inspector panel through `document.body` as a fixed viewport
@@ -55,6 +57,9 @@ anchor, but providers do not expose exact per-tool allocation.
footprint without opening logs, while repeated calls stay compact and
auditable through their call counts.
- Historical tool rows remain useful through a deterministic fallback estimate.
+- The session timing breakdown separates request-to-first-response wait from
+ streamed thinking/answer time and top-level tool execution. Overlapping
+ top-level tool calls count once; nested delegate timings are excluded.
- Tool estimates are transparent but cannot claim billing precision.
- The transcript protocol and storage shape gain optional fields, while the
existing protocol version remains compatible.
diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.md
index ee14880fc..dcdf1e96c 100644
--- a/docs/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/spec/03-runtime/01-ipc-protocol.md
@@ -962,7 +962,9 @@ type UiMessage = {
sessionMessage?: SessionMessageOrigin;
thinking?: string; // assistant reasoning, never folded into content
usage?: MessageUsage; // provider-reported assistant usage
- responseDurationMs?: number; // model stream duration for throughput
+ responseDurationMs?: number; // elapsed assistant response duration for throughput
+ providerWaitMs?: number; // request start to first model response event
+ modelStreamDurationMs?: number; // streamed thinking and answer duration
responseOutputTokens?: number; // estimated partial output when stop has no final usage
toolName?: string;
toolCallId?: string;
@@ -1184,15 +1186,24 @@ same normalized `AppError` carried by the lifecycle `error` event to the
assistant message before `message_end`. Error messages persist with the
transcript but are excluded from restored model context.
-The context inspector consumes two additive usage signals. `MessageUsage` is
-the provider-reported assistant usage and `responseDurationMs` is the
+The context inspector consumes additive usage and timing signals. `MessageUsage`
+is the provider-reported assistant usage and `responseDurationMs` is the
elapsed request duration used to display output tokens per second. Completed
responses use pi-ai 1.1.0's monotonic `AssistantMessage.durationMs`; when
-that value is unavailable, the sidecar stopwatch remains the fallback. `ToolTokenUsage`
-is a runtime estimate from the tool call arguments and result; providers do not
-report per-tool allocation, so the renderer labels these rows as estimates and
-never merges them into the exact provider total. Older peers may omit all of
-these optional fields without breaking the v6 handshake.
+that value is unavailable, the sidecar stopwatch remains the fallback.
+`providerWaitMs` measures from the model request start to the first response
+event, including transport and provider-side first-response wait;
+`modelStreamDurationMs` measures streamed thinking and answer content after
+that event. Both are persisted as optional assistant-message metadata. Older
+messages without split timing keep their prior `responseDurationMs` as the
+model-duration fallback; their request-wait duration cannot be recovered. The
+inspector sums top-level model timing and tool duration against elapsed session
+time; nested delegate timings are excluded, and overlapping top-level tool
+calls count once. `ToolTokenUsage` is a runtime estimate from the tool call
+arguments and result; providers do not report per-tool allocation, so the
+renderer labels these rows as estimates and never merges them into the exact
+provider total. Older peers may omit all of these optional fields without
+breaking the v6 handshake.
`turn_end.subagentUsage` is the settled subagent total since the previous
emitted `turn_end` of the same durable turn. Parent `message.usage` stays the
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.md
index fdecbb81f..067998318 100644
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@ -1685,6 +1685,9 @@ does not dispose, abort, or re-root a runtime belonging to another session.
estimate visible thinking plus answer output at four Unicode code points per
token and persist it as `responseOutputTokens` so stopped-turn throughput is
still available and visibly approximate
+- preserve request-to-first-response wait and streamed thinking/answer duration
+ on assistant messages when available; stopped streams retain the elapsed
+ streamed duration captured before cancellation
- renderer smart-stop transcript undo and structured Composer restoration are
reconciliation after abort; they do not change runtime cancellation or roll
back completed tool effects
diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.md
index f3d4ddc56..d7c52d90a 100644
--- a/docs/spec/04-ux/08-component-spec.md
+++ b/docs/spec/04-ux/08-component-spec.md
@@ -1912,8 +1912,14 @@ Single message render — either user (plaintext) or assistant (markdown streami
regardless of display mode, without making color the only signal.
Clicking the trigger (or activating it from the keyboard) toggles a
non-modal panel whose heading follows the same display-mode figure,
- followed by used/window counts and two
- unboxed turn/speed summary values. Model usage is compressed into one
+ followed by used/window counts, unboxed turn/speed summary values, and the
+ elapsed session time. Three compact timing rows show request-to-first-response
+ wait, streamed model response time (thinking plus answer), and top-level tool
+ execution time, each with its share of the session span. Network/provider wait
+ and streamed response are separate; parallel top-level tools count overlapping
+ time once, and nested delegate timing is excluded. Older messages retain the
+ existing response duration for the model row but cannot contribute request
+ wait. Model usage is compressed into one
inline summary row that retains exact last-request
input/output/cache/reasoning values
and the provider-reported cache hit rate when available. Tool usage is
diff --git a/docs/spec/04-ux/09-interaction-patterns.md b/docs/spec/04-ux/09-interaction-patterns.md
index 041e6c411..d5f1a728b 100644
--- a/docs/spec/04-ux/09-interaction-patterns.md
+++ b/docs/spec/04-ux/09-interaction-patterns.md
@@ -860,12 +860,14 @@ may be retained while exactly one workspace supplies the visible shell context.
- The context usage inspector keeps one muted line for the newest checkpoint,
shown while its panel is open — the count and summary cost sit below the
compact model/tool usage summaries without adding explanatory copy.
-- The open context usage inspector also shows the session's elapsed wall time
- and the cumulative duration of its top-level model responses. The response
- percentage compares those recorded request-to-completion durations with the
- session span; nested delegate responses are excluded because they may overlap.
- Long transcripts load earlier response timings in bounded pages only while
- the inspector is open.
+- The open context usage inspector shows elapsed session wall time plus three
+ cumulative timing rows: request-to-first-response wait, streamed model
+ response time (thinking and answer), and top-level tool execution time.
+ Each row shows its share of the elapsed session span. Nested delegate timing
+ is excluded, and overlapping top-level tool calls count once. Long transcripts
+ load earlier timing metadata in bounded pages only while the inspector is open.
+ Older messages use their existing response duration for the model row; their
+ request-wait time is unavailable.
## 4. Long content collapse / expand
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index fe7ac5d70..5de3b31ab 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -4918,12 +4918,15 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
badge and no context inspector under the answer. 3) Hover the composer
toolbar inspector trigger, confirm the panel stays closed, then click it.
4) Inspect the remaining-token-plus-percentage heading, used/window counts,
- unboxed turn/speed values, session duration, cumulative model response time
- with its share of session duration, one inline provider-usage summary, and
- one aggregate tool-usage summary, with no doubled heading rule and no inner
- section hairlines. For a transcript with more than one loaded page, wait for
- the earlier response timings to finish loading and confirm the cumulative
- value includes them. 5) Scroll the transcript and resize the window while the
+ unboxed turn/speed values, total session duration, and three timing rows for
+ network/provider wait, streamed model response (including thinking and
+ answer), and tool execution, each with its share of session duration. Confirm
+ overlapping top-level tool calls are counted once, nested delegate timings
+ are excluded, and one inline provider-usage summary plus one aggregate
+ tool-usage summary remain. There is no doubled heading rule or inner section
+ hairline. For a transcript with more than one loaded page, wait for earlier
+ timing metadata to finish loading and confirm the cumulative values include
+ it. 5) Scroll the transcript and resize the window while the
panel is open. Toggle and resize the sidebar and work panel while the panel
remains open. 6) Move the pointer away from the panel, then dismiss it by
clicking the trigger again, clicking outside it, and pressing Escape from
@@ -4943,9 +4946,11 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
survives the pointer leaving it and closes on a second trigger activation,
an outside click, or Escape, which returns focus to the trigger. Session
duration runs from session creation to the latest activity (or to now while
- running); cumulative model response time sums recorded top-level model
- request durations and its percentage is relative to that wall-time span.
- Earlier transcript pages load only while the inspector is open. Provider
+ running). Network request wait ends at the first model response event; model
+ response includes streamed thinking and answer, and tool time excludes nested
+ delegates and unions overlapping top-level calls. Each cumulative timing
+ percentage is relative to that wall-time span. Earlier transcript pages load
+ only while the inspector is open. Provider
values remain exact, tool values remain visibly approximate through the `~`
aggregate total, and no per-tool list, source badge, progress bar, or
explanatory estimate paragraph is rendered. Occupancy, turn total, and
diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.ts
index df0304e48..6fe4d6ca8 100644
--- a/packages/agent-runtime/src/runtime.test.ts
+++ b/packages/agent-runtime/src/runtime.test.ts
@@ -5784,6 +5784,101 @@ describe("DesktopAgentRuntime response duration", () => {
await runtime.dispose();
});
+ it("persists request wait separately from streamed thinking and answer time", async () => {
+ vi.useFakeTimers();
+ try {
+ const start = Date.parse("2026-10-01T00:00:00.000Z");
+ vi.setSystemTime(start + 1_000);
+ const onEvent = vi.fn();
+ const runtime = createRuntime({ onEvent });
+ const internals = runtime as unknown as {
+ handleAgentEvent(event: unknown): Promise<void>;
+ requestStartedAt: number | undefined;
+ };
+ internals.requestStartedAt = start;
+
+ await internals.handleAgentEvent({
+ type: "message_start",
+ message: { role: "assistant", content: [] },
+ });
+ await vi.advanceTimersByTimeAsync(2_500);
+ await internals.handleAgentEvent({
+ type: "message_end",
+ message: assistantMessage({
+ content: [
+ { type: "thinking", thinking: "reasoning" },
+ { type: "text", text: "answer" },
+ ],
+ }),
+ });
+
+ const events = onEvent.mock.calls.map(([envelope]) => envelope as any);
+ expect(events.find(({ event }) => event.type === "message_start")?.event.message)
+ .toMatchObject({ providerWaitMs: 1_000 });
+ expect(events.find(({ event }) => event.type === "message_end")?.event.message)
+ .toMatchObject({
+ providerWaitMs: 1_000,
+ modelStreamDurationMs: 2_500,
+ });
+ await runtime.dispose();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("accumulates request and stream timing across a provider retry", async () => {
+ vi.useFakeTimers();
+ try {
+ const start = Date.parse("2026-10-01T00:00:00.000Z");
+ vi.setSystemTime(start + 2_000);
+ const onEvent = vi.fn();
+ const runtime = createRuntime({ onEvent });
+ const internals = runtime as unknown as {
+ handleAgentEvent(event: unknown): Promise<void>;
+ requestStartedAt: number | undefined;
+ currentAssistant: unknown;
+ providerRetryInProgress: boolean;
+ };
+ internals.requestStartedAt = start + 1_000;
+ internals.providerRetryInProgress = true;
+ internals.currentAssistant = {
+ id: "assistant-retry",
+ role: "assistant",
+ content: "partial attempt",
+ createdAt: new Date(start).toISOString(),
+ status: "streaming",
+ modelId: "local-model",
+ providerId: "local",
+ providerWaitMs: 1_000,
+ modelStreamDurationMs: 500,
+ };
+
+ await internals.handleAgentEvent({
+ type: "message_start",
+ message: { role: "assistant", content: [] },
+ });
+ await vi.advanceTimersByTimeAsync(2_500);
+ await internals.handleAgentEvent({
+ type: "message_end",
+ message: assistantMessage({
+ content: [{ type: "text", text: "recovered answer" }],
+ }),
+ });
+
+ const terminal = onEvent.mock.calls
+ .map(([envelope]) => envelope as any)
+ .find(({ event }) => event.type === "message_end");
+ expect(terminal?.event.message).toMatchObject({
+ id: "assistant-retry",
+ providerWaitMs: 2_000,
+ modelStreamDurationMs: 3_000,
+ });
+ await runtime.dispose();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it.each(fallbackDurations)(
"falls back to the sidecar stopwatch for a $label Pi duration",
async ({ durationMs }) => {
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index 838403b60..c1b02e77f 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -7796,6 +7796,15 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
this.progressTurnRerunInProgress
? this.currentAssistant
: undefined;
+ const requestWaitMs =
+ this.requestStartedAt !== undefined
+ ? Math.max(0, Date.now() - this.requestStartedAt)
+ : undefined;
+ const cumulativeProviderWaitMs =
+ requestWaitMs !== undefined ||
+ retryingAssistant?.providerWaitMs !== undefined
+ ? (retryingAssistant?.providerWaitMs ?? 0) + (requestWaitMs ?? 0)
+ : undefined;
const initialText =
content.hasText && content.text.length > 0
? content.text
@@ -7813,6 +7822,12 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
status: "streaming",
modelId: this.provider.modelId,
providerId: this.provider.id,
+ ...(retryingAssistant?.modelStreamDurationMs !== undefined
+ ? { modelStreamDurationMs: retryingAssistant.modelStreamDurationMs }
+ : {}),
+ ...(cumulativeProviderWaitMs !== undefined
+ ? { providerWaitMs: cumulativeProviderWaitMs }
+ : {}),
};
if (retryingAssistant) {
// Keep one visible assistant bubble across the bounded retry. The
@@ -7986,6 +8001,9 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
this.streamStartedAt !== undefined
? Math.max(0, endedAt - this.streamStartedAt)
: undefined;
+ const modelStreamDurationMs =
+ (this.currentAssistant.modelStreamDurationMs ?? 0) +
+ (streamMs ?? 0);
if (classifiedError) {
classifiedError = this.providerErrorWithDiagnostics(
classifiedError,
@@ -8033,6 +8051,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
status: "streaming",
modelId: this.provider.modelId,
providerId: this.provider.id,
+ ...(streamMs !== undefined ? { modelStreamDurationMs } : {}),
...(usage ? { usage } : {}),
};
this.emit({ type: "message_update", message: this.currentAssistant });
@@ -8080,6 +8099,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
status: "streaming",
modelId: this.provider.modelId,
providerId: this.provider.id,
+ ...(streamMs !== undefined ? { modelStreamDurationMs } : {}),
...(usage ? { usage } : {}),
};
this.emit({ type: "message_update", message: this.currentAssistant });
@@ -8105,6 +8125,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
status: "streaming",
modelId: this.provider.modelId,
providerId: this.provider.id,
+ ...(streamMs !== undefined ? { modelStreamDurationMs } : {}),
...(usage ? { usage } : {}),
};
this.emit({ type: "message_update", message: this.currentAssistant });
@@ -8138,6 +8159,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
status: "streaming",
modelId: this.provider.modelId,
providerId: this.provider.id,
+ ...(streamMs !== undefined ? { modelStreamDurationMs } : {}),
...(usage ? { usage } : {}),
};
this.emit({ type: "message_update", message: this.currentAssistant });
@@ -8179,6 +8201,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
providerId: this.provider.id,
...(usage ? { usage } : {}),
...(responseDurationMs !== undefined ? { responseDurationMs } : {}),
+ ...(streamMs !== undefined ? { modelStreamDurationMs } : {}),
...(responseOutputTokens !== undefined
? { responseOutputTokens }
: {}),
@@ -8395,6 +8418,9 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
this.streamStartedAt !== undefined
? Math.max(0, Date.now() - this.streamStartedAt)
: undefined;
+ const modelStreamDurationMs =
+ (this.currentAssistant.modelStreamDurationMs ?? 0) +
+ (responseDurationMs ?? 0);
const responseOutputTokens =
status === "aborted"
? estimateVisibleResponseOutputTokens(this.currentAssistant)
@@ -8403,6 +8429,9 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
...this.currentAssistant,
status,
...(responseDurationMs !== undefined ? { responseDurationMs } : {}),
+ ...(responseDurationMs !== undefined
+ ? { modelStreamDurationMs }
+ : {}),
...(responseOutputTokens !== undefined
? { responseOutputTokens }
: {}),
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index 6892caeab..e4e2682c6 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -382,7 +382,12 @@ export const de = {
"usageThroughputEstimated": "≈ {{count}} Tokens/s",
"usageThroughputUnavailable": "–",
"usageSessionTime": "Gesamtdauer der Sitzung",
+ "usageNetworkRequest": "Netzwerkanfrage",
+ "usageNetworkRequestHelp": "Zeit vom Senden der Modellanfrage bis zum ersten Antwortereignis, einschließlich Netzwerk- und Anbieterwartezeit. Ältere Nachrichten ohne separate Zeitmessung sind nicht enthalten.",
"usageModelResponse": "Modellantwortzeit",
+ "usageModelResponseHelp": "Zeit für das Streamen von Denkprozess und Antwort. Bei älteren Nachrichten kann die Anfragewartezeit enthalten sein.",
+ "usageToolCalls": "Werkzeugaufrufzeit",
+ "usageToolCallsHelp": "Zeit der Aufrufe auf oberster Ebene; Überschneidungen paralleler Aufrufe zählen einmal.",
"usageTimingUnavailable": "Nicht verfügbar",
"usageProviderUsage": "Anbieternutzung",
"usageInput": "Eingabe",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index 5d0f49987..a71fdba3f 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -397,7 +397,12 @@ export const en = {
usageThroughputEstimated: "≈ {{count}} tokens/s",
usageThroughputUnavailable: "—",
usageSessionTime: "Total session time",
+ usageNetworkRequest: "Network request",
+ usageNetworkRequestHelp: "Time from sending a model request to its first response event; includes network and provider-side waiting. Older messages without separate timing are not included.",
usageModelResponse: "Model response time",
+ usageModelResponseHelp: "Time spent streaming both thinking and reply content. Older messages may include request wait.",
+ usageToolCalls: "Tool call time",
+ usageToolCallsHelp: "Top-level tool execution time; overlapping calls count once.",
usageTimingUnavailable: "Unavailable",
usageProviderUsage: "Provider usage",
usageInput: "Input",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index 27c6bfcf9..d98ca6fb8 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -382,7 +382,12 @@ export const es = {
"usageThroughputEstimated": "≈ {{count}} tokens/s",
"usageThroughputUnavailable": "—",
"usageSessionTime": "Tiempo total de sesión",
+ "usageNetworkRequest": "Solicitud de red",
+ "usageNetworkRequestHelp": "Tiempo desde que se envía la solicitud al modelo hasta el primer evento de respuesta; incluye la espera de red y del proveedor. No incluye mensajes antiguos sin tiempos separados.",
"usageModelResponse": "Tiempo de respuesta del modelo",
+ "usageModelResponseHelp": "Tiempo de transmisión del razonamiento y la respuesta. Los mensajes antiguos pueden incluir la espera de la solicitud.",
+ "usageToolCalls": "Tiempo de llamadas a herramientas",
+ "usageToolCallsHelp": "Tiempo de ejecución de herramientas de nivel superior; las llamadas simultáneas solo cuentan una vez durante el solapamiento.",
"usageTimingUnavailable": "No disponible",
"usageProviderUsage": "Uso del proveedor",
"usageInput": "Entrada",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index 1eccc83db..ff94f9e34 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -382,7 +382,12 @@ export const fr = {
"usageThroughputEstimated": "≈ {{count}} jetons/s",
"usageThroughputUnavailable": "—",
"usageSessionTime": "Durée totale de la session",
+ "usageNetworkRequest": "Requête réseau",
+ "usageNetworkRequestHelp": "Temps entre l’envoi de la requête au modèle et le premier événement de réponse, incluant l’attente réseau et côté fournisseur. Les anciens messages sans mesure distincte sont exclus.",
"usageModelResponse": "Temps de réponse du modèle",
+ "usageModelResponseHelp": "Temps de génération en flux du raisonnement et de la réponse. Les anciens messages peuvent inclure l’attente de la requête.",
+ "usageToolCalls": "Temps des appels d’outils",
+ "usageToolCallsHelp": "Temps d’exécution des outils de premier niveau ; les chevauchements entre appels parallèles ne sont comptés qu’une fois.",
"usageTimingUnavailable": "Indisponible",
"usageProviderUsage": "Utilisation du fournisseur",
"usageInput": "Entrée",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index 0381cda6b..944b39e46 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -394,7 +394,12 @@ export const ko = {
usageThroughputEstimated: "≈ {{count}} tokens/s",
usageThroughputUnavailable: "—",
usageSessionTime: "총 세션 시간",
+ usageNetworkRequest: "네트워크 요청 시간",
+ usageNetworkRequestHelp: "모델 요청을 보낸 시점부터 첫 응답 이벤트까지의 시간이며, 네트워크 및 제공자 대기 시간을 포함합니다. 별도 시간 정보가 없는 이전 메시지는 포함하지 않습니다.",
usageModelResponse: "모델 응답 시간",
+ usageModelResponseHelp: "모델의 추론과 답변이 스트리밍된 시간입니다. 이전 메시지는 요청 대기 시간을 포함할 수 있습니다.",
+ usageToolCalls: "도구 호출 시간",
+ usageToolCallsHelp: "최상위 도구 실행 시간입니다. 병렬 호출이 겹친 구간은 한 번만 계산합니다.",
usageTimingUnavailable: "사용할 수 없음",
usageProviderUsage: "프로바이더 사용량",
usageInput: "입력",
diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.ts
index da771c4b1..17ec40237 100644
--- a/packages/i18n/src/locales/pt-BR/index.ts
+++ b/packages/i18n/src/locales/pt-BR/index.ts
@@ -384,7 +384,12 @@ export const ptBR = {
usageThroughputEstimated: "≈ {{count}} tokens/s",
usageThroughputUnavailable: "—",
usageSessionTime: "Tempo total da sessão",
+ usageNetworkRequest: "Solicitação de rede",
+ usageNetworkRequestHelp: "Tempo entre o envio da solicitação ao modelo e o primeiro evento de resposta, incluindo a espera da rede e do provedor. Mensagens antigas sem tempos separados não são incluídas.",
usageModelResponse: "Tempo de resposta do modelo",
+ usageModelResponseHelp: "Tempo de transmissão do raciocínio e da resposta. Mensagens antigas podem incluir a espera da solicitação.",
+ usageToolCalls: "Tempo de chamadas de ferramentas",
+ usageToolCallsHelp: "Tempo de execução de ferramentas de nível superior; sobreposições entre chamadas paralelas contam uma vez.",
usageTimingUnavailable: "Indisponível",
usageProviderUsage: "Uso do provedor",
usageInput: "Entrada",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index 65d6146bd..6f719b9bb 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -394,7 +394,12 @@ export const tr = {
usageThroughputEstimated: "≈ {{count}} token/sn",
usageThroughputUnavailable: "—",
usageSessionTime: "Toplam oturum süresi",
+ usageNetworkRequest: "Ağ isteği süresi",
+ usageNetworkRequestHelp: "Model isteğinin gönderilmesiyle ilk yanıt olayı arasındaki süre; ağ ve sağlayıcı beklemesini içerir. Ayrı zaman bilgisi olmayan eski mesajlar dahil edilmez.",
usageModelResponse: "Model yanıt süresi",
+ usageModelResponseHelp: "Modelin düşünce ve yanıt içeriğini akışla üretme süresi. Eski mesajlarda istek bekleme süresi yer alabilir.",
+ usageToolCalls: "Araç çağrısı süresi",
+ usageToolCallsHelp: "Üst düzey araçların çalışma süresi; paralel çağrıların çakışan bölümü bir kez sayılır.",
usageTimingUnavailable: "Kullanılamıyor",
usageProviderUsage: "Servis kullanımı",
usageInput: "Girdi",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index 91d3e7817..f6de34730 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -387,7 +387,12 @@ export const zhCN = {
usageThroughputEstimated: "约 {{count}} tokens/s",
usageThroughputUnavailable: "—",
usageSessionTime: "会话总耗时",
+ usageNetworkRequest: "网络请求耗时",
+ usageNetworkRequestHelp: "从发出模型请求到收到首个响应事件的耗时,包含网络传输和服务端首响应等待;旧消息没有单独计时数据时不会计入。",
usageModelResponse: "模型响应耗时",
+ usageModelResponseHelp: "模型输出思考内容与回复内容的流式耗时;旧消息的计时可能包含请求等待。",
+ usageToolCalls: "工具调用耗时",
+ usageToolCallsHelp: "统计顶层工具调用时长;并行调用的重叠部分只计算一次。",
usageTimingUnavailable: "暂不可用",
usageProviderUsage: "模型用量",
usageInput: "输入",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index 9f1a16b1f..e37f8337a 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -387,7 +387,12 @@ export const zhTW = {
usageThroughputEstimated: "約 {{count}} tokens/s",
usageThroughputUnavailable: "—",
usageSessionTime: "工作階段總耗時",
+ usageNetworkRequest: "網路請求耗時",
+ usageNetworkRequestHelp: "從送出模型請求到收到第一個回應事件的時間,包含網路傳輸與服務端首次回應等待;舊訊息沒有獨立計時資料時不會列入。",
usageModelResponse: "模型回應耗時",
+ usageModelResponseHelp: "模型串流輸出思考內容與回覆內容所花的時間;舊訊息的計時可能包含請求等待。",
+ usageToolCalls: "工具呼叫耗時",
+ usageToolCallsHelp: "統計頂層工具呼叫時間;平行呼叫的重疊部分只計算一次。",
usageTimingUnavailable: "暫時無法使用",
usageProviderUsage: "模型用量",
usageInput: "輸入",
diff --git a/packages/shared/src/types/messages.ts b/packages/shared/src/types/messages.ts
index 683cf8d62..c12fe1a0c 100644
--- a/packages/shared/src/types/messages.ts
+++ b/packages/shared/src/types/messages.ts
@@ -1,7 +1,7 @@
-import type { PlanHistoryEntry } from "./plans.js";
+import type { AppError } from "../errors.js";
/** Shared public types grouped by the owning application domain. */
import type { SessionMessageOrigin } from "../session-collaboration.js";
-import type { AppError } from "../errors.js";
+import type { PlanHistoryEntry } from "./plans.js";
export type UiMessageRole = "user" | "assistant" | "system" | "tool";
@@ -117,8 +117,12 @@ export type UiMessage = {
providerId?: string;
/** Token usage for the assistant turn, when the provider reported it. */
usage?: MessageUsage;
- /** Elapsed model streaming time used to calculate output throughput. */
+ /** Elapsed assistant response duration used to calculate output throughput. */
responseDurationMs?: number;
+ /** Client-observed wait from issuing the model request to its first response event. */
+ providerWaitMs?: number;
+ /** Time spent streaming the model's thinking and answer after the first response event. */
+ modelStreamDurationMs?: number;
/** Output tokens used only for throughput when a stopped stream has no final usage. */
responseOutputTokens?: number;
/** Structured failure attached to the assistant turn that failed. */