Commit 0cac1220e for llama.cpp
commit 0cac1220e35a25fcfbe58e115ee2282a2de76142
Author: Aleksander Grygier <aleksander.grygier@gmail.com>
Date: Wed Nov 25 13:16:19 2026 +0100
ui: time each tool group by its own loop and show the task time in the reply stats (#33030)
The tool call group's timer now times its own loop of calls, from its first
call's start to its last call's end, ticking while it runs and kept once the
reply is done. The harness records each call's id and wall-clock start and
end with its timing for this.
The reply's statistics show the whole task time next to the generation
stats, ticking while an agentic reply runs.
Assisted-by: Claude (Opus 5.5 Medium)
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistantStatistics.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistantStatistics.svelte
index ba748f947..1f6fa8089 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistantStatistics.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistantStatistics.svelte
@@ -30,6 +30,7 @@
predictedTokens={liveLlm.predicted_n}
promptMs={liveLlm.prompt_ms}
promptTokens={liveLlm.prompt_n}
+ taskStartedAt={agenticStore.getStartedAt(message.convId)}
/>
{:else if showMessageStats && message.timings?.compaction}
{@const summary = message.timings.compaction}
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallGroup.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallGroup.svelte
index cc2154879..ebc3460cd 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallGroup.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallGroup.svelte
@@ -20,8 +20,10 @@
open: boolean;
isStreaming: boolean;
executingToolCallId?: string | null;
- /** Task start (ms since epoch) for the live timer, or null for none. */
+ /** Start of the group's loop (ms since epoch), or null for no timer. */
elapsedStartedAt?: number | null;
+ /** End of the group's loop (ms since epoch), or null while it runs. */
+ elapsedEndedAt?: number | null;
/**
* What the server is doing while the reply waits on it ( "Processing 40%",
* "Loading weights" ), shown as the live title when this is the last row.
@@ -33,6 +35,7 @@
let {
children,
+ elapsedEndedAt = null,
elapsedStartedAt = null,
executingToolCallId,
isStreaming,
@@ -67,7 +70,7 @@
{#snippet trailing()}
{#if elapsedStartedAt !== null}
- <ToolCallElapsed startedAt={elapsedStartedAt} />
+ <ToolCallElapsed endedAt={elapsedEndedAt} startedAt={elapsedStartedAt} />
{/if}
{/snippet}
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallElapsed.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallElapsed.svelte
index 9174148ac..b71ea5a03 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallElapsed.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallElapsed.svelte
@@ -1,36 +1,30 @@
<script lang="ts">
- // Time since the task started, ticking once a second.
+ // Time a loop of tool calls took, or since it started while it runs.
- import { MS_PER_SECOND, SECONDS_PER_MINUTE } from '#lib/constants/index.ts';
- import { formatPerformanceTime } from '#lib/utils/index.ts';
+ import { useNow } from '#lib/hooks/use-now.svelte.ts';
+ import { formatElapsedTime, formatPerformanceTime } from '#lib/utils/index.ts';
interface Props {
- /** Task start (ms since epoch). */
+ /** Loop start (ms since epoch). */
startedAt: number;
+ /** Loop end (ms since epoch), or null while it runs. */
+ endedAt?: number | null;
}
- let { startedAt }: Props = $props();
+ let { endedAt = null, startedAt }: Props = $props();
- let now = $state(Date.now());
+ const now = useNow(() => endedAt === null);
- $effect(() => {
- const timer = setInterval(() => (now = Date.now()), MS_PER_SECOND);
-
- return () => clearInterval(timer);
- });
-
- const elapsedMs = $derived(Math.max(0, now - startedAt));
- // whole seconds while short, so the label does not flicker every tick
const label = $derived(
- elapsedMs < SECONDS_PER_MINUTE * MS_PER_SECOND
- ? `${Math.floor(elapsedMs / MS_PER_SECOND)}s`
- : formatPerformanceTime(elapsedMs)
+ endedAt === null
+ ? formatElapsedTime(now.current - startedAt)
+ : formatPerformanceTime(endedAt - startedAt)
);
</script>
<span
class="text-body-sm font-normal text-muted-foreground tabular-nums"
- title="Time since the task started"
+ title={endedAt === null ? 'Time since the loop started' : 'Time the loop took'}
>
{label}
</span>
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/tool-call-elapsed.ts b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/tool-call-elapsed.ts
index 89a5fd2eb..9e7f11c6a 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/tool-call-elapsed.ts
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/tool-call-elapsed.ts
@@ -1,4 +1,4 @@
-// The live task timer sits at the end of the last tool row while a reply runs.
+// The live loop timer sits at the end of the last tool row while a reply runs.
// The trace sets it once, naming that row's call, so the per-tool blocks need
// no extra prop.
@@ -6,7 +6,7 @@ import { getContext, setContext } from 'svelte';
const KEY = Symbol('tool-call-elapsed');
-/** The call that shows the timer and the task start (ms since epoch), or null for no timer. */
+/** The call that shows the timer and its start (ms since epoch), or null for no timer. */
type ElapsedTarget = { startedAt: number; toolCallId: string } | null;
export function setToolCallElapsedContext(getTarget: () => ElapsedTarget): void {
@@ -14,7 +14,7 @@ export function setToolCallElapsedContext(getTarget: () => ElapsedTarget): void
}
/**
- * Call during component init. Returns a reader of the task start for a call:
+ * Call during component init. Returns a reader of the timer start for a call:
* its start when that call shows the timer, null otherwise.
*/
export function useToolCallElapsed(): (toolCallId: string | undefined) => number | null {
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte
index 988cb11d9..6ccb6f09b 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte
@@ -187,16 +187,52 @@
const lastItem = $derived(turns.at(-1)?.at(-1));
- // The live task timer goes on the last row while it is a tool row: a group
- // takes it as a prop, a single call reads it from context by its id.
- const taskStartedAt = $derived(isStreaming ? agenticStore.getStartedAt(message.convId) : null);
+ // Each tool row times its own loop of calls, from its first call's start
+ // to its last call's end; the run stamps those times on the root message's
+ // timings, and a call still running reads its start from the live session.
+ const callTimings = $derived(
+ new Map(
+ (message?.timings?.agentic?.toolCalls ?? []).flatMap((timing) =>
+ timing.id ? [[timing.id, timing] as const] : []
+ )
+ )
+ );
+
+ function callStartedAt(toolCallId: string | undefined): number | null {
+ if (!toolCallId) return null;
+
+ return (
+ callTimings.get(toolCallId)?.startedAt ??
+ (isStreaming ? agenticStore.getToolCallStartedAt(message.convId, toolCallId) : null)
+ );
+ }
+
+ /** The loop of a group: its start, and its end once done ( null while it runs ). */
+ function loopTiming(item: number[]): { startedAt: number; endedAt: number | null } | null {
+ // a group can open with the reasoning that led to its first call
+ const ids = item.flatMap((index) => sections[index]?.toolCallId ?? []);
+ const startedAt = callStartedAt(ids[0]);
+
+ if (startedAt === null) return null;
+
+ // the last row of a live reply is the loop still running
+ if (isStreaming && item === lastItem) return { endedAt: null, startedAt };
+
+ const ends = ids.map((id) => callTimings.get(id)?.endedAt);
+
+ return ends.every((end) => end !== undefined)
+ ? { endedAt: Math.max(...(ends as number[])), startedAt }
+ : null;
+ }
+ // a single call closing a live reply reads its timer from context by its id
setToolCallElapsedContext(() => {
- if (taskStartedAt === null || lastItem === undefined || Array.isArray(lastItem)) return null;
+ if (!isStreaming || lastItem === undefined || Array.isArray(lastItem)) return null;
const toolCallId = sections[lastItem]?.toolCallId;
+ const startedAt = callStartedAt(toolCallId);
- return toolCallId ? { startedAt: taskStartedAt, toolCallId } : null;
+ return toolCallId && startedAt !== null ? { startedAt, toolCallId } : null;
});
const lastToolIndex = $derived(sections.findLastIndex((section) => isToolCallStep(section)));
@@ -300,8 +336,10 @@
{#snippet renderItem(item: TraceItem)}
{#if Array.isArray(item)}
{@const groupOpen = isGroupExpanded(item)}
+ {@const loop = loopTiming(item)}
<ChatMessageToolCallGroup
- elapsedStartedAt={item === lastItem ? taskStartedAt : null}
+ elapsedEndedAt={loop?.endedAt ?? null}
+ elapsedStartedAt={loop?.startedAt ?? null}
executingToolCallId={currentlyExecutingToolCallId}
{isStreaming}
onToggle={() => toggleGroupExpanded(item)}
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageStatistics/ChatMessageStatistics.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageStatistics/ChatMessageStatistics.svelte
index 2dba6679e..b3e5764fb 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageStatistics/ChatMessageStatistics.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageStatistics/ChatMessageStatistics.svelte
@@ -13,8 +13,9 @@
import { ChatMessageStatisticsBadge } from '#lib/components/app/index.ts';
import { DEFAULT_PERFORMANCE_TIME, MS_PER_SECOND } from '#lib/constants/index.ts';
import { ChatMessageStatisticsMode, ChatMessageStatsView } from '#lib/enums/index.ts';
+ import { useNow } from '#lib/hooks/use-now.svelte.ts';
import type { ChatMessageAgenticTimings } from '#lib/types/chat.js';
- import { formatPerformanceTime } from '#lib/utils/index.ts';
+ import { formatElapsedTime, formatPerformanceTime } from '#lib/utils/index.ts';
import type { Component } from 'svelte';
interface Props {
@@ -29,6 +30,8 @@
onActiveViewChange?: (view: ChatMessageStatsView) => void;
hideSummary?: boolean;
mode?: ChatMessageStatisticsMode;
+ /** Start of a running task (ms since epoch): the task time ticks from it. */
+ taskStartedAt?: number | null;
}
let {
@@ -42,7 +45,8 @@
predictedMs,
predictedTokens,
promptMs,
- promptTokens
+ promptTokens,
+ taskStartedAt = null
}: Props = $props();
let isSwitchable = $derived(mode === ChatMessageStatisticsMode.SWITCHABLE);
@@ -139,6 +143,17 @@
let formattedAgenticTotalTime = $derived(formatPerformanceTime(agenticTotalTimeMs));
+ const now = useNow(() => taskStartedAt !== null);
+
+ // the whole reply, from the prompt to the answer: live while it runs, then as recorded
+ let formattedTaskTime = $derived(
+ taskStartedAt !== null
+ ? formatElapsedTime(now.current - taskStartedAt)
+ : agenticTimings?.totalMs !== undefined
+ ? formatPerformanceTime(agenticTimings.totalMs)
+ : undefined
+ );
+
const fixedFormatter = new Intl.NumberFormat(undefined, {
maximumFractionDigits: 2,
minimumFractionDigits: 2
@@ -240,12 +255,12 @@
value={formattedTime}
/>
- {#if hasAgenticStats && agenticTimings!.totalMs !== undefined}
+ {#if formattedTaskTime !== undefined}
<ChatMessageStatisticsBadge
class="bg-transparent"
icon={Hourglass}
tooltipLabel="Total task time, from the prompt to the answer"
- value={formattedAgenticTotalTime}
+ value={formattedTaskTime}
/>
{/if}
diff --git a/ui/apps/chat/src/lib/hooks/use-now.svelte.ts b/ui/apps/chat/src/lib/hooks/use-now.svelte.ts
new file mode 100644
index 000000000..e5345803c
--- /dev/null
+++ b/ui/apps/chat/src/lib/hooks/use-now.svelte.ts
@@ -0,0 +1,25 @@
+import { MS_PER_SECOND } from '#lib/constants/index.ts';
+
+/**
+ * The current time (ms since epoch), ticking once a second while `isTicking`
+ * returns true. Call during component init.
+ */
+export function useNow(isTicking: () => boolean = () => true): { readonly current: number } {
+ let now = $state(Date.now());
+
+ $effect(() => {
+ if (!isTicking()) return;
+
+ now = Date.now();
+
+ const timer = setInterval(() => (now = Date.now()), MS_PER_SECOND);
+
+ return () => clearInterval(timer);
+ });
+
+ return {
+ get current() {
+ return now;
+ }
+ };
+}
diff --git a/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts b/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts
index 602d49bfb..61b40ac1a 100644
--- a/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts
+++ b/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts
@@ -99,6 +99,7 @@ function createDefaultSession(): AgenticSession {
pendingPermissionRequest: null,
startedAt: null,
streamingToolCall: null,
+ toolCallStartedAt: {},
totalToolCalls: 0
};
}
@@ -287,6 +288,11 @@ class AgenticStore {
return this.sessions.get(conversationId)?.streamingToolCall ?? null;
}
+ /** When a call of the running flow started (ms since epoch), or null when it has not. */
+ getToolCallStartedAt(conversationId: string, toolCallId: string): number | null {
+ return this.sessions.get(conversationId)?.toolCallStartedAt[toolCallId] ?? null;
+ }
+
getTotalToolCalls(conversationId: string): number {
return this.sessions.get(conversationId)?.totalToolCalls ?? 0;
}
@@ -374,6 +380,7 @@ class AgenticStore {
lastError: null,
liveLlm: null,
startedAt: Date.now(),
+ toolCallStartedAt: {},
totalToolCalls: 0
});
@@ -403,7 +410,8 @@ class AgenticStore {
flowRootMessageId: null,
isRunning: false,
liveLlm: null,
- startedAt: null
+ startedAt: null,
+ toolCallStartedAt: {}
});
if (hasMcpServers) {
@@ -696,6 +704,16 @@ class AgenticStore {
break;
+ case HarnessEventType.TOOL_CALL: {
+ const started = this.sessions.get(conversationId)?.toolCallStartedAt ?? {};
+
+ this.updateSession(conversationId, {
+ toolCallStartedAt: { ...started, [event.toolCall.id]: Date.now() }
+ });
+
+ break;
+ }
+
case HarnessEventType.TOOL_UPDATE: {
if (!createToolResultMessage || !updateToolResultMessage) break;
diff --git a/ui/apps/chat/src/lib/types/agentic.d.ts b/ui/apps/chat/src/lib/types/agentic.d.ts
index 709b8f40e..faf4ce701 100644
--- a/ui/apps/chat/src/lib/types/agentic.d.ts
+++ b/ui/apps/chat/src/lib/types/agentic.d.ts
@@ -101,6 +101,8 @@ export interface AgenticSession {
flowRootMessageId: string | null;
/** When the running flow started (ms since epoch); null when idle. */
startedAt: number | null;
+ /** When each call of the running flow started (ms since epoch), by tool call id. */
+ toolCallStartedAt: Record<string, number>;
}
/**
diff --git a/ui/apps/chat/src/lib/types/chat.d.ts b/ui/apps/chat/src/lib/types/chat.d.ts
index ab6fe352a..659edf101 100644
--- a/ui/apps/chat/src/lib/types/chat.d.ts
+++ b/ui/apps/chat/src/lib/types/chat.d.ts
@@ -139,9 +139,14 @@ export interface ChatMessageAgenticTurnStats {
}
export interface ChatMessageToolCallTiming {
+ /** The call's id; older messages lack it and the wall-clock times. */
+ id?: string;
name: string;
duration_ms: number;
success: boolean;
+ /** Wall-clock start and end (ms since epoch), waits for approval included. */
+ startedAt?: number;
+ endedAt?: number;
}
/**
diff --git a/ui/apps/chat/src/lib/utils/formatters.ts b/ui/apps/chat/src/lib/utils/formatters.ts
index 866c0a792..2b8e98290 100644
--- a/ui/apps/chat/src/lib/utils/formatters.ts
+++ b/ui/apps/chat/src/lib/utils/formatters.ts
@@ -176,6 +176,18 @@ export function formatPerformanceTime(ms: number): string {
return parts.join(' ');
}
+/**
+ * A running time that ticks once a second: whole seconds under a minute, so
+ * the label does not flicker every tick, then as formatPerformanceTime.
+ */
+export function formatElapsedTime(ms: number): string {
+ const elapsedMs = Math.max(0, ms);
+
+ return elapsedMs < SECONDS_PER_MINUTE * MS_PER_SECOND
+ ? `${Math.floor(elapsedMs / MS_PER_SECOND)}s`
+ : formatPerformanceTime(elapsedMs);
+}
+
/**
* Formats attachment content for API requests with consistent header style.
* Used when converting message attachments to text content parts.
diff --git a/ui/apps/chat/src/lib/utils/index.ts b/ui/apps/chat/src/lib/utils/index.ts
index 915b9d671..44b78e205 100644
--- a/ui/apps/chat/src/lib/utils/index.ts
+++ b/ui/apps/chat/src/lib/utils/index.ts
@@ -112,6 +112,7 @@ export {
formatJsonPretty,
formatTime,
formatLocalIso,
+ formatElapsedTime,
formatPerformanceTime,
formatRelativeTime,
formatAttachmentText
diff --git a/ui/apps/chat/tests/client/components/ChatMessageStatisticsTestWrapper.svelte b/ui/apps/chat/tests/client/components/ChatMessageStatisticsTestWrapper.svelte
new file mode 100644
index 000000000..1bc62eb5a
--- /dev/null
+++ b/ui/apps/chat/tests/client/components/ChatMessageStatisticsTestWrapper.svelte
@@ -0,0 +1,11 @@
+<script lang="ts">
+ import * as Tooltip from '@ggml-org/llama-ui/ui/tooltip';
+ import ChatMessageStatistics from '#lib/components/app/chat/ChatMessages/ChatMessageStatistics/ChatMessageStatistics.svelte';
+ import type { ComponentProps } from 'svelte';
+
+ let props: ComponentProps<typeof ChatMessageStatistics> = $props();
+</script>
+
+<Tooltip.Provider>
+ <ChatMessageStatistics {...props} />
+</Tooltip.Provider>
diff --git a/ui/apps/chat/tests/client/loop-timer.svelte.test.ts b/ui/apps/chat/tests/client/loop-timer.svelte.test.ts
new file mode 100644
index 000000000..284c28c8f
--- /dev/null
+++ b/ui/apps/chat/tests/client/loop-timer.svelte.test.ts
@@ -0,0 +1,154 @@
+// Guards the loop timer: a tool row times its own loop of calls, not the whole
+// task. While a reply runs, the last tool row ticks from its first call's start
+// ( a single call reads it from context by its id, a group takes it as a prop );
+// once done, a group shows the time from its first call's start to its last
+// call's end, as the run recorded them.
+
+import ChatMessageAgentTrace from '#lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte';
+import { MessageRole, MessageType } from '#lib/enums/index.ts';
+import { agenticStore } from '#lib/stores/index.ts';
+import type { ChatMessageTimings, DatabaseMessage } from '#lib/types/index.ts';
+import { tick } from 'svelte';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { render } from 'vitest-browser-svelte';
+
+const CONV_ID = 'conv-timer';
+const LIVE_TIMER = '[title="Time since the loop started"]';
+const DONE_TIMER = '[title="Time the loop took"]';
+
+type SessionPatch = { toolCallStartedAt: Record<string, number> };
+type WithSession = { updateSession(conversationId: string, patch: SessionPatch): void };
+
+function reply(
+ calls: number,
+ timings?: ChatMessageTimings,
+ reasoningContent?: string
+): DatabaseMessage {
+ return {
+ children: [],
+ content: '',
+ convId: CONV_ID,
+ id: 'assistant-1',
+ parent: null,
+ reasoningContent,
+ role: MessageRole.ASSISTANT,
+ timestamp: 0,
+ timings,
+ toolCalls: JSON.stringify(
+ Array.from({ length: calls }, (_, i) => ({
+ function: { arguments: `{"path":"file-${i}.ts"}`, name: 'read_file' },
+ id: `call-${i}`
+ }))
+ ),
+ type: MessageType.TEXT
+ };
+}
+
+/** Run timings where call i ran from `spans[i][0]` to `spans[i][1]` (ms since epoch). */
+function timingsOf(spans: [number, number][]): ChatMessageTimings {
+ const llm = { predicted_ms: 0, predicted_n: 0, prompt_ms: 0, prompt_n: 0 };
+
+ return {
+ agentic: {
+ llm,
+ toolCalls: spans.map(([startedAt, endedAt], i) => ({
+ duration_ms: endedAt - startedAt,
+ endedAt,
+ id: `call-${i}`,
+ name: 'read_file',
+ startedAt,
+ success: true
+ })),
+ toolCallsCount: spans.length,
+ toolsMs: 0,
+ turns: 1
+ }
+ };
+}
+
+function setCallStarts(toolCallStartedAt: Record<string, number>) {
+ // the loop sets these as calls start; there is no public setter
+ (agenticStore as unknown as WithSession).updateSession(CONV_ID, { toolCallStartedAt });
+}
+
+describe('loop timer', () => {
+ beforeEach(() => setCallStarts({ 'call-0': Date.now() - 5000 }));
+ afterEach(() => setCallStarts({}));
+
+ it('ticks on a single running call', async () => {
+ const { container } = render(ChatMessageAgentTrace, {
+ isLastAssistantMessage: true,
+ isStreaming: true,
+ message: reply(1)
+ });
+
+ await tick();
+
+ expect(container.querySelectorAll(LIVE_TIMER)).toHaveLength(1);
+ expect(container.querySelector(LIVE_TIMER)?.textContent?.trim()).toMatch(/^\d+s$/);
+ });
+
+ it('ticks once on a running group, not on the calls inside it', async () => {
+ const { container } = render(ChatMessageAgentTrace, {
+ isLastAssistantMessage: true,
+ isStreaming: true,
+ message: reply(2)
+ });
+
+ await tick();
+
+ expect(container.querySelectorAll(LIVE_TIMER)).toHaveLength(1);
+ expect(container.querySelector('.tool-call-group')?.querySelector(LIVE_TIMER)).not.toBeNull();
+ });
+
+ it('shows the time a finished group took, from its first call to its last', async () => {
+ const { container } = render(ChatMessageAgentTrace, {
+ isLastAssistantMessage: true,
+ isStreaming: false,
+ message: reply(
+ 2,
+ timingsOf([
+ [1000, 2000],
+ [2500, 4500]
+ ])
+ )
+ });
+
+ await tick();
+
+ expect(container.querySelectorAll(LIVE_TIMER)).toHaveLength(0);
+ expect(container.querySelector(DONE_TIMER)?.textContent?.trim()).toBe('3.5s');
+ });
+
+ it('times a group that opens with the reasoning before its first call', async () => {
+ const { container } = render(ChatMessageAgentTrace, {
+ isLastAssistantMessage: true,
+ isStreaming: false,
+ message: reply(
+ 2,
+ timingsOf([
+ [1000, 2000],
+ [2500, 4500]
+ ]),
+ 'I should read both files.'
+ )
+ });
+
+ await tick();
+
+ expect(container.querySelector('.tool-call-group')?.querySelector(DONE_TIMER)).not.toBeNull();
+ expect(container.querySelector(DONE_TIMER)?.textContent?.trim()).toBe('3.5s');
+ });
+
+ it('shows nothing on a finished reply without call times', async () => {
+ const { container } = render(ChatMessageAgentTrace, {
+ isLastAssistantMessage: true,
+ isStreaming: false,
+ message: reply(2)
+ });
+
+ await tick();
+
+ expect(container.querySelectorAll(`${LIVE_TIMER}, ${DONE_TIMER}`)).toHaveLength(0);
+ });
+});
diff --git a/ui/apps/chat/tests/client/task-time-statistics.svelte.test.ts b/ui/apps/chat/tests/client/task-time-statistics.svelte.test.ts
new file mode 100644
index 000000000..1a1d2f35c
--- /dev/null
+++ b/ui/apps/chat/tests/client/task-time-statistics.svelte.test.ts
@@ -0,0 +1,58 @@
+// Guards the task time in a reply's statistics: the whole reply, from the
+// prompt to the answer, ticking while it runs and as recorded once done.
+
+import ChatMessageStatistics from './components/ChatMessageStatisticsTestWrapper.svelte';
+import { ChatMessageStatisticsMode } from '#lib/enums/index.ts';
+import type { ChatMessageAgenticTimings } from '#lib/types/index.ts';
+import { tick } from 'svelte';
+import { describe, expect, it } from 'vitest';
+import { render } from 'vitest-browser-svelte';
+
+const GENERATION = {
+ mode: ChatMessageStatisticsMode.GENERATION,
+ predictedMs: 2000,
+ predictedTokens: 100
+};
+const LLM = { predicted_ms: 2000, predicted_n: 100, prompt_ms: 500, prompt_n: 50 };
+
+function agentic(totalMs?: number): ChatMessageAgenticTimings {
+ return { llm: LLM, toolCallsCount: 1, toolsMs: 300, totalMs, turns: 2 };
+}
+
+describe('task time statistics', () => {
+ it('ticks from the task start while the reply runs', async () => {
+ const { container } = render(ChatMessageStatistics, {
+ ...GENERATION,
+ isLive: true,
+ taskStartedAt: Date.now() - 5000
+ });
+
+ await tick();
+
+ expect(container.textContent).toMatch(/\b5s\b/);
+ });
+
+ it('shows the recorded total once the reply is done', async () => {
+ const { container } = render(ChatMessageStatistics, {
+ ...GENERATION,
+ agenticTimings: agentic(12_345)
+ });
+
+ await tick();
+
+ expect(container.textContent).toMatch(/\b12s\b/);
+ });
+
+ it('shows no task time when none was recorded', async () => {
+ const { container } = render(ChatMessageStatistics, {
+ ...GENERATION,
+ agenticTimings: agentic()
+ });
+
+ await tick();
+
+ // tokens, generation time and speed only
+ expect(container.textContent).not.toContain('2.8s');
+ expect(container.querySelectorAll('svg.lucide-hourglass')).toHaveLength(0);
+ });
+});
diff --git a/ui/apps/chat/tests/client/task-timer.svelte.test.ts b/ui/apps/chat/tests/client/task-timer.svelte.test.ts
deleted file mode 100644
index 5c248cc2f..000000000
--- a/ui/apps/chat/tests/client/task-timer.svelte.test.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-// Guards the live task timer: while a reply runs, the last tool row shows the
-// time since the task started. A single call reads it from context by its id;
-// a group takes it as a prop; a finished reply shows none.
-
-import ChatMessageAgentTrace from '#lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte';
-import { MessageRole, MessageType } from '#lib/enums/index.ts';
-import { agenticStore } from '#lib/stores/index.ts';
-import type { DatabaseMessage } from '#lib/types/index.ts';
-import { tick } from 'svelte';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { render } from 'vitest-browser-svelte';
-
-const CONV_ID = 'conv-timer';
-const TIMER = '[title="Time since the task started"]';
-
-type SessionPatch = { startedAt: number | null };
-type WithSession = { updateSession(conversationId: string, patch: SessionPatch): void };
-
-function reply(calls: number): DatabaseMessage {
- return {
- children: [],
- content: '',
- convId: CONV_ID,
- id: 'assistant-1',
- parent: null,
- role: MessageRole.ASSISTANT,
- timestamp: 0,
- toolCalls: JSON.stringify(
- Array.from({ length: calls }, (_, i) => ({
- function: { arguments: `{"path":"file-${i}.ts"}`, name: 'read_file' },
- id: `call-${i}`
- }))
- ),
- type: MessageType.TEXT
- };
-}
-
-function setStartedAt(startedAt: number | null) {
- // the loop sets this when a flow starts; there is no public setter
- (agenticStore as unknown as WithSession).updateSession(CONV_ID, { startedAt });
-}
-
-describe('task timer', () => {
- beforeEach(() => setStartedAt(Date.now() - 5000));
- afterEach(() => setStartedAt(null));
-
- it('shows on a single running call', async () => {
- const { container } = render(ChatMessageAgentTrace, {
- isLastAssistantMessage: true,
- isStreaming: true,
- message: reply(1)
- });
-
- await tick();
-
- expect(container.querySelectorAll(TIMER)).toHaveLength(1);
- expect(container.querySelector(TIMER)?.textContent?.trim()).toMatch(/^\d+s$/);
- });
-
- it('shows once on a group, not on the calls inside it', async () => {
- const { container } = render(ChatMessageAgentTrace, {
- isLastAssistantMessage: true,
- isStreaming: true,
- message: reply(2)
- });
-
- await tick();
-
- expect(container.querySelectorAll(TIMER)).toHaveLength(1);
- expect(container.querySelector('.tool-call-group')?.querySelector(TIMER)).not.toBeNull();
- });
-
- it('shows nothing once the reply is not streaming', async () => {
- const { container } = render(ChatMessageAgentTrace, {
- isLastAssistantMessage: true,
- isStreaming: false,
- message: reply(1)
- });
-
- await tick();
-
- expect(container.querySelectorAll(TIMER)).toHaveLength(0);
- });
-});
diff --git a/ui/apps/chat/tests/stories/chat/messages/ChatMessageStatistics.stories.svelte b/ui/apps/chat/tests/stories/chat/messages/ChatMessageStatistics.stories.svelte
index cf5acfc04..cf9f01120 100644
--- a/ui/apps/chat/tests/stories/chat/messages/ChatMessageStatistics.stories.svelte
+++ b/ui/apps/chat/tests/stories/chat/messages/ChatMessageStatistics.stories.svelte
@@ -48,6 +48,23 @@
<ChatMessageStatistics {...stats} {agenticTimings} hideSummary />
</StateGalleryItem>
+ <StateGalleryItem label="Agentic task time" note="generation view, whole reply">
+ <ChatMessageStatistics
+ {...stats}
+ {agenticTimings}
+ mode={ChatMessageStatisticsMode.GENERATION}
+ />
+ </StateGalleryItem>
+
+ <StateGalleryItem label="Live agentic task" note="task time ticks from its start">
+ <ChatMessageStatistics
+ {...stats}
+ isLive
+ mode={ChatMessageStatisticsMode.GENERATION}
+ taskStartedAt={Date.now()}
+ />
+ </StateGalleryItem>
+
<StateGalleryItem label="Generation only">
<ChatMessageStatistics {...stats} mode={ChatMessageStatisticsMode.GENERATION} />
</StateGalleryItem>
diff --git a/ui/apps/chat/tests/stories/chat/messages/fixtures.ts b/ui/apps/chat/tests/stories/chat/messages/fixtures.ts
index a686c958f..89fdf16cb 100644
--- a/ui/apps/chat/tests/stories/chat/messages/fixtures.ts
+++ b/ui/apps/chat/tests/stories/chat/messages/fixtures.ts
@@ -14,6 +14,7 @@ import type {
ChatMessageActions,
ChatMessageAgenticTimings,
ChatMessageSiblingInfo,
+ ChatMessageToolCallTiming,
DatabaseMessage,
DatabaseMessageExtra,
SettingsConfigValue
@@ -210,15 +211,34 @@ export const rawOutputMessage = createMessage({
/* Agentic (tool calls) */
+// a fixed start, so the loop time the group shows does not depend on the clock
+const AGENTIC_LOOP_START = Date.UTC(2026, 0, 1);
+const agenticToolCallTimings: ChatMessageToolCallTiming[] = [
+ {
+ duration_ms: 42,
+ endedAt: AGENTIC_LOOP_START + 42,
+ id: 'call-info',
+ name: BuiltInTool.SERVER_GET_INFO,
+ startedAt: AGENTIC_LOOP_START,
+ success: true
+ },
+ {
+ duration_ms: 318,
+ endedAt: AGENTIC_LOOP_START + 2418,
+ id: 'call-ls',
+ name: BuiltInTool.SERVER_EXEC_SHELL_COMMAND,
+ // waited for approval after the first call
+ startedAt: AGENTIC_LOOP_START + 2100,
+ success: true
+ }
+];
+
export const agenticTimings: ChatMessageAgenticTimings = {
llm: { predicted_ms: 5400, predicted_n: 312, prompt_ms: 980, prompt_n: 4210 },
perTurn: [
{
llm: { predicted_ms: 1800, predicted_n: 96, prompt_ms: 610, prompt_n: 2400 },
- toolCalls: [
- { duration_ms: 42, name: BuiltInTool.SERVER_GET_INFO, success: true },
- { duration_ms: 318, name: BuiltInTool.SERVER_EXEC_SHELL_COMMAND, success: true }
- ],
+ toolCalls: agenticToolCallTimings,
toolsMs: 360,
turn: 1
},
@@ -229,12 +249,10 @@ export const agenticTimings: ChatMessageAgenticTimings = {
turn: 2
}
],
- toolCalls: [
- { duration_ms: 42, name: BuiltInTool.SERVER_GET_INFO, success: true },
- { duration_ms: 318, name: BuiltInTool.SERVER_EXEC_SHELL_COMMAND, success: true }
- ],
+ toolCalls: agenticToolCallTimings,
toolCallsCount: 2,
toolsMs: 360,
+ totalMs: 9840,
turns: 2
};
@@ -244,6 +262,7 @@ export const assistantWithToolCallsMessage = createMessage({
parent: 'user-1',
reasoningContent: 'I need the working directory and the file list before I answer.',
role: MessageRole.ASSISTANT,
+ timings: { agentic: agenticTimings, predicted_ms: 1800, predicted_n: 96 },
toolCalls: toolCallsJson([
{ args: {}, id: 'call-info', name: BuiltInTool.SERVER_GET_INFO },
{ args: { command: 'ls -la' }, id: 'call-ls', name: BuiltInTool.SERVER_EXEC_SHELL_COMMAND }
diff --git a/ui/lib/harness/src/harness.ts b/ui/lib/harness/src/harness.ts
index e58e7ea25..594fea656 100644
--- a/ui/lib/harness/src/harness.ts
+++ b/ui/lib/harness/src/harness.ts
@@ -13,6 +13,7 @@ import type {
Timings,
Tool,
ToolCall,
+ ToolCallTiming,
ToolResult,
TurnStats,
} from "./types.js";
@@ -267,6 +268,7 @@ async function* run(
const tool = toolsByName.get(toolCall.function.name);
const startTime = performance.now();
+ const startedAt = Date.now();
let result: ToolResult;
@@ -327,9 +329,12 @@ async function* run(
}
const durationMs = Math.round(result.durationMs ?? performance.now() - startTime);
- const timing = {
+ const timing: ToolCallTiming = {
duration_ms: durationMs,
+ endedAt: Date.now(),
+ id: toolCall.id,
name: toolCall.function.name,
+ startedAt,
success: !result.isError,
};
diff --git a/ui/lib/harness/src/types.ts b/ui/lib/harness/src/types.ts
index 9167e37ca..a12e9a7e7 100644
--- a/ui/lib/harness/src/types.ts
+++ b/ui/lib/harness/src/types.ts
@@ -90,9 +90,14 @@ export interface LlmTotals {
}
export interface ToolCallTiming {
+ /** The call's id, to match the timing to its call. */
+ id: string;
name: string;
duration_ms: number;
success: boolean;
+ /** Wall-clock start and end (ms since epoch), waits for approval included. */
+ startedAt: number;
+ endedAt: number;
}
export interface TurnStats {
diff --git a/ui/lib/harness/tests/harness.test.ts b/ui/lib/harness/tests/harness.test.ts
index 4e302a14c..0fe79889b 100644
--- a/ui/lib/harness/tests/harness.test.ts
+++ b/ui/lib/harness/tests/harness.test.ts
@@ -163,6 +163,23 @@ describe("createHarness", () => {
});
});
+ it("times each call by its id with its wall-clock start and end", async () => {
+ const { client } = scriptedClient([[callEvent("first", "second")], []]);
+ const before = Date.now();
+ const events = await collect(client, [tool("first"), tool("second")]);
+ const toolCalls = (last(events) as { timings: { agentic: { toolCalls: unknown[] } } }).timings
+ .agentic.toolCalls as Array<{ id: string; startedAt: number; endedAt: number }>;
+
+ expect(toolCalls.map((timing) => timing.id)).toEqual(["call_0", "call_1"]);
+
+ for (const timing of toolCalls) {
+ expect(timing.startedAt).toBeGreaterThanOrEqual(before);
+ expect(timing.endedAt).toBeGreaterThanOrEqual(timing.startedAt);
+ }
+
+ expect(toolCalls[1].startedAt).toBeGreaterThanOrEqual(toolCalls[0].endedAt);
+ });
+
it("emits a streaming tool's updates before its result", async () => {
const { client } = scriptedClient([[callEvent("shell")], []]);
const events = await collect(client, [