Commit 325914def for llama.cpp
commit 325914defd2c1279a039366d999dff4c19a75b54
Author: Aleksander Grygier <aleksander.grygier@gmail.com>
Date: Mon Nov 23 17:24:05 2026 +0100
ui: show an agentic reply as a grouped Agent Trace (#32879)
* ui: show tool calls in the trace as a grouped, plain-language log
Tool calls and all the reasoning around them, up to the answer, collapse
into one row whose title sums up what happened ("Ran 2 commands, read 1
file"), so a model that thinks before every call still reads as one row
of work. Two calls, or one call with reasoning beside it, make a group;
without per-turn stats a group spans turns.
Each call reads as a sentence: built-in tools get hand-written phrasing
in two tenses, MCP and unknown tools read as "Used <tool> <argument>",
and the generic block shows simple arguments as labelled fields. A call
that has the argument a display setting picks (description by default,
overridable per tool in Settings > Tools) shows it as the model wrote it
instead, for any tool that declares it. A shell row always shows the
command, after "Ran" or after that description, and opens into the
terminal; the permission card shows the command that would run.
An open group is a list of rows under one rule, with no icons in the
headings; a running row shimmers. While a group is live its title says
what is happening now ("Reading package.json", "Thinking"), with a timer
since the prompt was sent, and the loop records the task's total time,
which the response stats show. Thoughts and tool calls now stay collapsed
while generating, with a one-time migration of the saved old default.
Assisted-by: Claude (Opus 5.5 Medium)
* ui: keep a live reply steady while its status changes
The status line ( Loading weights, Processing 40% ) sat above the content
before the first token and below it afterwards, and collapsed to nothing
while tokens streamed, so the stats and actions under it jumped. It is now
one row in the trace column with a trace row's box, shown only while
nothing else is moving, and while a tool group closes the reply it becomes
that group's live title instead.
The model badge shows from the start of a live reply, the user message
reserves its stats row while the prompt is processed, and a collapsed
group title is muted.
Assisted-by: Claude (Opus 5.5 Medium)
* ui: glide a sent message to the top of the screen
Sending snapped the page to its bottom in one frame, and layout that
settled a moment later was followed with more snaps. The page now eases
there: the target is read again every frame, so late layout bends the
motion instead of ending it with a jump, and corrections shortly after a
send are glided to as well.
A frame that arrives late counts as one frame, so a busy page slows the
glide instead of skipping it. Wheel, touch and scroll keys hand the page
back at once; typing the next message does not. Reduced motion keeps the
jump.
Assisted-by: Claude (Opus 5.5 Medium)
* ui: show tool images in the trace and in one slideshow of the thread
A closed tool group shows every image its calls produced under its title,
64px tall at their own proportions, in a carousel once they overflow; the
strip fades out when the group opens. A call with images shows tiny
thumbnails beside its title while its row is closed.
A group thumbnail, or an image in a user message, opens one slideshow of
every image, audio clip and video in the open thread, in thread order, at
the clicked item.
Assisted-by: Claude (Opus 5.5 Medium)
* ui: quiet the conversation around its messages
Stats and actions under earlier messages stay hidden until the reader
points at the message or tabs into it, changing only opacity so nothing
moves; the latest exchange keeps them in view and touch screens keep them
shown. A Display setting, Always show message statistics, keeps every
message's statistics in view.
With them out of sight the spacing tightens: messages sit 1rem apart, the
answer sits 0.75rem from the trace rows around it, and the user message's
stats and actions sit closer together. A queued message no longer sticks
to the bottom of the screen and scrolls with the conversation.
Assisted-by: Claude (Opus 5.5 Medium)
* ui: name the agentic reply an Agent Trace and give basic chat its own view
A reply that ran the agentic loop is now an Agent Trace: the component
that renders it is ChatMessageAgentTrace, with matching class names and
docs. A basic chat reply, with no tool calls, renders through the new
ChatMessageAssistantResponse as its reasoning and its answer, without the
trace's grouping, timer and permission handling. hasAgenticContent picks
the view, so a live reply becomes a trace the moment its first tool call
streams in.
Assisted-by: Claude (Opus 5.5 Medium)
diff --git a/ui/apps/chat/src/app.css b/ui/apps/chat/src/app.css
index 24ba6cec4..03e0e7d27 100644
--- a/ui/apps/chat/src/app.css
+++ b/ui/apps/chat/src/app.css
@@ -388,3 +388,27 @@
.stick-to-bottom-pin {
height: 1px;
}
+
+/*
+ * A message's stats and actions stay out of the way until the reader points at
+ * it or tabs into it. Only opacity changes, so their room is kept and nothing
+ * moves when they appear. Touch screens have no hover, so they keep them shown.
+ */
+@media (hover: hover) {
+ .message-meta {
+ opacity: 0;
+ transition: opacity 150ms ease-out;
+ }
+
+ .chat-message-user:hover .message-meta,
+ .chat-message-assistant:hover .message-meta,
+ .message-meta:focus-within {
+ opacity: 1;
+ }
+}
+
+@media (hover: hover) and (prefers-reduced-motion: reduce) {
+ .message-meta {
+ transition: none;
+ }
+}
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsList.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsList.svelte
index cc9b940df..611e52a75 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsList.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsList.svelte
@@ -6,8 +6,14 @@
ScrollCarousel
} from '#lib/components/app/index.ts';
import { ScrollCarouselVariant } from '#lib/enums/index.ts';
+ import { mediaGalleryStore } from '#lib/stores/index.ts';
import type { DatabaseMessageExtraMcpResource } from '#lib/types/index.ts';
- import { getAttachmentDisplayItems, isMcpPrompt, isMcpResource } from '#lib/utils/index.ts';
+ import {
+ getAttachmentDisplayItems,
+ isMcpPrompt,
+ isMcpResource,
+ isMediaExtra
+ } from '#lib/utils/index.ts';
interface Props {
class?: string;
@@ -26,12 +32,15 @@
limitToSingleRow?: boolean;
// For vision modality check
activeModelId?: string;
+ /** A message's attachments: media opens the conversation's slideshow at it */
+ conversationGallery?: boolean;
}
let {
activeModelId,
attachments = [],
class: className = '',
+ conversationGallery = false,
// Default to small size for form previews
imageClass = '',
imageHeight = 'h-24',
@@ -55,6 +64,12 @@
event?.stopPropagation();
event?.preventDefault();
+ if (conversationGallery && item.attachment && isMediaExtra(item.attachment)) {
+ mediaGalleryStore.show(item.attachment);
+
+ return;
+ }
+
// Find the index of the clicked item among non-MCP attachments
const nonMcpItems = displayItems.filter((i) => !isMcpPrompt(i) && !isMcpResource(i));
const index = nonMcpItems.findIndex((i) => i.id === item.id);
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistant.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistant.svelte
index 72679c8f1..5a5b3cd92 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistant.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistant.svelte
@@ -1,20 +1,21 @@
<script lang="ts">
import {
ChatMessageActionIcons,
- ChatMessageAgenticContent,
+ ChatMessageAgentTrace,
ChatMessageAssistantModel,
ChatMessageAssistantProcessingInfo,
ChatMessageAssistantRawOutput,
+ ChatMessageAssistantResponse,
ChatMessageAssistantStatistics,
ChatMessageContextMenu,
ChatMessageEditForm
} from '#lib/components/app/index.ts';
+ import { SETTINGS_KEYS } from '#lib/constants/index.ts';
import { getChatMessageEditContext } from '#lib/contexts/index.ts';
import { MessageRole } from '#lib/enums/index.ts';
import { useProcessingState } from '#lib/hooks/use-processing-state.svelte.ts';
import { chatStore, modelsStore, serverStore, settingsStore } from '#lib/stores/index.ts';
- import { modelLoadProgressText } from '#lib/utils/index.ts';
- import { hasAgenticContent } from '#lib/utils/index.ts';
+ import { hasAgenticContent, modelLoadProgressText } from '#lib/utils/index.ts';
interface Props {
class?: string;
@@ -39,7 +40,6 @@
// Get edit context
const editCtx = getChatMessageEditContext();
- const isAgentic = $derived(hasAgenticContent(message, toolMessages));
const processingState = useProcessingState();
let currentConfig = $derived(settingsStore.config);
@@ -47,11 +47,13 @@
let showRawOutput = $state(false);
- let displayedModel = $derived(message.model ?? null);
+ // A reply that ran the agentic loop ( it called tools ) is an Agent Trace;
+ // a basic chat reply is just its reasoning and its answer. A live reply
+ // becomes a trace the moment its first tool call streams in.
+ const isAgentTrace = $derived(hasAgenticContent(message, toolMessages));
let isCurrentlyLoading = $derived(chatStore.isLoading);
let isStreaming = $derived(chatStore.isStreaming());
- let hasNoContent = $derived(!message?.content?.trim());
let isActivelyProcessing = $derived(isCurrentlyLoading || isStreaming);
// A compaction summary reports its own progress on the compaction row, so
// this turn stays quiet while it runs instead of duplicating the indicator.
@@ -67,21 +69,29 @@
);
let modelLoadingText = $derived(modelLoadProgressText(modelLoadProgress));
- let showProcessingInfoTop = $derived(
- message?.role === MessageRole.ASSISTANT &&
- isActivelyProcessing &&
- !isCompacting &&
- hasNoContent &&
- !isAgentic &&
- isLastAssistantMessage
+ // The model badge shows from the start of a live reply, before the first
+ // chunk names the model, so the stats row does not pop in under the status
+ let displayedModel = $derived(
+ message.model ?? (isLastAssistantMessage && isActivelyProcessing ? loadTargetModel : null)
);
- let showProcessingInfoBottom = $derived(
+ // What the server is doing while nothing is generated yet; null when this
+ // message is not the live one. Empty while tokens are streaming.
+ let statusText = $derived(
message?.role === MessageRole.ASSISTANT &&
isActivelyProcessing &&
!isCompacting &&
- (!hasNoContent || isAgentic) &&
isLastAssistantMessage
+ ? modelLoadingText ||
+ processingState.getPromptProgressText() ||
+ processingState.getProcessingMessage()
+ : null
+ );
+
+ // the latest exchange keeps its stats and actions in view; earlier messages
+ // show them on hover, and the setting can keep their stats in view as well
+ let hidesStatsUntilHover = $derived(
+ !isLastAssistantMessage && !currentConfig[SETTINGS_KEYS.ALWAYS_SHOW_MESSAGE_STATS]
);
let assistantEl: HTMLDivElement | undefined = $state();
@@ -151,7 +161,7 @@
});
$effect(() => {
- if (showProcessingInfoTop || showProcessingInfoBottom) {
+ if (statusText !== null) {
processingState.startMonitoring();
}
});
@@ -167,10 +177,6 @@
class="chat-message-assistant text-md group w-full leading-7.5 {className}"
role="group"
>
- {#if showProcessingInfoTop}
- <ChatMessageAssistantProcessingInfo {modelLoadingText} position="top" {processingState} />
- {/if}
-
{#if editCtx.isEditing}
<ChatMessageEditForm />
{:else}
@@ -182,23 +188,31 @@
>
{#if showRawOutput}
<ChatMessageAssistantRawOutput {message} {toolMessages} />
- {:else}
- <ChatMessageAgenticContent
+
+ {#if statusText}
+ <ChatMessageAssistantProcessingInfo text={statusText} />
+ {/if}
+ {:else if isAgentTrace}
+ <ChatMessageAgentTrace
{isLastAssistantMessage}
isStreaming={chatStore.isStreaming()}
{message}
+ {statusText}
{toolMessages}
/>
+ {:else}
+ <ChatMessageAssistantResponse
+ {isLastAssistantMessage}
+ isStreaming={chatStore.isStreaming()}
+ {message}
+ {statusText}
+ />
{/if}
</ChatMessageContextMenu>
{/if}
- {#if showProcessingInfoBottom}
- <ChatMessageAssistantProcessingInfo {modelLoadingText} position="bottom" {processingState} />
- {/if}
-
{#if displayedModel}
- <div class="info my-6 grid gap-4 tabular-nums">
+ <div class={['info my-4 grid gap-4 tabular-nums', hidesStatsUntilHover && 'message-meta']}>
<div class="inline-flex flex-wrap items-start gap-2 text-caption text-muted-foreground">
<ChatMessageAssistantModel
{displayedModel}
@@ -218,32 +232,41 @@
{/if}
{#if message.timestamp && !editCtx.isEditing}
- <ChatMessageActionIcons
- actionsPosition="left"
- justify="start"
- onContinue={currentConfig.enableContinueGeneration ? onContinue : undefined}
- onRawOutputToggle={(enabled) => (showRawOutput = enabled)}
- {onRegenerate}
- rawOutputEnabled={showRawOutput}
- showRawOutputSwitch={currentConfig.showRawOutputSwitch}
- />
+ <div class={isLastAssistantMessage ? undefined : 'message-meta'}>
+ <ChatMessageActionIcons
+ actionsPosition="left"
+ justify="start"
+ onContinue={currentConfig.enableContinueGeneration ? onContinue : undefined}
+ onRawOutputToggle={(enabled) => (showRawOutput = enabled)}
+ {onRegenerate}
+ rawOutputEnabled={showRawOutput}
+ showRawOutputSwitch={currentConfig.showRawOutputSwitch}
+ />
+ </div>
{/if}
</div>
<style>
+ /* The reply's minimum height decides where a sent message rests once it
+ glides up, and the top offset adds room above it. A phone's floating
+ header covers the top of the page, so there it rests below the header. */
:global(.chat-message):last-child .chat-message-assistant {
+ --sent-message-top-offset: var(--page-top);
--assistant-min-height-offset: calc(
var(--last-user-message-height, 19rem) + var(--chat-form-height, 6rem) +
var(--chat-form-bottom-position, 0.5rem) + var(--chat-form-padding-top, 6rem) +
- var(--assistant-margin-top, 3rem) + var(--chat-tabs-offset, 0px)
+ var(--assistant-margin-top, 1rem) + var(--chat-tabs-offset, 0px) +
+ var(--sent-message-top-offset)
);
min-height: calc(100dvh - var(--assistant-min-height-offset));
@media (width > 768px) {
+ --sent-message-top-offset: 0.5rem;
--assistant-min-height-offset: calc(
var(--last-user-message-height, 18rem) + var(--chat-form-height, 6rem) +
var(--chat-form-bottom-position, 1rem) + var(--chat-form-padding-top, 6rem) +
- var(--assistant-margin-top, 3rem) + var(--chat-tabs-offset, 0px)
+ var(--assistant-margin-top, 1rem) + var(--chat-tabs-offset, 0px) +
+ var(--sent-message-top-offset)
);
}
}
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistantProcessingInfo.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistantProcessingInfo.svelte
index 3d824b0b3..ee5845770 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistantProcessingInfo.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistantProcessingInfo.svelte
@@ -1,25 +1,15 @@
<script lang="ts">
- import type { UseProcessingStateReturn } from '#lib/hooks/use-processing-state.svelte.ts';
- import { fade } from 'svelte/transition';
+ // One status row for a reply that is waiting on the server: loading the
+ // model, processing the prompt. It has the same box as a trace row, so
+ // the row that comes next takes its place without moving what is below.
interface Props {
- modelLoadingText: string | null;
- processingState: UseProcessingStateReturn;
- position: 'top' | 'bottom';
+ text: string;
}
- let { modelLoadingText, position, processingState }: Props = $props();
-
- const marginClass = $derived(position === 'top' ? 'mt-6' : 'mt-4');
+ let { text }: Props = $props();
</script>
-<div in:fade class="{marginClass} w-full max-w-3xl">
- <div class="flex flex-col items-start gap-2">
- <span class="shimmer-text text-body-sm">
- {modelLoadingText ??
- processingState.getPromptProgressText() ??
- processingState.getProcessingMessage() ??
- 'Processing...'}
- </span>
- </div>
+<div class="py-1.5 text-body-sm">
+ <span class="shimmer-text font-medium">{text}</span>
</div>
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistantResponse.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistantResponse.svelte
new file mode 100644
index 000000000..259da9a9a
--- /dev/null
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistantResponse.svelte
@@ -0,0 +1,108 @@
+<script lang="ts">
+ // A basic chat reply: the model's reasoning, if any, and its answer. A reply
+ // that ran the agentic loop renders as an Agent Trace (ChatMessageAgentTrace)
+ // instead, with its tool calls grouped into rows.
+
+ import ChatMessageReasoningBlock from '../../ChatMessageReasoningBlock.svelte';
+ import ChatMessageAssistantProcessingInfo from './ChatMessageAssistantProcessingInfo.svelte';
+ import { MarkdownContent } from '#lib/components/app/index.ts';
+ import { REPLY_STATUS_FALLBACK } from '#lib/constants/index.ts';
+ import { AgenticSectionType } from '#lib/enums/index.ts';
+ import { agenticStore, settingsStore } from '#lib/stores/index.ts';
+ import type { AgenticSection, DatabaseMessage } from '#lib/types/index.ts';
+ import {
+ deriveAgenticSections,
+ isSectionExpandedByDefault,
+ showsReplyStatus
+ } from '#lib/utils/index.ts';
+
+ interface Props {
+ message: DatabaseMessage;
+ isStreaming?: boolean;
+ isLastAssistantMessage?: boolean;
+ /**
+ * What the server is doing while this reply waits on it ( "Processing
+ * 40%" ), empty while tokens stream, null when the reply is not live.
+ */
+ statusText?: string | null;
+ }
+
+ let {
+ isLastAssistantMessage = false,
+ isStreaming: isChatStreaming = false,
+ message,
+ statusText = null
+ }: Props = $props();
+
+ // only the last assistant message is live; the chat-level flag is shared
+ const isStreaming = $derived(isChatStreaming && isLastAssistantMessage);
+
+ let expandedStates: Record<number, boolean> = $state({});
+
+ const showThoughtInProgress = $derived(Boolean(settingsStore.config.showThoughtInProgress));
+
+ const hasReasoningError = $derived(
+ isLastAssistantMessage ? !!agenticStore.getLastError(message.convId) : false
+ );
+
+ const sections = $derived(deriveAgenticSections(message, [], [], isStreaming));
+
+ function isExpanded(index: number, section: AgenticSection): boolean {
+ if (expandedStates[index] !== undefined) return expandedStates[index];
+
+ // a basic reply has no tool sections, so the two tool settings never apply
+ return isSectionExpandedByDefault(section, {
+ alwaysShowToolCallContent: false,
+ showThoughtInProgress,
+ showToolCallInProgress: false
+ });
+ }
+
+ function toggleExpanded(index: number, section: AgenticSection) {
+ expandedStates[index] = !isExpanded(index, section);
+ }
+
+ const showStatus = $derived(showsReplyStatus(statusText, sections.at(-1), isStreaming));
+</script>
+
+<div class="assistant-response">
+ {#each sections as section, index (index)}
+ {#if section.type === AgenticSectionType.TEXT}
+ <div class="assistant-response-text">
+ <MarkdownContent attachments={message?.extra} content={section.content} />
+ </div>
+ {:else if section.type === AgenticSectionType.REASONING || section.type === AgenticSectionType.REASONING_PENDING}
+ <ChatMessageReasoningBlock
+ attachments={message?.extra}
+ {hasReasoningError}
+ {isStreaming}
+ onToggle={() => toggleExpanded(index, section)}
+ open={isExpanded(index, section)}
+ {section}
+ />
+ {/if}
+ {/each}
+
+ {#if showStatus}
+ <ChatMessageAssistantProcessingInfo text={statusText || REPLY_STATUS_FALLBACK} />
+ {/if}
+</div>
+
+<style>
+ .assistant-response {
+ display: flex;
+ flex-direction: column;
+ gap: 0.5rem;
+ width: 100%;
+ max-width: 48rem;
+ }
+
+ .assistant-response > :global(*) {
+ min-width: 0;
+ }
+
+ /* the answer stands a little apart from the reasoning above it, as in a trace */
+ .assistant-response > :global(:not(.assistant-response-text) + .assistant-response-text) {
+ margin-top: 0.25rem;
+ }
+</style>
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockDefault.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockDefault.svelte
index f959d0028..0cbe86535 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockDefault.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockDefault.svelte
@@ -3,7 +3,9 @@
// Renders section.toolArgs / section.toolResult directly using the
// shared chrome shell.
+ import { simpleToolArgFields } from './parsers/tool-call-phrasing';
import ToolCallBlock from './ToolCallBlock.svelte';
+ import ToolCallTitle from './ToolCallTitle.svelte';
import { Loader2 } from '@lucide/svelte';
import { MarkdownContent, SyntaxHighlightedCode } from '#lib/components/app/index.ts';
import { MAX_HEIGHT_CODE_BLOCK } from '#lib/constants/index.ts';
@@ -13,7 +15,6 @@
import {
classifyToolResult,
formatJsonPretty,
- getToolUi,
parseToolResultWithMedia
} from '#lib/utils/index.ts';
@@ -27,14 +28,31 @@
let { attachments, isStreaming, onToggle, open, section }: Props = $props();
- const title = $derived(getToolUi(section.toolName)?.label ?? section.toolName ?? '');
+ const argFields = $derived(simpleToolArgFields(section.toolArgs));
const outputKind = $derived(classifyToolResult(section.toolResult));
const parsedLines: ToolResultLine[] = $derived(
section.toolResult ? parseToolResultWithMedia(section.toolResult, attachments) : []
);
</script>
-<ToolCallBlock {isStreaming} meta={null} {onToggle} {open} {section} {title}>
+{#snippet inputFields(fields: { label: string; value: string }[])}
+ <dl class="grid grid-cols-[minmax(0,max-content)_minmax(0,1fr)] gap-x-6 gap-y-1 text-caption">
+ {#each fields as field, i (i)}
+ <dt class="text-muted-foreground">{field.label}</dt>
+
+ <dd class="min-w-0 font-mono break-words text-foreground/90">{field.value}</dd>
+ {/each}
+ </dl>
+{/snippet}
+
+<ToolCallBlock {isStreaming} meta={null} {onToggle} {open} {section}>
+ {#snippet titleSnippet(phrase)}
+ <ToolCallTitle
+ label={phrase.label}
+ target={phrase.target && phrase.quoted ? `'${phrase.target}'` : phrase.target}
+ />
+ {/snippet}
+
{#snippet children(_meta, ctx)}
{#if ctx.isStreamingCall}
<div class="mb-2 flex items-center gap-2 text-caption text-muted-foreground/70">
@@ -70,12 +88,16 @@
<span>Input</span>
</div>
- <SyntaxHighlightedCode
- code={formatJsonPretty(section.toolArgs ?? '')}
- language={FileTypeText.JSON}
- maxHeight={MAX_HEIGHT_CODE_BLOCK}
- streaming={ctx.isCodeStreaming}
- />
+ {#if argFields}
+ {@render inputFields(argFields)}
+ {:else}
+ <SyntaxHighlightedCode
+ code={formatJsonPretty(section.toolArgs ?? '')}
+ language={FileTypeText.JSON}
+ maxHeight={MAX_HEIGHT_CODE_BLOCK}
+ streaming={ctx.isCodeStreaming}
+ />
+ {/if}
{/if}
<div
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockEditFile.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockEditFile.svelte
index 5e45d7c2c..30c6f8e15 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockEditFile.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockEditFile.svelte
@@ -1,10 +1,15 @@
<script lang="ts">
- import { parseEditFileMeta, parseEditFileTitleMeta } from './parsers/edit-file';
+ import {
+ editFileDiffStats,
+ parseEditFileMeta,
+ parseEditFileTitleMeta
+ } from './parsers/edit-file';
import ToolCallBlock from './ToolCallBlock.svelte';
+ import ToolCallTitle from './ToolCallTitle.svelte';
import { XCircle } from '@lucide/svelte';
import { SyntaxHighlightedCode } from '#lib/components/app/index.ts';
import { MAX_HEIGHT_CODE_BLOCK, RESULT_STAT_SEPARATOR } from '#lib/constants/index.ts';
- import { FileTypeText } from '#lib/enums/index.ts';
+ import { AgenticSectionType, FileTypeText } from '#lib/enums/index.ts';
import { toolsStore } from '#lib/stores/index.ts';
import type { AgenticSection } from '#lib/types/index.ts';
import {
@@ -24,7 +29,7 @@
let { isStreaming, onToggle, open, section }: Props = $props();
const editFileMeta = $derived(parseEditFileTitleMeta(section));
- // body-only: the full meta parses the embedded edit strings, and these
+ // body-only: the full meta parses the embedded edit strings, and these two
// deriveds are read solely from the children snippet, which renders only
// while the block is expanded
const editFileBody = $derived(parseEditFileMeta(section));
@@ -32,23 +37,36 @@
const editDiffs = $derived(
(editFileBody?.edits ?? []).map((edit) => computeLineDiff(edit.oldText, edit.newText))
);
+
+ // Lines added and removed, for the title once the edit has applied. The
+ // title always renders and sections are rebuilt on every streamed chunk,
+ // so the parse and diff are remembered per call instead of re-run each time.
+ const diffStats = $derived(
+ section.type === AgenticSectionType.TOOL_CALL && section.toolResult
+ ? editFileDiffStats(section)
+ : null
+ );
</script>
<ToolCallBlock {isStreaming} meta={editFileMeta} {onToggle} {open} {section}>
- {#snippet titleSnippet()}
- <span class="flex min-w-0 flex-wrap items-baseline gap-x-1">
- <span class="shrink-0 text-muted-foreground">Edit file</span>
-
- <span class="flex min-w-0 items-baseline gap-1.5">
- <span class="min-w-0 overflow-x-auto font-mono" title={editFileMeta?.filePath}>
- {abbreviateHome(editFileMeta?.filePath ?? '', home)}
+ {#snippet titleSnippet(phrase)}
+ <ToolCallTitle
+ label={phrase.label}
+ target={abbreviateHome(editFileMeta?.filePath ?? '', home)}
+ targetTitle={editFileMeta?.filePath}
+ >
+ {#if diffStats}
+ <span class="shrink-0 font-mono text-caption">
+ <span class="text-fg-success">+{diffStats.added}</span>
+
+ <span class="text-fg-danger">-{diffStats.removed}</span>
</span>
+ {/if}
- {#if editFileMeta?.errorMessage}
- <span class="shrink-0 text-caption italic text-muted-foreground/70">(failed)</span>
- {/if}
- </span>
- </span>
+ {#if editFileMeta?.errorMessage}
+ <span class="shrink-0 text-caption italic text-muted-foreground/70">(failed)</span>
+ {/if}
+ </ToolCallTitle>
{/snippet}
{#snippet children(_meta, ctx)}
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockExecShellCommand.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockExecShellCommand.svelte
index 06d417f7a..d79535613 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockExecShellCommand.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockExecShellCommand.svelte
@@ -1,15 +1,15 @@
<script lang="ts">
- // Block for `exec_shell_command`. Unlike the other tools, this
- // renderer uses CollapsibleTerminalBlock (terminal-style frame)
- // and treats "live" output chunks as active even after the call
- // resolved, so the spinner stays on while stdout is still flowing.
+ // Block for `exec_shell_command`. Collapsed, it reads as one line: "Ran"
+ // or the model's description of the call, always followed by the command.
+ // Open, it shows the terminal: the prompt line and the output. It treats
+ // "live" output chunks as active even after the call resolved, so the
+ // spinner stays on while stdout is still flowing.
// The scroll-to-bottom auto-scroll logic mirrors what was here
// before extraction.
import { parseExecShellCommandMeta } from './parsers/exec-shell-command';
import ToolCallBlock from './ToolCallBlock.svelte';
import { AlertTriangle, Check, CircleStop, Loader2, XCircle } from '@lucide/svelte';
- import { CollapsibleTerminalBlock } from '#lib/components/app/index.ts';
import {
SETTINGS_KEYS,
TOOL_RUNTIME_SCROLL_AT_BOTTOM_THRESHOLD_PX
@@ -213,13 +213,13 @@
});
</script>
-{#snippet execShellTitle()}
+{#snippet promptLine()}
{#if cwd}
<span class="exec-wd" title={cwd}>{wdDisplay}</span>
-
- <span class="exec-prompt">$</span>
{/if}
+ <span class="exec-prompt">$</span>
+
{#if highlightedCommandHtml}
<span class="font-mono">{@html highlightedCommandHtml}</span>
{:else}
@@ -239,73 +239,98 @@
{onToggle}
{open}
{section}
- spinIconWhenActive={true}
- wrapper={CollapsibleTerminalBlock}
>
- {#snippet titleSnippet()}
- {@render execShellTitle()}
+ {#snippet titleSnippet(phrase)}
+ <!-- The command is always in the title: a description is the model's
+ wording, and the reader approves and audits what actually runs.
+ Both take their own width while the row has room. When it runs out
+ the command gives way first, since the full command is one click away
+ and a cut description reads as noise. -->
+ <span class="flex min-w-0 items-baseline gap-1.5">
+ <span
+ class={phrase.described ? 'min-w-0 truncate' : 'shrink-0'}
+ title={phrase.described ? phrase.label : undefined}>{phrase.label}</span
+ >
+
+ {#if execShellMeta?.command}
+ <span
+ class="exec-title-command min-w-[2ch] shrink-[1000] truncate font-mono"
+ title={execShellMeta.command}
+ >
+ {execShellMeta.command}
+ </span>
+ {/if}
+ </span>
{/snippet}
{#snippet children(_meta, ctx)}
- {#if (ctx.isPending && !commandStreaming) || (isLive && !section.toolResult)}
- <div class="flex items-start gap-2 text-caption text-muted-foreground/70">
- <Loader2 class="size-icon-xs animate-spin" />
- Executing command...
- </div>
- {:else if ctx.isInterrupted}
- <div class="flex items-start gap-2 text-caption text-muted-foreground/70 italic">
- <CircleStop class="mt-0.5 h-3 w-3 shrink-0" />
-
- <span>Command interrupted before it returned output</span>
+ <div class="terminal-frame">
+ <div class="exec-prompt-line font-mono text-caption">
+ {@render promptLine()}
</div>
- {:else if execShellError}
- <div class="flex items-start gap-2 text-caption text-fg-danger italic">
- <XCircle class="mt-0.5 size-icon-xs shrink-0" />
- <span>{execShellError}</span>
- </div>
- {:else if section.toolResult}
- <div
- bind:this={scrollEl}
- class={['terminal-output', !useFullHeightCodeBlocks && 'is-clamped']}
- onscroll={handleScrollEvent}
- >
- {#each outputLines as line, i (i)}
- <div class="font-mono text-caption leading-relaxed whitespace-pre-wrap">{line.text}</div>
-
- {#if line.media?.type === AttachmentType.IMAGE}
- <img
- alt={line.media.name}
- class="mt-2 mb-2 h-auto max-w-full rounded-lg"
- loading="lazy"
- src={line.media.base64Url}
- />
- {/if}
- {/each}
+ {#if (ctx.isPending && !commandStreaming) || (isLive && !section.toolResult)}
+ <div class="flex items-start gap-2 text-caption text-muted-foreground/70">
+ <Loader2 class="size-icon-xs animate-spin" />
+ Executing command...
+ </div>
+ {:else if ctx.isInterrupted}
+ <div class="flex items-start gap-2 text-caption text-muted-foreground/70 italic">
+ <CircleStop class="mt-0.5 h-3 w-3 shrink-0" />
+
+ <span>Command interrupted before it returned output</span>
+ </div>
+ {:else if execShellError}
+ <div class="flex items-start gap-2 text-caption text-fg-danger italic">
+ <XCircle class="mt-0.5 size-icon-xs shrink-0" />
+
+ <span>{execShellError}</span>
+ </div>
+ {:else if section.toolResult}
+ <div
+ bind:this={scrollEl}
+ class={['terminal-output', !useFullHeightCodeBlocks && 'is-clamped']}
+ onscroll={handleScrollEvent}
+ >
+ {#each outputLines as line, i (i)}
+ <div class="font-mono text-caption leading-relaxed whitespace-pre-wrap">
+ {line.text}
+ </div>
+
+ {#if line.media?.type === AttachmentType.IMAGE}
+ <img
+ alt={line.media.name}
+ class="mt-2 mb-2 h-auto max-w-full rounded-lg"
+ loading="lazy"
+ src={line.media.base64Url}
+ />
+ {/if}
+ {/each}
- {#if isExitCodeFinalLine && execShellExitStatus}
- <div class={exitBadgeClass}>
- {#if execShellExitStatus.timedOut}
- <AlertTriangle class="size-icon-xs" />
+ {#if isExitCodeFinalLine && execShellExitStatus}
+ <div class={exitBadgeClass}>
+ {#if execShellExitStatus.timedOut}
+ <AlertTriangle class="size-icon-xs" />
- <span>timed out</span>
+ <span>timed out</span>
- <span class="exit-sep">·</span>
+ <span class="exit-sep">·</span>
- <span>exit {execShellExitStatus.code}</span>
- {:else if execShellExitStatus.code === 0}
- <Check class="size-icon-xs" />
+ <span>exit {execShellExitStatus.code}</span>
+ {:else if execShellExitStatus.code === 0}
+ <Check class="size-icon-xs" />
- <span>exit 0</span>
- {:else}
- <XCircle class="size-icon-xs" />
+ <span>exit 0</span>
+ {:else}
+ <XCircle class="size-icon-xs" />
- <span>exit {execShellExitStatus.code}</span>
- {/if}
- </div>
- {/if}
- </div>
- {/if}
+ <span>exit {execShellExitStatus.code}</span>
+ {/if}
+ </div>
+ {/if}
+ </div>
+ {/if}
+ </div>
{/snippet}
</ToolCallBlock>
@@ -343,6 +368,29 @@
}
}
+ .exec-title-command {
+ color: var(--fg-muted);
+ font-size: 0.92em;
+ }
+
+ .terminal-frame {
+ display: grid;
+ gap: 0.5rem;
+ min-width: 0;
+ padding: 0.625rem 0.75rem;
+ border-radius: var(--radius-md, 0.375rem);
+ background: var(--surface-code);
+ border: 1px solid color-mix(in oklch, var(--line-default) 30%, transparent);
+ }
+
+ .exec-prompt-line {
+ word-break: break-word;
+ }
+
+ .exec-prompt-line :global(.font-mono) {
+ white-space: pre-wrap;
+ }
+
.terminal-output.is-clamped {
max-height: 28rem;
overflow-y: auto;
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockFileGlobSearch.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockFileGlobSearch.svelte
index 67c5e15c3..f2da8cbf7 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockFileGlobSearch.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockFileGlobSearch.svelte
@@ -20,11 +20,9 @@
</script>
<ToolCallBlock {isStreaming} meta={fileGlobMeta} {onToggle} {open} {section}>
- {#snippet titleSnippet()}
+ {#snippet titleSnippet(phrase)}
{#if fileGlobMeta}
- <span class="text-muted-foreground"
- >{fileGlobMeta.include === '**' ? 'List files' : 'Search files'} </span
- >
+ <span class="text-muted-foreground">{phrase.label} </span>
{#if fileGlobMeta.include !== '**'}
<span class="font-mono">{fileGlobMeta.include}</span>
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetDatetime.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetDatetime.svelte
index efcec2a3f..0b3486b7e 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetDatetime.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetDatetime.svelte
@@ -1,5 +1,5 @@
<script lang="ts">
- import { Clock, Loader2 } from '@lucide/svelte';
+ import { Loader2 } from '@lucide/svelte';
import { AgenticSectionType } from '#lib/enums/index.ts';
import type { AgenticSection } from '#lib/types/index.ts';
@@ -43,8 +43,6 @@
</script>
<div class="text-muted-foreground flex items-center gap-2 py-1.5">
- <Clock class="text-muted-foreground/60 size-icon-sm shrink-0" />
-
{#if showSpinner}
<span class="text-foreground/80 text-label">Current time</span>
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetInfo.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetInfo.svelte
index 3b68a2d85..bfc1aff97 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetInfo.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetInfo.svelte
@@ -48,15 +48,7 @@
const cwdDisplay = $derived(abbreviateHome(infoMeta.cwd ?? '', home));
</script>
-<ToolCallBlock
- {isStreaming}
- meta={infoMeta}
- {onToggle}
- {open}
- {section}
- spinIconWhenActive
- title="Runtime info"
->
+<ToolCallBlock {isStreaming} meta={infoMeta} {onToggle} {open} {section}>
{#snippet children(meta, _ctx)}
{#if meta?.errorMessage}
<div
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGrepSearch.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGrepSearch.svelte
index 29e70f3f6..b9d147168 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGrepSearch.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGrepSearch.svelte
@@ -20,9 +20,9 @@
</script>
<ToolCallBlock {isStreaming} meta={grepMeta} {onToggle} {open} {section}>
- {#snippet titleSnippet()}
+ {#snippet titleSnippet(phrase)}
{#if grepMeta}
- <span class="text-muted-foreground">Search for </span>
+ <span class="text-muted-foreground">{phrase.label} </span>
<span class="font-mono">{grepMeta.pattern}</span>
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockReadFile.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockReadFile.svelte
index e8c424605..eefdc0021 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockReadFile.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockReadFile.svelte
@@ -1,6 +1,7 @@
<script lang="ts">
import { parseReadFileMeta } from './parsers/read-file';
import ToolCallBlock from './ToolCallBlock.svelte';
+ import ToolCallTitle from './ToolCallTitle.svelte';
import { SyntaxHighlightedCode } from '#lib/components/app/index.ts';
import { CODE_BLOCK, MAX_HEIGHT_CODE_BLOCK } from '#lib/constants/index.ts';
import type { AgenticSection } from '#lib/types/index.ts';
@@ -18,20 +19,14 @@
</script>
<ToolCallBlock {isStreaming} meta={readFileMeta} {onToggle} {open} {section}>
- {#snippet titleSnippet()}
- <span class="flex min-w-0 flex-wrap items-baseline gap-x-1">
- <span class="shrink-0 text-muted-foreground">Read file</span>
-
- <span class="flex min-w-0 items-baseline gap-1.5">
- <span class="min-w-0 overflow-x-auto font-mono">{readFileMeta?.fileName}</span>
-
- {#if readFileMeta?.lineRange}
- <span class="shrink-0 text-muted-foreground">
- (lines {readFileMeta.lineRange.start}-{readFileMeta.lineRange.end})
- </span>
- {/if}
- </span>
- </span>
+ {#snippet titleSnippet(phrase)}
+ <ToolCallTitle label={phrase.label} target={readFileMeta?.fileName}>
+ {#if readFileMeta?.lineRange}
+ <span class="shrink-0 text-muted-foreground">
+ (lines {readFileMeta.lineRange.start}-{readFileMeta.lineRange.end})
+ </span>
+ {/if}
+ </ToolCallTitle>
{/snippet}
{#snippet children(_meta, _ctx)}
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockReadMedia.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockReadMedia.svelte
index 3961b86d0..1091b8dcb 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockReadMedia.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockReadMedia.svelte
@@ -1,6 +1,7 @@
<script lang="ts">
import { parseReadMediaMeta } from './parsers/read-media';
import ToolCallBlock from './ToolCallBlock.svelte';
+ import ToolCallTitle from './ToolCallTitle.svelte';
import { ATTACHMENT_SAVED_REGEX } from '#lib/constants/agentic.constants.ts';
import { AttachmentType, MimeTypeAudio } from '#lib/enums/index.ts';
import type {
@@ -47,12 +48,8 @@
</script>
<ToolCallBlock {isStreaming} meta={readMediaMeta} {onToggle} {open} {section}>
- {#snippet titleSnippet()}
- <span class="flex min-w-0 flex-wrap items-baseline gap-x-1">
- <span class="shrink-0 text-muted-foreground">Read media</span>
-
- <span class="min-w-0 overflow-x-auto font-mono">{readMediaMeta?.fileName}</span>
- </span>
+ {#snippet titleSnippet(phrase)}
+ <ToolCallTitle label={phrase.label} target={readMediaMeta?.fileName} />
{/snippet}
{#snippet children(_meta, _ctx)}
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockRunJavascript.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockRunJavascript.svelte
index 2fd1866f3..e20a4f4ba 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockRunJavascript.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockRunJavascript.svelte
@@ -6,7 +6,6 @@
import { MAX_HEIGHT_CODE_BLOCK } from '#lib/constants/index.ts';
import { FileTypeText } from '#lib/enums/index.ts';
import type { AgenticSection } from '#lib/types/index.ts';
- import { getToolUi } from '#lib/utils/index.ts';
interface Props {
section: AgenticSection;
@@ -18,10 +17,9 @@
let { isStreaming, onToggle, open, section }: Props = $props();
const runJsMeta = $derived(parseRunJavascriptMeta(section));
- const title = $derived(getToolUi(section.toolName)?.label ?? section.toolName ?? '');
</script>
-<ToolCallBlock {isStreaming} meta={runJsMeta} {onToggle} {open} {section} {title}>
+<ToolCallBlock {isStreaming} meta={runJsMeta} {onToggle} {open} {section}>
{#snippet children(meta, ctx)}
{#if ctx.isPending}
<div class="rounded bg-muted/20 p-2 text-caption text-muted-foreground/70 italic">
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockSearchResults.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockSearchResults.svelte
index 78fba40f9..efbbde974 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockSearchResults.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockSearchResults.svelte
@@ -2,7 +2,6 @@
import * as HoverCard from '@ggml-org/llama-ui/ui/hover-card';
import { Globe, Loader2 } from '@lucide/svelte';
import { CollapsibleContentBlock } from '#lib/components/app/index.ts';
- import { ICON_CLASS_DEFAULT, ICON_CLASS_SPIN } from '#lib/constants/index.ts';
import { AgenticSectionType } from '#lib/enums/index.ts';
import { mcpStore } from '#lib/stores/index.ts';
import type { AgenticSection, SearchResult } from '#lib/types/index.ts';
@@ -30,13 +29,6 @@
const results = $derived(extractSearchResults(section.toolResult));
const query = $derived(extractSearchQuery(section.toolArgs));
- // Same icon-resolution chain as ChatMessageToolCallBlockDefault so
- // MCP-server branding is consistent across both views. Spinner wins
- // while the call is in flight so the user sees execution status.
- const iconUrl = $derived(showSpinner ? null : mcpStore.getServerFaviconForTool(section.toolName));
- const icon = $derived(showSpinner ? Loader2 : undefined);
- const iconClass = $derived(showSpinner ? ICON_CLASS_SPIN : ICON_CLASS_DEFAULT);
-
// Verb reflects state: "Searching" while the call is in flight, "Searched"
// once results (or a definitive empty response) have arrived. Lets the
// heading read as a live progress indicator rather than a completed
@@ -154,7 +146,14 @@
{/if}
{/snippet}
-<CollapsibleContentBlock class="my-2" {icon} {iconClass} {iconUrl} {onToggle} {open} {title}>
+<CollapsibleContentBlock
+ class="my-2"
+ inlineChevron
+ {onToggle}
+ {open}
+ shimmerTitle={showSpinner}
+ {title}
+>
{#if results.length > 0}
<div class="flex flex-wrap items-center gap-2 pb-1">
{#each results as result (result.url)}
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockWriteFile.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockWriteFile.svelte
index 394287ec1..c0fdfa8ed 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockWriteFile.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockWriteFile.svelte
@@ -1,6 +1,7 @@
<script lang="ts">
import { parseWriteFileMeta, parseWriteFileTitleMeta } from './parsers/write-file';
import ToolCallBlock from './ToolCallBlock.svelte';
+ import ToolCallTitle from './ToolCallTitle.svelte';
import { XCircle } from '@lucide/svelte';
import { SyntaxHighlightedCode } from '#lib/components/app/index.ts';
import { MAX_HEIGHT_CODE_BLOCK, RESULT_STAT_SEPARATOR } from '#lib/constants/index.ts';
@@ -27,20 +28,16 @@
</script>
<ToolCallBlock {isStreaming} meta={writeFileMeta} {onToggle} {open} {section}>
- {#snippet titleSnippet()}
- <span class="flex min-w-0 flex-wrap items-baseline gap-x-1">
- <span class="shrink-0 text-muted-foreground">Write file</span>
-
- <span class="flex min-w-0 items-baseline gap-1.5">
- <span class="min-w-0 overflow-x-auto font-mono" title={writeFileMeta?.filePath}>
- {abbreviateHome(writeFileMeta?.filePath ?? '', home)}
- </span>
-
- {#if writeFileMeta?.errorMessage}
- <span class="shrink-0 text-caption italic text-muted-foreground/70">(failed)</span>
- {/if}
- </span>
- </span>
+ {#snippet titleSnippet(phrase)}
+ <ToolCallTitle
+ label={phrase.label}
+ target={abbreviateHome(writeFileMeta?.filePath ?? '', home)}
+ targetTitle={writeFileMeta?.filePath}
+ >
+ {#if writeFileMeta?.errorMessage}
+ <span class="shrink-0 text-caption italic text-muted-foreground/70">(failed)</span>
+ {/if}
+ </ToolCallTitle>
{/snippet}
{#snippet children(_meta, ctx)}
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
new file mode 100644
index 000000000..3f8acb39e
--- /dev/null
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallGroup.svelte
@@ -0,0 +1,122 @@
+<script lang="ts">
+ // One row for a run of consecutive tool calls: a summary of what they did
+ // ("Ran 3 commands, read 2 files") or, while one runs, what is happening
+ // now ("Reading package.json"). Images the calls produced show as small
+ // thumbnails under it. Expanding it lists each call as its own row.
+
+ import { describeToolActivity, summarizeToolCalls } from './parsers/tool-call-phrasing';
+ import ToolCallElapsed from './ToolCallElapsed.svelte';
+ import { CollapsibleContentBlock } from '#lib/components/app/index.ts';
+ import { ScrollCarousel } from '#lib/components/app/index.ts';
+ import { ScrollCarouselVariant } from '#lib/enums/index.ts';
+ import { mediaGalleryStore, settingsStore } from '#lib/stores/index.ts';
+ import type { AgenticSection } from '#lib/types/index.ts';
+ import { imageExtras, toolCallShownArg } from '#lib/utils/index.ts';
+ import type { Snippet } from 'svelte';
+ import { fade } from 'svelte/transition';
+
+ interface Props {
+ sections: AgenticSection[];
+ open: boolean;
+ isStreaming: boolean;
+ executingToolCallId?: string | null;
+ /** Task start (ms since epoch) for the live timer, or null for none. */
+ elapsedStartedAt?: 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.
+ */
+ status?: string | null;
+ onToggle?: () => void;
+ children: Snippet;
+ }
+
+ let {
+ children,
+ elapsedStartedAt = null,
+ executingToolCallId,
+ isStreaming,
+ onToggle,
+ open,
+ sections,
+ status = null
+ }: Props = $props();
+
+ const activity = $derived(
+ status ||
+ describeToolActivity(sections, isStreaming, executingToolCallId, (toolName) =>
+ toolCallShownArg(settingsStore.config, toolName)
+ )
+ );
+ const summary = $derived(activity ?? summarizeToolCalls(sections));
+
+ const images = $derived(sections.flatMap((section) => imageExtras(section.toolResultExtras)));
+</script>
+
+<div class="tool-call-group min-w-0">
+ <CollapsibleContentBlock inlineChevron {onToggle} {open} shimmerTitle={Boolean(activity)}>
+ {#snippet titleSnippet()}
+ <span class="flex min-w-0 items-baseline gap-x-2">
+ <!-- collapsed, the summary steps back behind the answer; a live title keeps its shimmer -->
+ <span
+ class={['min-w-0 truncate', !open && !activity && 'font-normal text-muted-foreground']}
+ title={summary}>{summary}</span
+ >
+ </span>
+ {/snippet}
+
+ {#snippet titleSuffix()}
+ {#if elapsedStartedAt !== null}
+ <ToolCallElapsed startedAt={elapsedStartedAt} />
+ {/if}
+ {/snippet}
+
+ <div class="tool-call-list grid min-w-0">
+ {@render children()}
+ </div>
+ </CollapsibleContentBlock>
+
+ <!-- every image the calls produced, at their own proportions, under the summary
+ while the group is closed;
+ opening it shows each call with its own images, so the strip fades out -->
+ {#if images.length > 0 && !open}
+ <div transition:fade={{ duration: 150 }} class="tool-call-media">
+ <ScrollCarousel gapSize="2" variant={ScrollCarouselVariant.CENTER}>
+ {#each images as image, i (i)}
+ <button
+ aria-label={image.name ? `Preview ${image.name}` : 'Preview image'}
+ class="h-16 shrink-0 overflow-hidden rounded-md border border-border/60 transition-opacity hover:opacity-80"
+ onclick={() => mediaGalleryStore.show(image)}
+ type="button"
+ >
+ <img
+ alt=""
+ class="h-full w-auto max-w-60 object-cover"
+ loading="lazy"
+ src={image.base64Url}
+ />
+ </button>
+ {/each}
+ </ScrollCarousel>
+ </div>
+ {/if}
+</div>
+
+<style>
+ /* under the title text, past the indent the rows use */
+ .tool-call-media {
+ padding-top: 0.25rem;
+ }
+
+ .tool-call-list > :global(*) {
+ min-width: 0;
+ margin: 0 !important;
+ }
+
+ /* the group already draws the rule; a row's body only indents */
+ .tool-call-list :global([data-slot='collapsible-body']) {
+ border-left: 0;
+ padding-left: 0.5rem;
+ padding-bottom: 0;
+ }
+</style>
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallBlock.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallBlock.svelte
index cafb077e5..f8f9ee05b 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallBlock.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallBlock.svelte
@@ -1,22 +1,27 @@
<script generics="TMeta" lang="ts">
// Generic chrome shell shared by every per-tool block under
// `ChatMessageToolCall/`. Owns:
- // - the collapsible wrapper (defaults to CollapsibleContentBlock;
- // `exec_shell_command` swaps in CollapsibleTerminalBlock via the
- // `wrapper` prop);
- // - the icon, spinner state, and MCP favicon fallback chain;
+ // - the collapsible wrapper (CollapsibleContentBlock);
+ // - the running state, shown as a shimmering title;
// - the status subtitle pill.
+ // - the call's plain-language description, handed to the title.
// Components supply only their `meta`, a title snippet, and a body
// snippet - everything around them is this single source of truth.
- import { Loader2, Wrench } from '@lucide/svelte';
+ import {
+ describeToolCall,
+ formatToolCallLine,
+ isToolCallRunning
+ } from './parsers/tool-call-phrasing';
+ import { useToolCallElapsed } from './tool-call-elapsed';
+ import ToolCallElapsed from './ToolCallElapsed.svelte';
import { CollapsibleContentBlock } from '#lib/components/app/index.ts';
- import { ICON_CLASS_DEFAULT, ICON_CLASS_SPIN } from '#lib/constants/index.ts';
import { AgenticSectionType } from '#lib/enums/index.ts';
- import { mcpStore } from '#lib/stores/index.ts';
- import type { AgenticSection, ToolUiEntry } from '#lib/types/index.ts';
- import { getToolUi } from '#lib/utils/index.ts';
- import type { Component, Snippet } from 'svelte';
+ import { settingsStore } from '#lib/stores/index.ts';
+ import type { AgenticSection, ToolCallDescription } from '#lib/types/index.ts';
+ import { imageExtras, toolCallShownArg } from '#lib/utils/index.ts';
+ import type { Snippet } from 'svelte';
+ import { fade } from 'svelte/transition';
type ToolCallBlockMetaWithError = TMeta & { errorMessage?: string };
@@ -43,29 +48,16 @@
* `exec_shell_command`'s stdout feed).
*/
extraLiveStreaming?: boolean;
- /**
- * Swap the title-row icon for a spinning `Loader2` while the
- * spinner is showing. Only meaningful for tools where "live"
- * is interesting (e.g. exec_shell_command showing the in-flight
- * process). Other tools leave it off and render the spinner
- * inline within the body.
- */
- spinIconWhenActive?: boolean;
/**
* Treat an empty result as interrupted too. For tools that create
* their result message before running (`exec_shell_command`), so a
* stop mid-run leaves an empty result rather than none.
*/
emptyResultIsInterrupted?: boolean;
- /**
- * Wrapper component that renders the title row and the body
- * children. Defaults to CollapsibleContentBlock;
- * `exec_shell_command` uses CollapsibleTerminalBlock for its
- * terminal-style frame.
- */
- wrapper?: typeof CollapsibleContentBlock;
+ /** A fixed title; without it and without a snippet, the description is the title. */
title?: string;
- titleSnippet?: Snippet;
+ /** The title, given the call's description ( "Read a file", "Reading ..." ). */
+ titleSnippet?: Snippet<[ToolCallDescription]>;
onToggle?: () => void;
children: Snippet<[TMeta | null | undefined, ToolCallCtx]>;
}
@@ -79,10 +71,8 @@
onToggle,
open,
section,
- spinIconWhenActive = false,
title,
- titleSnippet,
- wrapper: Wrapper = CollapsibleContentBlock
+ titleSnippet: blockTitle
}: Props = $props();
const isPending = $derived(section.type === AgenticSectionType.TOOL_CALL_PENDING);
@@ -97,22 +87,6 @@
!showSpinner
);
- const toolUi: ToolUiEntry | null = $derived(getToolUi(section.toolName));
- const toolIcon: Component = $derived(
- spinIconWhenActive && showSpinner ? Loader2 : (toolUi?.icon ?? Wrench)
- );
- const toolIconClass = $derived(
- spinIconWhenActive && showSpinner ? ICON_CLASS_SPIN : ICON_CLASS_DEFAULT
- );
- // Drop the MCP favicon while the spinner is on so the title row
- // signals "in flight" without being overwritten by server branding.
- const mcpServerFavicon = $derived(
- showSpinner ? null : mcpStore.getServerFaviconForTool(section.toolName)
- );
- const iconUrl = $derived(
- showSpinner || (toolUi?.icon ?? null) || !mcpServerFavicon ? null : mcpServerFavicon
- );
-
// No subtitle while the call is in flight - the spinner already
// signals activity; only terminal states get a pill.
function subtitleFor(errorMessage?: string): string | undefined {
@@ -128,19 +102,65 @@
}
const subtitle = $derived(subtitleFor(meta?.errorMessage));
+ const elapsedStartFor = useToolCallElapsed();
+ const elapsedStart = $derived(elapsedStartFor(section.toolCallId));
+
+ // images the call produced, as tiny thumbnails beside its title while the
+ // row is closed; opened, its body shows them in full
+ const images = $derived(imageExtras(section.toolResultExtras));
+
+ // what the call did, or is doing while it runs; described once here for
+ // every per-tool title
+ const phrase = $derived(
+ describeToolCall(
+ section.toolName,
+ section.toolArgs,
+ extraLiveStreaming || isToolCallRunning(section, isStreaming),
+ toolCallShownArg(settingsStore.config, section.toolName)
+ )
+ );
</script>
-<Wrapper
+<CollapsibleContentBlock
class="my-2"
- icon={toolIcon}
- iconClass={toolIconClass}
- {iconUrl}
+ inlineChevron
{onToggle}
{open}
+ shimmerTitle={showSpinner}
{subtitle}
- {title}
- {titleSnippet}
>
+ {#snippet titleSnippet()}
+ {#if blockTitle}
+ {@render blockTitle(phrase)}
+ {:else}
+ {title ?? formatToolCallLine(phrase)}
+ {/if}
+ {/snippet}
+
+ {#snippet titleSuffix()}
+ {#if elapsedStart !== null}
+ <ToolCallElapsed startedAt={elapsedStart} />
+ {/if}
+
+ {#if images.length > 0 && !open}
+ <span
+ transition:fade={{ duration: 150 }}
+ aria-label="{images.length} {images.length === 1 ? 'image' : 'images'}"
+ class="ml-1 inline-flex items-center gap-1 align-middle"
+ role="img"
+ >
+ {#each images as image, i (i)}
+ <img
+ alt=""
+ class="h-5 w-auto max-w-10 rounded-sm border border-border/60 object-cover"
+ loading="lazy"
+ src={image.base64Url}
+ />
+ {/each}
+ </span>
+ {/if}
+ {/snippet}
+
{@render children(meta, {
isCodeStreaming,
isInterrupted,
@@ -148,4 +168,4 @@
isStreaming,
isStreamingCall
})}
-</Wrapper>
+</CollapsibleContentBlock>
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
new file mode 100644
index 000000000..b83c74933
--- /dev/null
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallElapsed.svelte
@@ -0,0 +1,36 @@
+<script lang="ts">
+ // Time since the task started, ticking once a second.
+
+ import { MS_PER_SECOND, SECONDS_PER_MINUTE } from '#lib/constants/index.ts';
+ import { formatPerformanceTime } from '#lib/utils/index.ts';
+
+ interface Props {
+ /** Task start (ms since epoch). */
+ startedAt: number;
+ }
+
+ let { startedAt }: Props = $props();
+
+ let now = $state(Date.now());
+
+ $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)
+ );
+</script>
+
+<span
+ class="text-caption font-normal text-muted-foreground tabular-nums"
+ title="Time since the task started"
+>
+ {label}
+</span>
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallTitle.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallTitle.svelte
new file mode 100644
index 000000000..c16e0cdd8
--- /dev/null
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallTitle.svelte
@@ -0,0 +1,32 @@
+<script lang="ts">
+ // The title most tool rows share: what the call did, in muted text, then
+ // what it acted on in monospace, then anything a tool adds after it.
+
+ import type { Snippet } from 'svelte';
+
+ interface Props {
+ label: string;
+ /** What the call acted on, e.g. a file name or a search term. */
+ target?: string;
+ /** Tooltip for the target, e.g. the full path behind a short one. */
+ targetTitle?: string;
+ /** Extras after the target, e.g. a line range or diff stats. */
+ children?: Snippet;
+ }
+
+ let { children, label, target, targetTitle }: Props = $props();
+</script>
+
+<span class="flex min-w-0 flex-wrap items-baseline gap-x-1">
+ <span class="shrink-0 text-muted-foreground">{label}</span>
+
+ {#if target || children}
+ <span class="flex min-w-0 items-baseline gap-1.5">
+ {#if target}
+ <span class="min-w-0 truncate font-mono" title={targetTitle ?? target}>{target}</span>
+ {/if}
+
+ {@render children?.()}
+ </span>
+ {/if}
+</span>
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/edit-file.ts b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/edit-file.ts
index 006ea186f..72c1306a7 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/edit-file.ts
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/edit-file.ts
@@ -11,14 +11,14 @@ import {
parseToolArgs
} from './_shared';
import { TOOL_ARG_PATH_KEYS } from '#lib/constants/index.ts';
-import { BuiltInTool } from '#lib/enums/index.ts';
+import { BuiltInTool, DiffLineKind } from '#lib/enums/index.ts';
import type {
AgenticSection,
EditFileEdit,
EditFileMeta,
EditFileTitleMeta
} from '#lib/types/index.ts';
-import { tryParseToolResultObject } from '#lib/utils/index.ts';
+import { computeLineDiff, memoizeBounded, tryParseToolResultObject } from '#lib/utils/index.ts';
export function parseEditFileMeta(section: AgenticSection): EditFileMeta | null {
const args = parseToolArgs(BuiltInTool.SERVER_EDIT_FILE, section, { partial: true });
@@ -112,3 +112,38 @@ export function parseEditFileTitleMeta(section: AgenticSection): EditFileTitleMe
return { editsApplied, errorMessage, fileName, filePath, resultMessage };
}
+
+/**
+ * Lines added and removed by a finished `edit_file` call, or null when it
+ * failed or changed nothing. Memoized per call: the title that shows it
+ * renders for every row, while sections are rebuilt on every streamed chunk.
+ * The id names the call, so a call without one is computed uncached; the
+ * sizes guard against an id that another conversation reuses.
+ */
+export const editFileDiffStats = memoizeBounded(
+ buildEditFileDiffStats,
+ (section) =>
+ section.toolCallId
+ ? `${section.toolCallId}:${section.toolArgs?.length ?? 0}:${section.toolResult?.length ?? 0}`
+ : null,
+ 64
+);
+
+function buildEditFileDiffStats(
+ section: AgenticSection
+): { added: number; removed: number } | null {
+ const meta = parseEditFileMeta(section);
+
+ if (!meta || meta.errorMessage || meta.edits.length === 0) return null;
+
+ const stats = { added: 0, removed: 0 };
+
+ for (const edit of meta.edits) {
+ for (const line of computeLineDiff(edit.oldText, edit.newText)) {
+ if (line.kind === DiffLineKind.ADD) stats.added++;
+ else if (line.kind === DiffLineKind.REMOVE) stats.removed++;
+ }
+ }
+
+ return stats;
+}
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/tool-call-phrasing.ts b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/tool-call-phrasing.ts
new file mode 100644
index 000000000..8792bc90a
--- /dev/null
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/tool-call-phrasing.ts
@@ -0,0 +1,445 @@
+// Plain-language lines for tool calls: what one call did ("Read a file
+// sheet_new.jpg"), what it is doing now ("Reading package.json") and what
+// a run of calls did ("Ran 3 commands, read 2 files"). A call that has the
+// arg the settings pick (`description` by default) shows it as the model
+// wrote it. Otherwise built-in tools use TOOL_CALL_PHRASING, and MCP and
+// unknown tools read as "Used <tool>" with their main argument.
+
+import { extractToolArgString, fileNameFromPath } from './_shared';
+import {
+ TOOL_ARG_PATH_KEYS,
+ TOOL_CALL_MAIN_ARG_KEYS,
+ TOOL_CALL_PHRASING,
+ TOOL_CALL_SHOWN_ARG_DEFAULT,
+ TOOL_CALL_SIMPLE_ARG_MAX_CHARS,
+ TOOL_CALL_SUMMARY,
+ TOOL_CALL_TARGET_MAX_CHARS,
+ TOOL_CALL_THINKING_LABEL,
+ TOOL_SEARCH_LOAD_PHRASING,
+ TOOL_SEARCH_PHRASING_NAME,
+ TOOL_SEARCH_PHRASING_SELECT_PREFIX,
+ TOOL_SEARCH_QUERY_PHRASING,
+ WEB_SEARCH_PHRASING
+} from '#lib/constants/index.ts';
+import { AgenticSectionType, BuiltInTool, ToolCallSummaryKind } from '#lib/enums/index.ts';
+import type { AgenticSection, ToolCallDescription, ToolCallPhrasing } from '#lib/types/index.ts';
+import { isWebSearchToolName, memoizeBounded, parsePartialJsonArgs } from '#lib/utils/index.ts';
+
+/** How many results each cache below holds. */
+const CACHE_MAX_SIZE = 256;
+/** Args longer than this ( whole files ) are not worth holding as cache keys. */
+const CACHE_MAX_ARGS_CHARS = 2000;
+
+type ToolArgField = { label: string; value: string };
+
+function shorten(text: string): string {
+ const oneLine = text.replace(/\s+/g, ' ').trim();
+
+ return oneLine.length > TOOL_CALL_TARGET_MAX_CHARS
+ ? `${oneLine.slice(0, TOOL_CALL_TARGET_MAX_CHARS - 3)}...`
+ : oneLine;
+}
+
+function stringArg(args: Record<string, unknown> | null, key: string): string | undefined {
+ const value = args?.[key];
+
+ return typeof value === 'string' && value.trim() ? value : undefined;
+}
+
+function genericMainArg(args: Record<string, unknown> | null): string | undefined {
+ if (!args) return undefined;
+
+ for (const key of TOOL_CALL_MAIN_ARG_KEYS) {
+ const value = stringArg(args, key);
+
+ if (value) return value;
+ }
+
+ for (const value of Object.values(args)) {
+ if (typeof value === 'number') return String(value);
+
+ if (typeof value === 'string' && value.trim() && value.length <= TOOL_CALL_TARGET_MAX_CHARS) {
+ return value;
+ }
+ }
+
+ return undefined;
+}
+
+function genericPhrasing(toolName: string): ToolCallPhrasing {
+ return {
+ object: toolName,
+ past: 'Used',
+ present: 'Using',
+ summary: ToolCallSummaryKind.OTHER,
+ targetObject: toolName
+ };
+}
+
+interface ResolvedCall {
+ phrasing: ToolCallPhrasing;
+ target?: string;
+ count?: number;
+}
+
+function resolveCall(toolName: string, toolArgs: string): ResolvedCall {
+ // write_file and edit_file args hold whole files: read the path with a
+ // targeted match instead of parsing the blob
+ if (
+ toolName === BuiltInTool.SERVER_READ_FILE ||
+ toolName === BuiltInTool.SERVER_WRITE_FILE ||
+ toolName === BuiltInTool.SERVER_EDIT_FILE ||
+ toolName === BuiltInTool.BROWSER_READ_MEDIA
+ ) {
+ const path =
+ extractToolArgString(toolArgs, TOOL_ARG_PATH_KEYS) ??
+ stringArg(parsePartialJsonArgs(toolArgs), 'path');
+
+ return { phrasing: TOOL_CALL_PHRASING[toolName], target: fileNameFromPath(path) };
+ }
+
+ const args = toolArgs ? parsePartialJsonArgs(toolArgs) : null;
+
+ if (toolName === BuiltInTool.SERVER_EXEC_SHELL_COMMAND) {
+ // the targeted match keeps the command in the line while a later arg
+ // is still streaming and the JSON does not parse
+ return {
+ phrasing: TOOL_CALL_PHRASING[toolName],
+ target: stringArg(args, 'command') ?? extractToolArgString(toolArgs, ['command'])
+ };
+ }
+
+ switch (toolName) {
+ case BuiltInTool.SERVER_GREP_SEARCH:
+ return { phrasing: TOOL_CALL_PHRASING[toolName], target: stringArg(args, 'pattern') };
+
+ case BuiltInTool.SERVER_FILE_GLOB_SEARCH: {
+ const include = stringArg(args, 'include');
+
+ return {
+ phrasing: TOOL_CALL_PHRASING[toolName],
+ target: include && include !== '**' ? include : undefined
+ };
+ }
+
+ case BuiltInTool.BROWSER_SEARCH_CHATS: {
+ const matches = Array.isArray(args?.by_matches)
+ ? args.by_matches.filter((m): m is string => typeof m === 'string' && m.trim() !== '')
+ : [];
+
+ return { phrasing: TOOL_CALL_PHRASING[toolName], target: matches.join(', ') || undefined };
+ }
+
+ case TOOL_SEARCH_PHRASING_NAME: {
+ const query = stringArg(args, 'query')?.trim();
+
+ if (query?.startsWith(TOOL_SEARCH_PHRASING_SELECT_PREFIX)) {
+ const names = query
+ .slice(TOOL_SEARCH_PHRASING_SELECT_PREFIX.length)
+ .split(',')
+ .map((name) => name.trim())
+ .filter(Boolean);
+
+ return {
+ count: Math.max(names.length, 1),
+ phrasing: TOOL_SEARCH_LOAD_PHRASING,
+ target: names.join(', ') || undefined
+ };
+ }
+
+ return { phrasing: TOOL_SEARCH_QUERY_PHRASING, target: query };
+ }
+ }
+
+ if (isWebSearchToolName(toolName)) {
+ return { phrasing: WEB_SEARCH_PHRASING, target: stringArg(args, 'query') };
+ }
+
+ const known = TOOL_CALL_PHRASING[toolName];
+
+ if (known) return { phrasing: known };
+
+ return { phrasing: genericPhrasing(toolName), target: genericMainArg(args) };
+}
+
+/** An arg name the settings can pick: a plain key, so it is safe in a pattern. */
+const SHOWN_ARG_PATTERN = /^[\w-]+$/;
+
+/**
+ * The value of the arg a call's line shows, when the call has it. Whole-file
+ * args are not parsed for it: the targeted match reads it instead.
+ */
+function shownArgValue(toolArgs: string, shownArg: string | null): string | undefined {
+ if (!shownArg || !toolArgs || !SHOWN_ARG_PATTERN.test(shownArg)) return undefined;
+
+ const value =
+ toolArgs.length <= CACHE_MAX_ARGS_CHARS
+ ? stringArg(parsePartialJsonArgs(toolArgs), shownArg)
+ : extractToolArgString(toolArgs, [shownArg]);
+
+ return value?.trim() || undefined;
+}
+
+/**
+ * Describe one tool call as a short sentence, in the past tense once it is
+ * done and the present tense while `running`. `shownArg` names the arg
+ * shown instead when the call has it ( null for none ).
+ */
+export function describeToolCall(
+ toolName: string | undefined,
+ toolArgs: string | undefined,
+ running = false,
+ shownArg: string | null = TOOL_CALL_SHOWN_ARG_DEFAULT
+): ToolCallDescription {
+ return describeCached(toolName || 'a tool', toolArgs ?? '', running, shownArg ?? '');
+}
+
+// Sections are rebuilt on every streamed chunk, so the same finished call is
+// described again and again: remember the answer for its args. Every caller
+// of one call reads the same frozen object, so a title cannot edit the line
+// out for the others.
+const describeCached = memoizeBounded(
+ (name: string, args: string, running: boolean, shownArg: string) =>
+ Object.freeze(buildDescription(name, args, running, shownArg || null)),
+ (name, args, running, shownArg) =>
+ args.length <= CACHE_MAX_ARGS_CHARS
+ ? `${running ? 1 : 0}\0${shownArg}\0${name}\0${args}`
+ : null,
+ CACHE_MAX_SIZE
+);
+
+function buildDescription(
+ name: string,
+ args: string,
+ running: boolean,
+ shownArg: string | null
+): ToolCallDescription {
+ const { count = 1, phrasing, target } = resolveCall(name, args);
+ const shown = shownArgValue(args, shownArg);
+ // an arg the row already shows as its target ( a shell command ) would
+ // only repeat it
+ const described = shown && shown !== target?.trim() ? shown : undefined;
+
+ if (described) {
+ return {
+ count,
+ described: true,
+ // shown as the model wrote it: rewriting its tense by rule mangles
+ // anything that does not start with a plain verb
+ label: shorten(described).replace(/[.\s]+$/, ''),
+ quoted: false,
+ summary: phrasing.summary
+ };
+ }
+
+ const verb = running ? phrasing.present : phrasing.past;
+ const shortTarget = target ? shorten(target) : undefined;
+ const object = shortTarget ? phrasing.targetObject : phrasing.object;
+
+ return {
+ count,
+ label: object ? `${verb} ${object}` : verb,
+ quoted: Boolean(phrasing.quoteTarget && shortTarget),
+ summary: phrasing.summary,
+ target: shortTarget
+ };
+}
+
+/** One line of plain text for a description, e.g. `Searched for 'issue'`. */
+export function formatToolCallLine(description: ToolCallDescription): string {
+ if (!description.target) return description.label;
+
+ const target = description.quoted ? `'${description.target}'` : description.target;
+
+ return `${description.label} ${target}`;
+}
+
+export function isToolCallSection(section: AgenticSection): boolean {
+ return (
+ section.type === AgenticSectionType.TOOL_CALL ||
+ section.type === AgenticSectionType.TOOL_CALL_PENDING ||
+ section.type === AgenticSectionType.TOOL_CALL_STREAMING
+ );
+}
+
+/** True while the call has no result yet and the reply is still streaming. */
+export function isToolCallRunning(section: AgenticSection, isStreaming: boolean): boolean {
+ return (
+ isStreaming &&
+ (section.type === AgenticSectionType.TOOL_CALL_PENDING ||
+ section.type === AgenticSectionType.TOOL_CALL_STREAMING)
+ );
+}
+
+/**
+ * Summarize a run of tool calls, e.g. "Ran 3 commands, read 2 files".
+ * Kinds keep the order they first appear in; other tools come last.
+ */
+export function summarizeToolCalls(sections: readonly AgenticSection[]): string {
+ const counts = new Map<ToolCallSummaryKind, number>();
+
+ for (const section of sections) {
+ if (!isToolCallSection(section)) continue;
+
+ const { count, summary } = describeToolCall(section.toolName, section.toolArgs);
+
+ counts.set(summary, (counts.get(summary) ?? 0) + count);
+ }
+
+ const other = counts.get(ToolCallSummaryKind.OTHER);
+
+ if (other !== undefined) {
+ counts.delete(ToolCallSummaryKind.OTHER);
+ counts.set(ToolCallSummaryKind.OTHER, other);
+ }
+
+ const clauses = [...counts].map(([kind, n]) => TOOL_CALL_SUMMARY[kind](n));
+ const text = clauses.join(', ');
+
+ return text.charAt(0).toUpperCase() + text.slice(1);
+}
+
+/**
+ * What a run of calls is doing now, in user words ("Running a command",
+ * "Thinking"): the model thinking at its end, or the last call still
+ * running; null when neither is.
+ */
+export function describeToolActivity(
+ sections: readonly AgenticSection[],
+ isStreaming: boolean,
+ executingToolCallId?: string | null,
+ shownArgFor: (toolName: string | undefined) => string | null = () => TOOL_CALL_SHOWN_ARG_DEFAULT
+): string | null {
+ // the model thinking at the end of the run, between calls or before its answer
+ if (isStreaming && sections.at(-1)?.type === AgenticSectionType.REASONING_PENDING) {
+ return TOOL_CALL_THINKING_LABEL;
+ }
+
+ for (let i = sections.length - 1; i >= 0; i--) {
+ const section = sections[i];
+ const executing =
+ section.toolCallId !== undefined && section.toolCallId === executingToolCallId;
+
+ if (executing || isToolCallRunning(section, isStreaming)) {
+ return formatToolCallLine(
+ describeToolCall(section.toolName, section.toolArgs, true, shownArgFor(section.toolName))
+ );
+ }
+ }
+
+ return null;
+}
+
+/**
+ * Tool args as labelled fields when every value is a short, one-line
+ * scalar; null when the args need the JSON view instead. Memoized like
+ * describeToolCall: the row that shows them re-renders on every chunk.
+ */
+export function simpleToolArgFields(toolArgs: string | undefined): ToolArgField[] | null {
+ return toolArgs ? argFieldsCached(toolArgs) : null;
+}
+
+const argFieldsCached = memoizeBounded(
+ buildSimpleToolArgFields,
+ (toolArgs) => (toolArgs.length <= CACHE_MAX_ARGS_CHARS ? toolArgs : null),
+ CACHE_MAX_SIZE
+);
+
+function buildSimpleToolArgFields(toolArgs: string): ToolArgField[] | null {
+ let parsed: unknown;
+
+ try {
+ parsed = JSON.parse(toolArgs);
+ } catch {
+ return null;
+ }
+
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
+
+ const entries = Object.entries(parsed as Record<string, unknown>);
+
+ if (entries.length === 0) return null;
+
+ const fields: ToolArgField[] = [];
+
+ for (const [key, value] of entries) {
+ if (value !== null && typeof value === 'object') return null;
+
+ const text = String(value);
+
+ if (text.length > TOOL_CALL_SIMPLE_ARG_MAX_CHARS || text.includes('\n')) return null;
+
+ fields.push({ label: humanizeArgKey(key), value: text });
+ }
+
+ return fields;
+}
+
+/** `max_results` / `maxResults` -> `Max results`. */
+export function humanizeArgKey(key: string): string {
+ const words = key
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
+ .replace(/[_-]+/g, ' ')
+ .trim()
+ .toLowerCase();
+
+ return words.charAt(0).toUpperCase() + words.slice(1);
+}
+
+export function isReasoningSection(section: AgenticSection): boolean {
+ return (
+ section.type === AgenticSectionType.REASONING ||
+ section.type === AgenticSectionType.REASONING_PENDING
+ );
+}
+
+/**
+ * Split section positions into single items and runs of tool work, e.g.
+ * [0, [1, 2, 3], 4]. A run is the calls and all the reasoning around them,
+ * up to the next text, so the answer follows the work as one row: it is
+ * grouped once it holds `minCalls` calls, or one call with reasoning beside
+ * it. Reasoning with no call in reach, and text, stay apart.
+ */
+export function groupToolCallRuns(
+ sections: readonly AgenticSection[],
+ indices: readonly number[],
+ minCalls: number
+): (number | number[])[] {
+ const items: (number | number[])[] = [];
+
+ let run: number[] = [];
+ let calls = 0;
+ // reasoning seen since the last call: it ends the run if text follows,
+ // and leads into it if another call does
+ let thinking: number[] = [];
+
+ const flush = () => {
+ const whole = [...run, ...thinking];
+
+ if (calls >= minCalls || (calls > 0 && whole.length > calls)) items.push(whole);
+ else items.push(...whole);
+
+ run = [];
+ thinking = [];
+ calls = 0;
+ };
+
+ for (const index of indices) {
+ const section = sections[index];
+
+ if (isToolCallSection(section)) {
+ run.push(...thinking, index);
+ thinking = [];
+ calls++;
+ } else if (isReasoningSection(section)) {
+ thinking.push(index);
+ } else {
+ flush();
+ items.push(index);
+ }
+ }
+
+ flush();
+
+ return items;
+}
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
new file mode 100644
index 000000000..89a5fd2eb
--- /dev/null
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/tool-call-elapsed.ts
@@ -0,0 +1,28 @@
+// The live task 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.
+
+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. */
+type ElapsedTarget = { startedAt: number; toolCallId: string } | null;
+
+export function setToolCallElapsedContext(getTarget: () => ElapsedTarget): void {
+ setContext(KEY, getTarget);
+}
+
+/**
+ * Call during component init. Returns a reader of the task start for a call:
+ * its start when that call shows the timer, null otherwise.
+ */
+export function useToolCallElapsed(): (toolCallId: string | undefined) => number | null {
+ const getTarget = getContext<(() => ElapsedTarget) | undefined>(KEY);
+
+ return (toolCallId) => {
+ const target = getTarget?.();
+
+ return target && target.toolCallId === toolCallId ? target.startedAt : null;
+ };
+}
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUser.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUser.svelte
index 1101287c7..4c4df7ba9 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUser.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUser.svelte
@@ -6,6 +6,7 @@
ChatMessageStatistics,
ChatMessageUserBubble
} from '#lib/components/app/chat/index.ts';
+ import { SETTINGS_KEYS } from '#lib/constants/index.ts';
import { getChatMessageEditContext } from '#lib/contexts/index.ts';
import { ChatMessageStatisticsMode, MessageRole } from '#lib/enums/index.ts';
import { useProcessingState } from '#lib/hooks/use-processing-state.svelte.ts';
@@ -50,6 +51,12 @@
};
});
+ // the latest exchange keeps its stats and actions in view; earlier messages
+ // show them on hover, and the setting can keep their stats in view as well
+ let hidesStatsUntilHover = $derived(
+ !isLastUserMessage && !currentConfig[SETTINGS_KEYS.ALWAYS_SHOW_MESSAGE_STATS]
+ );
+
let showStoredReadingStats = $derived(
Boolean(currentConfig.showMessageStats) && storedReadingStats !== null
);
@@ -67,7 +74,7 @@
<div
aria-label="User message with actions"
- class="chat-message-user group flex flex-col items-end gap-3 md:gap-2 {className}"
+ class="chat-message-user group flex flex-col items-end gap-2 {className}"
role="group"
>
{#if editCtx.isEditing}
@@ -83,7 +90,12 @@
{#if showStoredReadingStats}
<!-- Reading stats sourced from the assistant message that followed this turn -->
- <div class="info my-2 grid w-full justify-items-end gap-4 tabular-nums">
+ <div
+ class={[
+ 'info grid w-full justify-items-end gap-4 tabular-nums',
+ hidesStatsUntilHover && 'message-meta'
+ ]}
+ >
<div
class="inline-flex flex-wrap items-start justify-end gap-2 text-caption text-muted-foreground"
>
@@ -96,8 +108,10 @@
</div>
{:else if showLiveReadingStats}
{@const liveStats = processingState.getLiveProcessingStats()}
- {#if liveStats}
- <div class="info my-2 grid w-full justify-items-end gap-4 tabular-nums">
+ <!-- The row's room is there from the moment the prompt is sent, so the
+ reply below does not get pushed down when the first numbers arrive. -->
+ <div class="info grid min-h-5.5 w-full justify-items-end gap-4 tabular-nums">
+ {#if liveStats}
<div
class="inline-flex flex-wrap items-start justify-end gap-2 text-caption text-muted-foreground"
>
@@ -108,12 +122,12 @@
promptTokens={liveStats.tokensProcessed}
/>
</div>
- </div>
- {/if}
+ {/if}
+ </div>
{/if}
{#if message.timestamp}
- <div class="max-w-4/5">
+ <div class={['max-w-4/5', !isLastUserMessage && 'message-meta']}>
<ChatMessageActionIcons actionsPosition="right" justify="end" />
</div>
{/if}
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUserBubble.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUserBubble.svelte
index c4f823886..4419454ca 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUserBubble.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUserBubble.svelte
@@ -56,6 +56,7 @@
<div class="mb-2 max-w-4/5">
<ChatAttachmentsList
{attachments}
+ conversationGallery
imageHeight="max-h-40"
imageWidth="w-auto max-w-full"
readonly
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUserPending.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUserPending.svelte
index 73ef9091e..1b911ff9b 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUserPending.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUserPending.svelte
@@ -34,7 +34,7 @@
<div
aria-label="Pending user message"
- class="group flex flex-col items-end gap-3 transition-opacity hover:opacity-80 md:gap-2 {className} sticky bottom-32"
+ class="group flex flex-col items-end gap-3 transition-opacity hover:opacity-80 md:gap-2 {className}"
role="group"
>
{#if editCtx.isEditing}
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCard.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCard.svelte
index 452effa1e..796f2a4d2 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCard.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCard.svelte
@@ -5,10 +5,12 @@
interface Props {
icon: Component<{ class?: string }>;
message: Snippet;
+ /** What the decision is about, shown in full between the question and the actions. */
+ detail?: Snippet;
actions: Snippet;
}
- let { actions, icon: IconComponent, message }: Props = $props();
+ let { actions, detail, icon: IconComponent, message }: Props = $props();
</script>
<div class="my-2 rounded-lg border border-(--action-card-border) bg-card p-3">
@@ -20,6 +22,12 @@
</span>
</div>
+ {#if detail}
+ <div class="min-w-0">
+ {@render detail()}
+ </div>
+ {/if}
+
<div class="flex flex-wrap items-center gap-2">
{@render actions()}
</div>
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardPermissionRequest.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardPermissionRequest.svelte
index 42561a63b..9e50951e3 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardPermissionRequest.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardPermissionRequest.svelte
@@ -12,10 +12,15 @@
interface Props {
toolName: string;
serverLabel: string;
+ /**
+ * The shell command the call would run, shown in full: the trace row may
+ * show the model's own description of it, which is not what gets executed.
+ */
+ command?: string;
onDecision: (decision: ToolPermissionDecision) => void;
}
- let { onDecision, serverLabel, toolName }: Props = $props();
+ let { command, onDecision, serverLabel, toolName }: Props = $props();
</script>
<ChatMessageActionCard icon={ShieldQuestion}>
@@ -24,6 +29,13 @@
from <span class="font-semibold">{serverLabel}</span>{/if}?
{/snippet}
+ {#snippet detail()}
+ {#if command}
+ <pre
+ class="mb-3 max-h-40 overflow-auto rounded-md bg-(--surface-code) px-3 py-2 font-mono text-caption whitespace-pre-wrap break-words">{command}</pre>
+ {/if}
+ {/snippet}
+
{#snippet actions()}
<DropdownMenu.Root>
<ButtonGroup.Root>
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
new file mode 100644
index 000000000..f0e7bffde
--- /dev/null
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte
@@ -0,0 +1,410 @@
+<script lang="ts">
+ import ChatMessageToolCallBlock from './ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlock.svelte';
+ import ChatMessageToolCallGroup from './ChatMessage/ChatMessageToolCall/ChatMessageToolCallGroup.svelte';
+ import { parseExecShellCommandMeta } from './ChatMessage/ChatMessageToolCall/parsers/exec-shell-command';
+ import {
+ groupToolCallRuns,
+ isToolCallSection
+ } from './ChatMessage/ChatMessageToolCall/parsers/tool-call-phrasing';
+ import { setToolCallElapsedContext } from './ChatMessage/ChatMessageToolCall/tool-call-elapsed';
+ import ChatMessageReasoningBlock from './ChatMessageReasoningBlock.svelte';
+ import {
+ ChatMessageActionCardContinueRequest,
+ ChatMessageActionCardPermissionRequest,
+ ChatMessageAssistantProcessingInfo,
+ ChatMessageStatistics,
+ MarkdownContent
+ } from '#lib/components/app/index.ts';
+ import { REPLY_STATUS_FALLBACK, TOOL_CALL_GROUP_MIN_CALLS } from '#lib/constants/index.ts';
+ import {
+ AgenticSectionType,
+ ChatMessageStatsView,
+ ToolPermissionDecision
+ } from '#lib/enums/index.ts';
+ import { agenticStore, conversationsStore, settingsStore } from '#lib/stores/index.ts';
+ import type {
+ AgenticSection,
+ ChatMessageAgenticTimings,
+ ChatMessageAgenticTurnStats,
+ DatabaseMessage
+ } from '#lib/types/index.ts';
+ import {
+ deriveAgenticSections,
+ isSectionExpandedByDefault,
+ showsReplyStatus
+ } from '#lib/utils/index.ts';
+
+ interface Props {
+ message: DatabaseMessage;
+ toolMessages?: DatabaseMessage[];
+ isStreaming?: boolean;
+ isLastAssistantMessage?: boolean;
+ /**
+ * What the server is doing while this reply waits on it ( "Processing
+ * 40%" ), empty while tokens stream, null when the reply is not live.
+ */
+ statusText?: string | null;
+ }
+
+ let {
+ isLastAssistantMessage = false,
+ isStreaming: isChatStreaming = false,
+ message,
+ statusText = null,
+ toolMessages = []
+ }: Props = $props();
+
+ // The chat-level streaming flag is shared by every message; only the last
+ // assistant message is actually live, so earlier ones must not keep their
+ // unresolved tool calls spinning while a newer reply streams.
+ const isStreaming = $derived(isChatStreaming && isLastAssistantMessage);
+
+ let expandedStates: Record<number, boolean> = $state({});
+ // keyed by the flat index of the group's first call
+ let groupExpandedStates: Record<number, boolean> = $state({});
+
+ const showThoughtInProgress = $derived(Boolean(settingsStore.config.showThoughtInProgress));
+ const showToolCallInProgress = $derived(Boolean(settingsStore.config.showToolCallInProgress));
+ const alwaysShowToolCallContent = $derived(
+ Boolean(settingsStore.config.alwaysShowToolCallContent)
+ );
+ const showMessageStats = $derived(Boolean(settingsStore.config.showMessageStats));
+ const showAgenticTurnStats = $derived(
+ showMessageStats && Boolean(settingsStore.config.showAgenticTurnStats)
+ );
+
+ const hasReasoningError = $derived(
+ isLastAssistantMessage ? !!agenticStore.getLastError(message.convId) : false
+ );
+
+ const pendingPermission = $derived(
+ isStreaming ? agenticStore.getPendingPermissionRequest(message.convId) : null
+ );
+
+ // dismissal applies to the request object, so the next request ( new
+ // identity ) shows the card again without any reset bookkeeping
+ let dismissedPermission: typeof pendingPermission = $state(null);
+
+ const visiblePermission = $derived(
+ pendingPermission && dismissedPermission !== pendingPermission ? pendingPermission : null
+ );
+
+ function handlePermission(decision: ToolPermissionDecision) {
+ dismissedPermission = pendingPermission;
+ agenticStore.resolvePermission(message.convId, decision);
+ }
+
+ const pendingContinue = $derived(
+ isStreaming ? agenticStore.getPendingContinueRequest(message.convId) : false
+ );
+
+ let continueDismissed = $state(false);
+
+ // the continue request is a plain boolean, so there is no identity to
+ // compare against; clear the dismissal whenever no request is pending so
+ // the next one starts from a clean state
+ $effect(() => {
+ if (!pendingContinue) {
+ continueDismissed = false;
+ }
+ });
+
+ const showContinue = $derived(Boolean(pendingContinue) && !continueDismissed);
+
+ function handleContinue(shouldContinue: boolean) {
+ continueDismissed = true;
+ agenticStore.resolveContinue(message.convId, shouldContinue);
+ }
+
+ const sections = $derived(deriveAgenticSections(message, toolMessages, [], isStreaming));
+
+ // The command the pending call would run, for the permission card: the gate
+ // names the call it is asking about, so an earlier call of the same tool
+ // whose result has not landed yet cannot be mistaken for it.
+ const pendingCommand = $derived.by(() => {
+ if (!visiblePermission) return undefined;
+
+ const pending = sections.find((section) => section.toolCallId === visiblePermission.toolCallId);
+
+ return pending ? parseExecShellCommandMeta(pending)?.command : undefined;
+ });
+
+ const currentlyExecutingToolCallId = $derived(
+ isStreaming ? agenticStore.getExecutingToolCallId(message.convId) : null
+ );
+
+ // Cwd the agentic loop passes to tool calls in this conversation; the exec
+ // block shows it until the result message persists the real one.
+ const conversationCwd = $derived(
+ conversationsStore.activeConversation?.id === message.convId
+ ? conversationsStore.activeConversation?.cwd
+ : undefined
+ );
+
+ /** A single section by its index, or a run of them shown as one group row. */
+ type TraceItem = number | number[];
+
+ // The rows of the reply, as one list per turn. Per-turn stats sit between
+ // turns, so with them on each turn groups its own calls. Without them a
+ // run of calls spans turns ( a model that thinks before each call ) and
+ // the reply is a single list.
+ const turns: TraceItem[][] = $derived.by(() => {
+ if (!showAgenticTurnStats) {
+ return [
+ groupToolCallRuns(
+ sections,
+ sections.map((_, i) => i),
+ TOOL_CALL_GROUP_MIN_CALLS
+ )
+ ];
+ }
+
+ const result: TraceItem[][] = [];
+
+ let indices: number[] = [];
+ let prevWasTool = false;
+
+ const pushTurn = () =>
+ result.push(groupToolCallRuns(sections, indices, TOOL_CALL_GROUP_MIN_CALLS));
+
+ for (let i = 0; i < sections.length; i++) {
+ const isTool = isToolCallSection(sections[i]);
+
+ // a turn ends where its tool calls do
+ if (!isTool && prevWasTool && indices.length > 0) {
+ pushTurn();
+ indices = [];
+ }
+
+ indices.push(i);
+ prevWasTool = isTool;
+ }
+
+ if (indices.length > 0) pushTurn();
+
+ return result;
+ });
+
+ // a single turn has no stats of its own to show
+ const showTurnStats = $derived(showAgenticTurnStats && turns.length > 1);
+
+ 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);
+
+ setToolCallElapsedContext(() => {
+ if (taskStartedAt === null || lastItem === undefined || Array.isArray(lastItem)) return null;
+
+ const toolCallId = sections[lastItem]?.toolCallId;
+
+ return toolCallId ? { startedAt: taskStartedAt, toolCallId } : null;
+ });
+
+ const lastToolIndex = $derived(sections.findLastIndex((section) => isToolCallSection(section)));
+
+ // The status row shows only while nothing else in the reply is moving: a
+ // running row, a permission card or streaming text already says what is
+ // happening. It sits where the next row will land, so that row replaces
+ // it and the stats below stay put.
+ const showStatus = $derived(
+ currentlyExecutingToolCallId === null &&
+ !visiblePermission &&
+ !showContinue &&
+ showsReplyStatus(statusText, sections.at(-1), isStreaming)
+ );
+
+ // a group closing the reply carries the status as its live title, so the
+ // waiting reads as part of the work instead of a line of its own
+ const statusInGroup = $derived(showStatus && Array.isArray(lastItem));
+
+ function isExecutingCall(section: AgenticSection): boolean {
+ return section.toolCallId !== undefined && section.toolCallId === currentlyExecutingToolCallId;
+ }
+
+ function isExpanded(index: number, section: AgenticSection, inOpenGroup = false): boolean {
+ if (expandedStates[index] !== undefined) {
+ return expandedStates[index];
+ }
+
+ // opening a group while a call runs shows that call's live output
+ if (inOpenGroup && isExecutingCall(section)) return true;
+
+ return isSectionExpandedByDefault(section, {
+ alwaysShowToolCallContent,
+ executingToolCallId: currentlyExecutingToolCallId,
+ showThoughtInProgress,
+ showToolCallInProgress
+ });
+ }
+
+ function toggleExpanded(index: number, section: AgenticSection, inOpenGroup = false) {
+ const currentState = isExpanded(index, section, inOpenGroup);
+
+ expandedStates[index] = !currentState;
+ }
+
+ function isGroupExpanded(indices: number[]): boolean {
+ const state = groupExpandedStates[indices[0]];
+
+ if (state !== undefined) return state;
+
+ if (alwaysShowToolCallContent) return true;
+
+ // with "Show tool call in progress" the latest group stays open for the
+ // whole reply, so calls are seen as they happen, and folds into its
+ // summary once the reply is done
+ return showToolCallInProgress && isStreaming && indices.includes(lastToolIndex);
+ }
+
+ function toggleGroupExpanded(indices: number[]) {
+ groupExpandedStates[indices[0]] = !isGroupExpanded(indices);
+ }
+
+ function buildTurnAgenticTimings(stats: ChatMessageAgenticTurnStats): ChatMessageAgenticTimings {
+ return {
+ llm: stats.llm,
+ toolCalls: stats.toolCalls,
+ toolCallsCount: stats.toolCalls.length,
+ toolsMs: stats.toolsMs,
+ turns: 1
+ };
+ }
+</script>
+
+{#snippet renderSection(section: AgenticSection, index: number, inOpenGroup = false)}
+ {#if section.type === AgenticSectionType.TEXT}
+ <div class="agent-trace-text">
+ <MarkdownContent attachments={message?.extra} content={section.content} />
+ </div>
+ {:else if section.type === AgenticSectionType.REASONING || section.type === AgenticSectionType.REASONING_PENDING}
+ <ChatMessageReasoningBlock
+ attachments={message?.extra}
+ {hasReasoningError}
+ {isStreaming}
+ onToggle={() => toggleExpanded(index, section)}
+ open={isExpanded(index, section)}
+ {section}
+ />
+ {:else if section.type === AgenticSectionType.TOOL_CALL || section.type === AgenticSectionType.TOOL_CALL_PENDING || section.type === AgenticSectionType.TOOL_CALL_STREAMING}
+ <ChatMessageToolCallBlock
+ attachments={section.toolResultExtras}
+ {conversationCwd}
+ isExecuting={isExecutingCall(section)}
+ {isStreaming}
+ onToggle={() => toggleExpanded(index, section, inOpenGroup)}
+ open={isExpanded(index, section, inOpenGroup)}
+ {section}
+ />
+ {/if}
+{/snippet}
+
+{#snippet renderItem(item: TraceItem)}
+ {#if Array.isArray(item)}
+ {@const groupOpen = isGroupExpanded(item)}
+ <ChatMessageToolCallGroup
+ elapsedStartedAt={item === lastItem ? taskStartedAt : null}
+ executingToolCallId={currentlyExecutingToolCallId}
+ {isStreaming}
+ onToggle={() => toggleGroupExpanded(item)}
+ open={groupOpen}
+ sections={item.map((i) => sections[i])}
+ status={statusInGroup && item === lastItem ? statusText || REPLY_STATUS_FALLBACK : null}
+ >
+ {#each item as index (index)}
+ {@render renderSection(sections[index], index, groupOpen)}
+ {/each}
+ </ChatMessageToolCallGroup>
+ {:else}
+ {@render renderSection(sections[item], item)}
+ {/if}
+{/snippet}
+
+{#snippet renderItems(items: TraceItem[])}
+ {#each items as item (Array.isArray(item) ? `g${item[0]}` : item)}
+ {@render renderItem(item)}
+ {/each}
+{/snippet}
+
+<div class="agent-trace gap-2">
+ {#each turns as items, turnIndex (turnIndex)}
+ {#if showTurnStats}
+ {@const turnStats = message?.timings?.agentic?.perTurn?.[turnIndex]}
+
+ <div class="agent-trace-turn group/turn grid gap-2">
+ {@render renderItems(items)}
+
+ {#if turnStats}
+ <div class="turn-stats transition-opacity duration-150 mt-1 mb-4">
+ <ChatMessageStatistics
+ agenticTimings={turnStats.toolCalls.length > 0
+ ? buildTurnAgenticTimings(turnStats)
+ : undefined}
+ hideSummary
+ initialView={ChatMessageStatsView.GENERATION}
+ predictedMs={turnStats.llm.predicted_ms}
+ predictedTokens={turnStats.llm.predicted_n}
+ promptMs={turnStats.llm.prompt_ms}
+ promptTokens={turnStats.llm.prompt_n}
+ />
+ </div>
+ {/if}
+ </div>
+ {:else}
+ {@render renderItems(items)}
+ {/if}
+ {/each}
+
+ {#if visiblePermission}
+ <ChatMessageActionCardPermissionRequest
+ command={pendingCommand}
+ onDecision={handlePermission}
+ serverLabel={visiblePermission.serverLabel}
+ toolName={visiblePermission.toolName}
+ />
+ {/if}
+
+ {#if showContinue}
+ <ChatMessageActionCardContinueRequest onDecision={handleContinue} />
+ {/if}
+
+ {#if showStatus && !statusInGroup}
+ <ChatMessageAssistantProcessingInfo text={statusText || REPLY_STATUS_FALLBACK} />
+ {/if}
+</div>
+
+<style>
+ .agent-trace {
+ display: flex;
+ flex-direction: column;
+ width: 100%;
+ max-width: 48rem;
+ }
+
+ .agent-trace > :global(*),
+ .agent-trace-turn > :global(*) {
+ min-width: 0;
+ }
+
+ .agent-trace-text {
+ width: 100%;
+ }
+
+ /* the answer stands a little apart from the work around it: trace rows keep
+ their tight 0.5rem stack, text and a trace row get 0.75rem between them */
+ .agent-trace > :global(:not(.agent-trace-text) + .agent-trace-text),
+ .agent-trace-turn > :global(:not(.agent-trace-text) + .agent-trace-text) {
+ margin-top: 0.25rem;
+ }
+
+ /* on the text, not the row: the collapsible rows pin their own margins */
+ .agent-trace > :global(.agent-trace-text:has(+ :not(.agent-trace-text))),
+ .agent-trace-turn > :global(.agent-trace-text:has(+ :not(.agent-trace-text))) {
+ margin-bottom: 0.25rem;
+ }
+
+ .turn-stats {
+ border-top: 1px solid hsl(var(--surface-muted) / 0.5);
+ }
+</style>
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageAgenticContent.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageAgenticContent.svelte
deleted file mode 100644
index fa97fcde3..000000000
--- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageAgenticContent.svelte
+++ /dev/null
@@ -1,273 +0,0 @@
-<script lang="ts">
- import ChatMessageToolCallBlock from './ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlock.svelte';
- import ChatMessageReasoningBlock from './ChatMessageReasoningBlock.svelte';
- import {
- ChatMessageActionCardContinueRequest,
- ChatMessageActionCardPermissionRequest,
- ChatMessageStatistics,
- MarkdownContent
- } from '#lib/components/app/index.ts';
- import {
- AgenticSectionType,
- ChatMessageStatsView,
- ToolPermissionDecision
- } from '#lib/enums/index.ts';
- import { agenticStore, conversationsStore, settingsStore } from '#lib/stores/index.ts';
- import type {
- AgenticSection,
- ChatMessageAgenticTimings,
- ChatMessageAgenticTurnStats,
- DatabaseMessage
- } from '#lib/types/index.ts';
- import { deriveAgenticSections, isSectionExpandedByDefault } from '#lib/utils/index.ts';
-
- interface Props {
- message: DatabaseMessage;
- toolMessages?: DatabaseMessage[];
- isStreaming?: boolean;
- isLastAssistantMessage?: boolean;
- }
-
- let {
- isLastAssistantMessage = false,
- isStreaming: isChatStreaming = false,
- message,
- toolMessages = []
- }: Props = $props();
-
- // The chat-level streaming flag is shared by every message; only the last
- // assistant message is actually live, so earlier ones must not keep their
- // unresolved tool calls spinning while a newer reply streams.
- const isStreaming = $derived(isChatStreaming && isLastAssistantMessage);
-
- let expandedStates: Record<number, boolean> = $state({});
-
- const showThoughtInProgress = $derived(Boolean(settingsStore.config.showThoughtInProgress));
- const showToolCallInProgress = $derived(Boolean(settingsStore.config.showToolCallInProgress));
- const alwaysShowToolCallContent = $derived(
- Boolean(settingsStore.config.alwaysShowToolCallContent)
- );
- const showMessageStats = $derived(Boolean(settingsStore.config.showMessageStats));
- const showAgenticTurnStats = $derived(
- showMessageStats && Boolean(settingsStore.config.showAgenticTurnStats)
- );
-
- const hasReasoningError = $derived(
- isLastAssistantMessage ? !!agenticStore.getLastError(message.convId) : false
- );
-
- const pendingPermission = $derived(
- isStreaming ? agenticStore.getPendingPermissionRequest(message.convId) : null
- );
-
- // dismissal applies to the request object, so the next request ( new
- // identity ) shows the card again without any reset bookkeeping
- let dismissedPermission: typeof pendingPermission = $state(null);
-
- const visiblePermission = $derived(
- pendingPermission && dismissedPermission !== pendingPermission ? pendingPermission : null
- );
-
- function handlePermission(decision: ToolPermissionDecision) {
- dismissedPermission = pendingPermission;
- agenticStore.resolvePermission(message.convId, decision);
- }
-
- const pendingContinue = $derived(
- isStreaming ? agenticStore.getPendingContinueRequest(message.convId) : false
- );
-
- let continueDismissed = $state(false);
-
- // the continue request is a plain boolean, so there is no identity to
- // compare against; clear the dismissal whenever no request is pending so
- // the next one starts from a clean state
- $effect(() => {
- if (!pendingContinue) {
- continueDismissed = false;
- }
- });
-
- const showContinue = $derived(Boolean(pendingContinue) && !continueDismissed);
-
- function handleContinue(shouldContinue: boolean) {
- continueDismissed = true;
- agenticStore.resolveContinue(message.convId, shouldContinue);
- }
-
- const sections = $derived(deriveAgenticSections(message, toolMessages, [], isStreaming));
-
- const currentlyExecutingToolCallId = $derived(
- isStreaming ? agenticStore.getExecutingToolCallId(message.convId) : null
- );
-
- // Cwd the agentic loop passes to tool calls in this conversation; the exec
- // block shows it until the result message persists the real one.
- const conversationCwd = $derived(
- conversationsStore.activeConversation?.id === message.convId
- ? conversationsStore.activeConversation?.cwd
- : undefined
- );
-
- type TurnGroup = {
- sections: AgenticSection[];
- flatIndices: number[];
- };
-
- const turnGroups: TurnGroup[] = $derived.by(() => {
- const groups: TurnGroup[] = [];
-
- let currentTurn: AgenticSection[] = [];
- let currentIndices: number[] = [];
- let prevWasTool = false;
-
- for (let i = 0; i < sections.length; i++) {
- const section = sections[i];
- const isTool =
- section.type === AgenticSectionType.TOOL_CALL ||
- section.type === AgenticSectionType.TOOL_CALL_PENDING ||
- section.type === AgenticSectionType.TOOL_CALL_STREAMING;
-
- if (!isTool && prevWasTool && currentTurn.length > 0) {
- groups.push({ flatIndices: currentIndices, sections: currentTurn });
- currentTurn = [];
- currentIndices = [];
- }
-
- currentTurn.push(section);
- currentIndices.push(i);
- prevWasTool = isTool;
- }
-
- if (currentTurn.length > 0) {
- groups.push({ flatIndices: currentIndices, sections: currentTurn });
- }
-
- return groups;
- });
-
- function isExpanded(index: number, section: AgenticSection): boolean {
- if (expandedStates[index] !== undefined) {
- return expandedStates[index];
- }
-
- return isSectionExpandedByDefault(section, {
- alwaysShowToolCallContent,
- executingToolCallId: currentlyExecutingToolCallId,
- showThoughtInProgress,
- showToolCallInProgress
- });
- }
-
- function toggleExpanded(index: number, section: AgenticSection) {
- const currentState = isExpanded(index, section);
-
- expandedStates[index] = !currentState;
- }
-
- function buildTurnAgenticTimings(stats: ChatMessageAgenticTurnStats): ChatMessageAgenticTimings {
- return {
- llm: stats.llm,
- toolCalls: stats.toolCalls,
- toolCallsCount: stats.toolCalls.length,
- toolsMs: stats.toolsMs,
- turns: 1
- };
- }
-</script>
-
-{#snippet renderSection(section: AgenticSection, index: number)}
- {#if section.type === AgenticSectionType.TEXT}
- <div class="agentic-text">
- <MarkdownContent attachments={message?.extra} content={section.content} />
- </div>
- {:else if section.type === AgenticSectionType.REASONING || section.type === AgenticSectionType.REASONING_PENDING}
- <ChatMessageReasoningBlock
- attachments={message?.extra}
- {hasReasoningError}
- {isStreaming}
- onToggle={() => toggleExpanded(index, section)}
- open={isExpanded(index, section)}
- {section}
- />
- {:else if section.type === AgenticSectionType.TOOL_CALL || section.type === AgenticSectionType.TOOL_CALL_PENDING || section.type === AgenticSectionType.TOOL_CALL_STREAMING}
- <ChatMessageToolCallBlock
- attachments={section.toolResultExtras}
- {conversationCwd}
- isExecuting={section.toolCallId !== undefined &&
- section.toolCallId === currentlyExecutingToolCallId}
- {isStreaming}
- onToggle={() => toggleExpanded(index, section)}
- open={isExpanded(index, section)}
- {section}
- />
- {/if}
-{/snippet}
-
-<div class="agentic-content gap-2">
- {#if turnGroups.length > 1}
- {#each turnGroups as turn, turnIndex (turnIndex)}
- {@const turnStats = message?.timings?.agentic?.perTurn?.[turnIndex]}
-
- <div class="agentic-turn group/turn grid gap-2">
- {#each turn.sections as section, sIdx (turn.flatIndices[sIdx])}
- {@render renderSection(section, turn.flatIndices[sIdx])}
- {/each}
-
- {#if turnStats && showAgenticTurnStats}
- <div class="turn-stats transition-opacity duration-150 mt-1 mb-4">
- <ChatMessageStatistics
- agenticTimings={turnStats.toolCalls.length > 0
- ? buildTurnAgenticTimings(turnStats)
- : undefined}
- hideSummary
- initialView={ChatMessageStatsView.GENERATION}
- predictedMs={turnStats.llm.predicted_ms}
- predictedTokens={turnStats.llm.predicted_n}
- promptMs={turnStats.llm.prompt_ms}
- promptTokens={turnStats.llm.prompt_n}
- />
- </div>
- {/if}
- </div>
- {/each}
- {:else}
- {#each sections as section, index (index)}
- {@render renderSection(section, index)}
- {/each}
- {/if}
-
- {#if visiblePermission}
- <ChatMessageActionCardPermissionRequest
- onDecision={handlePermission}
- serverLabel={visiblePermission.serverLabel}
- toolName={visiblePermission.toolName}
- />
- {/if}
-
- {#if showContinue}
- <ChatMessageActionCardContinueRequest onDecision={handleContinue} />
- {/if}
-</div>
-
-<style>
- .agentic-content {
- display: flex;
- flex-direction: column;
- width: 100%;
- max-width: 48rem;
- }
-
- .agentic-content > :global(*),
- .agentic-turn > :global(*) {
- min-width: 0;
- }
-
- .agentic-text {
- width: 100%;
- }
-
- .turn-stats {
- border-top: 1px solid hsl(var(--surface-muted) / 0.5);
- }
-</style>
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageReasoningBlock.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageReasoningBlock.svelte
index f084d6cd6..b417f4256 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageReasoningBlock.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageReasoningBlock.svelte
@@ -1,5 +1,4 @@
<script lang="ts">
- import { Lightbulb } from '@lucide/svelte';
import { CollapsibleContentBlock, MarkdownContent } from '#lib/components/app/index.ts';
import { REASONING_SCROLL_AT_BOTTOM_THRESHOLD_PX } from '#lib/constants/index.ts';
import { AgenticSectionType } from '#lib/enums/index.ts';
@@ -125,8 +124,7 @@
<CollapsibleContentBlock
class="my-2"
- icon={Lightbulb}
- iconClass="size-icon-sm"
+ inlineChevron
{onToggle}
{open}
{shimmerTitle}
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 49f6a3b29..2dba6679e 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
@@ -1,6 +1,15 @@
<script lang="ts">
import * as Tooltip from '@ggml-org/llama-ui/ui/tooltip';
- import { BookOpenText, Clock, Gauge, Layers, Sparkles, WholeWord, Wrench } from '@lucide/svelte';
+ import {
+ BookOpenText,
+ Clock,
+ Gauge,
+ Hourglass,
+ Layers,
+ Sparkles,
+ WholeWord,
+ Wrench
+ } from '@lucide/svelte';
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';
@@ -117,9 +126,14 @@
hasAgenticStats ? formatPerformanceTime(agenticTimings!.toolsMs) : DEFAULT_PERFORMANCE_TIME
);
+ // wall time of the whole task when recorded (permission waits included);
+ // older messages fall back to the sum of LLM and tool time
let agenticTotalTimeMs = $derived(
hasAgenticStats
- ? agenticTimings!.toolsMs + agenticTimings!.llm.predicted_ms + agenticTimings!.llm.prompt_ms
+ ? (agenticTimings!.totalMs ??
+ agenticTimings!.toolsMs +
+ agenticTimings!.llm.predicted_ms +
+ agenticTimings!.llm.prompt_ms)
: 0
);
@@ -226,6 +240,15 @@
value={formattedTime}
/>
+ {#if hasAgenticStats && agenticTimings!.totalMs !== undefined}
+ <ChatMessageStatisticsBadge
+ class="bg-transparent"
+ icon={Hourglass}
+ tooltipLabel="Total task time, from the prompt to the answer"
+ value={formattedAgenticTotalTime}
+ />
+ {/if}
+
<ChatMessageStatisticsBadge
class="bg-transparent"
icon={Gauge}
@@ -271,7 +294,7 @@
<ChatMessageStatisticsBadge
class="bg-transparent"
icon={Clock}
- tooltipLabel="Total time (LLM + tools)"
+ tooltipLabel="Total task time"
value={formattedAgenticTotalTime}
/>
{:else if hasPromptStats && (mode === ChatMessageStatisticsMode.READING || isSwitchable)}
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessages.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessages.svelte
index 2fd19d8f8..d1e60179a 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessages.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessages.svelte
@@ -244,7 +244,7 @@
{#each displayMessages as { isLastAssistantMessage, isLastUserMessage, message, nextAssistantMessage, siblingInfo, toolMessages }, index (message.id)}
<LazyChatMessage
{chatActions}
- class="mx-auto mt-12 w-full max-w-3xl"
+ class="mx-auto mt-4 w-full max-w-3xl"
eager={index >= displayMessages.length - LANDING_EAGER_ROWS}
{isLastAssistantMessage}
{isLastUserMessage}
@@ -261,7 +261,7 @@
{#if pendingContent}
<ChatMessageUserPending
- class="mx-auto mt-12 w-full max-w-3xl"
+ class="mx-auto mt-4 w-full max-w-3xl"
content={pendingContent}
extras={agenticStore.getPendingSteeringMessageExtras(convId)}
onDelete={() => agenticStore.clearSteeringMessage(convId)}
@@ -276,7 +276,7 @@
{#if pendingContent}
<ChatMessageUserPending
- class="mx-auto mt-12 w-full max-w-3xl"
+ class="mx-auto mt-4 w-full max-w-3xl"
content={pendingContent}
extras={chatStore.getPendingMessageExtras(convId)}
onDelete={() => chatStore.clearPendingMessage(convId)}
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreen.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreen.svelte
index 911f07434..7cf2366e3 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreen.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreen.svelte
@@ -148,8 +148,9 @@
return false;
}
- // Sending re-arms following: the reply streams in under the message.
- stick.scrollToBottom();
+ // Sending re-arms following: the message glides to the top of the screen
+ // and the reply streams in under it.
+ stick.glideToBottom();
await chatStore.sendMessage(message, result?.extras);
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenDialogsAndAlerts.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenDialogsAndAlerts.svelte
index 5dc6107a0..ef96cca5b 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenDialogsAndAlerts.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenDialogsAndAlerts.svelte
@@ -1,11 +1,13 @@
<script lang="ts">
import {
+ DialogChatAttachmentsPreview,
DialogChatError,
DialogConversationDelete,
DialogEmptyFileAlert,
DialogFileUploadError
} from '#lib/components/app/index.ts';
import { ErrorDialogType } from '#lib/enums/index.ts';
+ import { mediaGalleryStore } from '#lib/stores/index.ts';
let {
activeErrorDialog,
@@ -46,3 +48,10 @@
open={Boolean(activeErrorDialog)}
type={activeErrorDialog?.type ?? ErrorDialogType.SERVER}
/>
+
+<!-- the conversation's media as one slideshow, opened from any thumbnail in the chat -->
+<DialogChatAttachmentsPreview
+ bind:open={mediaGalleryStore.open}
+ attachments={mediaGalleryStore.items}
+ previewFocusIndex={mediaGalleryStore.index}
+/>
diff --git a/ui/apps/chat/src/lib/components/app/chat/index.ts b/ui/apps/chat/src/lib/components/app/chat/index.ts
index f7626c73a..fd90e5d61 100644
--- a/ui/apps/chat/src/lib/components/app/chat/index.ts
+++ b/ui/apps/chat/src/lib/components/app/chat/index.ts
@@ -450,7 +450,7 @@ export { default as ChatMessages } from './ChatMessages/ChatMessages.svelte';
* - Edit creates new branch or preserves responses
*
* **Assistant Messages:**
- * - Renders content via MarkdownContent or ChatMessageAgenticContent
+ * - Renders a plain reply via ChatMessageAssistantResponse, an agentic one via ChatMessageAgentTrace
* - Shows model info badge (when enabled)
* - Regenerate creates sibling with optional model override
* - Continue action for incomplete responses
@@ -476,39 +476,26 @@ export { default as ChatMessages } from './ChatMessages/ChatMessages.svelte';
export { default as ChatMessage } from './ChatMessages/ChatMessage/ChatMessage.svelte';
/**
- * **ChatMessageAgenticContent** - Agentic workflow output display
+ * **ChatMessageAgentTrace** - An assistant reply that ran the agentic loop
*
- * Specialized renderer for assistant messages with tool calls and reasoning.
- * Derives display sections from structured message data (toolCalls, reasoningContent,
- * and child tool result messages) and renders them as interactive collapsible sections.
+ * Shows what the agent did as a log: tool calls and the reasoning around them
+ * fold into one group row whose title sums them up ("Ran 2 commands, read 1
+ * file"), or says what is happening now while the reply is live, followed by
+ * the answer. A reply without tool calls renders through
+ * ChatMessageAssistantResponse instead.
*
* **Architecture:**
* - Uses `deriveAgenticSections()` from `#lib/utils/index.ts` to build sections from structured data
- * - Renders sections as CollapsibleContentBlock components
- * - Handles streaming state for progressive content display
- * - Falls back to MarkdownContent for plain text sections
- *
- * **Execution States:**
- * - **Streaming**: Animated spinner, block expanded, auto-scroll enabled
- * - **Pending**: Waiting indicator for queued tool calls
- * - **Completed**: Static display, block collapsed by default
- *
- * **Features:**
- * - JSON arguments syntax highlighting via SyntaxHighlightedCode
- * - Tool results display with formatting
- * - Plain text sections between markers rendered as markdown
- * - Smart collapse defaults (expanded while streaming, collapsed when done)
+ * - Groups runs of calls and reasoning with `groupToolCallRuns()` into ChatMessageToolCallGroup rows
+ * - Renders each call through ChatMessageToolCallBlock, text through MarkdownContent
+ * - Carries the live status, the task timer and the permission and continue cards
*
* @example
* ```svelte
- * <ChatMessageAgenticContent
- * content={message.content}
- * {message}
- * isStreaming={isGenerating}
- * />
+ * <ChatMessageAgentTrace {message} {toolMessages} isStreaming={isGenerating} />
* ```
*/
-export { default as ChatMessageAgenticContent } from './ChatMessages/ChatMessageAgenticContent.svelte';
+export { default as ChatMessageAgentTrace } from './ChatMessages/ChatMessageAgentTrace.svelte';
export { default as ChatMessageActionCardPermissionRequest } from './ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardPermissionRequest.svelte';
export { default as ChatMessageActionCard } from './ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCard.svelte';
export { default as ChatMessageActionCardContinueRequest } from './ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardContinueRequest.svelte';
@@ -583,14 +570,20 @@ export { default as ChatMessageMcpPromptContent } from './ChatMessages/ChatMessa
/**
* Assistant message display component. Renders assistant responses with left-aligned styling.
- * Supports both plain markdown content (via MarkdownContent) and agentic content with tool calls
- * (via ChatMessageAgenticContent). Shows model info badge, statistics, and action buttons.
+ * A basic chat reply renders as reasoning and text (via ChatMessageAssistantResponse); a reply
+ * that ran the agentic loop renders as an Agent Trace (via ChatMessageAgentTrace). Shows model
+ * info badge, statistics, and action buttons.
* Handles streaming state with real-time content updates.
*/
export { default as ChatMessageAssistant } from './ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistant.svelte';
export { default as ChatMessageAssistantModel } from './ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistantModel.svelte';
export { default as ChatMessageAssistantProcessingInfo } from './ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistantProcessingInfo.svelte';
export { default as ChatMessageAssistantRawOutput } from './ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistantRawOutput.svelte';
+/**
+ * A basic chat reply: the model's reasoning, if any, and its answer. Replies
+ * that ran the agentic loop render as ChatMessageAgentTrace instead.
+ */
+export { default as ChatMessageAssistantResponse } from './ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistantResponse.svelte';
export { default as ChatMessageAssistantStatistics } from './ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistantStatistics.svelte';
/**
diff --git a/ui/apps/chat/src/lib/components/app/content/CollapsibleContentBlock.svelte b/ui/apps/chat/src/lib/components/app/content/CollapsibleContentBlock.svelte
index 797a4f2fe..328ced020 100644
--- a/ui/apps/chat/src/lib/components/app/content/CollapsibleContentBlock.svelte
+++ b/ui/apps/chat/src/lib/components/app/content/CollapsibleContentBlock.svelte
@@ -31,6 +31,15 @@
* message width on its own.
*/
flushBody?: boolean;
+ /** Shown at the end of the header row, before the chevron. */
+ trailing?: Snippet;
+ /** Shown right after the title, e.g. a live timer. */
+ titleSuffix?: Snippet;
+ /**
+ * Put the chevron right after the title and keep it visible, for rows
+ * that read as a line of text ( the tool call trace ) instead of a bar.
+ */
+ inlineChevron?: boolean;
onToggle?: () => void;
children: Snippet;
}
@@ -43,12 +52,15 @@
icon: IconComponent,
iconClass = ICON_CLASS_DEFAULT,
iconUrl = null,
+ inlineChevron = false,
onToggle,
open = $bindable(false),
shimmerTitle = false,
subtitle,
title = '',
titleSnippet,
+ titleSuffix,
+ trailing,
variant = 'default'
}: Props = $props();
@@ -91,6 +103,22 @@
<span aria-hidden="true" class="h-px min-w-4 flex-1 bg-current opacity-25"></span>
{/snippet}
+<!-- Beside the title it is always visible and points right until open; at the
+ end of the row it appears on hover and flips. -->
+{#snippet chevron()}
+ <ChevronDown
+ class={cn(
+ 'shrink-0 text-muted-foreground/60 duration-150 ease-out',
+ inlineChevron
+ ? ['size-3.5 self-center transition-transform', !open && '-rotate-90']
+ : [
+ 'mt-0.75 size-4 opacity-0 transition-all group-hover/collapsible:opacity-100',
+ open && 'rotate-180'
+ ]
+ )}
+ />
+{/snippet}
+
{#snippet toggleTitle(layoutClass: string)}
<span
class={cn(
@@ -109,6 +137,15 @@
{#if subtitle}
<span class="text-caption italic text-muted-foreground/70">{subtitle}</span>
{/if}
+
+ {#if shimmerTitle}
+ <!-- the shimmer is the only sign that this is still running -->
+ <span class="sr-only">in progress</span>
+ {/if}
+
+ {#if titleSuffix}
+ <span class="shrink-0 text-body-sm empty:hidden">{@render titleSuffix()}</span>
+ {/if}
{/snippet}
<Collapsible.Root
@@ -142,14 +179,21 @@
{@render toggleIcon('mt-0.75')}
{@render toggleTitle('overflow-x-auto text-body-sm')}
+
+ {#if inlineChevron}
+ {@render chevron()}
+ {/if}
</div>
- <ChevronDown
- class={cn(
- 'size-4 shrink-0 text-muted-foreground/60 transition-all duration-150 ease-out opacity-0 group-hover/collapsible:opacity-100 mt-0.75',
- open && 'rotate-180'
- )}
- />
+ {#if trailing}
+ <div class="ml-auto flex shrink-0 items-center">
+ {@render trailing()}
+ </div>
+ {/if}
+
+ {#if !inlineChevron}
+ {@render chevron()}
+ {/if}
<span class="sr-only">Toggle content</span>
</Collapsible.Trigger>
@@ -162,6 +206,7 @@
<div class="pl-1.5 grid min-w-0" style="min-height: var(--min-message-height);">
<div
class={cn('min-w-0 pb-2 my-2', !flushBody && 'border-l border-muted-foreground/20 pl-4')}
+ data-slot="collapsible-body"
>
{@render children()}
</div>
diff --git a/ui/apps/chat/src/lib/components/app/content/index.ts b/ui/apps/chat/src/lib/components/app/content/index.ts
index 62ad69780..c3d69b6d6 100644
--- a/ui/apps/chat/src/lib/components/app/content/index.ts
+++ b/ui/apps/chat/src/lib/components/app/content/index.ts
@@ -119,6 +119,10 @@ export { default as CollapsibleContentBlock } from './CollapsibleContentBlock.sv
* <pre>{output}</pre>
* </CollapsibleTerminalBlock>
* ```
+ *
+ * @deprecated No component uses it any more: the shell tool call draws its
+ * terminal frame inside a CollapsibleContentBlock row. Kept for its story and
+ * the lazy-body test until those move over.
*/
export { default as CollapsibleTerminalBlock } from './CollapsibleTerminalBlock.svelte';
diff --git a/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatToolsTab.svelte b/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatToolsTab.svelte
index 15c62cf48..83dd0cd52 100644
--- a/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatToolsTab.svelte
+++ b/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatToolsTab.svelte
@@ -1,16 +1,73 @@
<script lang="ts">
import { Checkbox } from '@ggml-org/llama-ui/ui/checkbox';
import * as Collapsible from '@ggml-org/llama-ui/ui/collapsible';
+ import * as Select from '@ggml-org/llama-ui/ui/select';
import { ChevronDown, ChevronRight } from '@lucide/svelte';
import { McpServerIdentity, TruncatedText } from '#lib/components/app/index.ts';
- import { ICON_CLASS_DEFAULT } from '#lib/constants/index.ts';
+ import {
+ ICON_CLASS_DEFAULT,
+ SETTINGS_KEYS,
+ TOOL_CALL_SHOWN_ARG_NONE
+ } from '#lib/constants/index.ts';
import { ToolSource } from '#lib/enums/tools.enums.ts';
- import { conversationsStore, mcpStore, permissionsStore, toolsStore } from '#lib/stores/index.ts';
- import { getToolUi } from '#lib/utils/index.ts';
+ import {
+ conversationsStore,
+ mcpStore,
+ permissionsStore,
+ settingsStore,
+ toolsStore
+ } from '#lib/stores/index.ts';
+ import type { OpenAIToolDefinition } from '#lib/types/index.ts';
+ import { getToolUi, parseToolCallShownArgOverrides } from '#lib/utils/index.ts';
import { SvelteSet } from 'svelte/reactivity';
+ // the shown-argument picks: a tool follows the global setting until it gets one of its own
+ const SHOWN_ARG_DEFAULT = '__default__';
+ const SHOWN_ARG_NONE = '__none__';
+
let expandedGroups = new SvelteSet<string>();
let groups = $derived(toolsStore.toolGroups);
+ let shownArgOverrides = $derived(
+ parseToolCallShownArgOverrides(
+ settingsStore.config[SETTINGS_KEYS.TOOL_CALL_SHOWN_ARG_OVERRIDES]
+ )
+ );
+ let globalShownArg = $derived(
+ String(settingsStore.config[SETTINGS_KEYS.TOOL_CALL_SHOWN_ARG] ?? '').trim()
+ );
+
+ function argNames(definition: OpenAIToolDefinition): string[] {
+ const properties = (definition.function.parameters as { properties?: object } | undefined)
+ ?.properties;
+
+ return properties ? Object.keys(properties) : [];
+ }
+
+ function shownArgPick(toolName: string): string {
+ const own = shownArgOverrides[toolName];
+
+ if (own === undefined) return SHOWN_ARG_DEFAULT;
+
+ return own === TOOL_CALL_SHOWN_ARG_NONE ? SHOWN_ARG_NONE : own;
+ }
+
+ function shownArgLabel(pick: string): string {
+ if (pick === SHOWN_ARG_NONE) return 'None';
+
+ if (pick === SHOWN_ARG_DEFAULT)
+ return globalShownArg ? `Default (${globalShownArg})` : 'Default';
+
+ return pick;
+ }
+
+ function setShownArg(toolName: string, pick: string) {
+ const next = { ...shownArgOverrides };
+
+ if (pick === SHOWN_ARG_DEFAULT) delete next[toolName];
+ else next[toolName] = pick === SHOWN_ARG_NONE ? TOOL_CALL_SHOWN_ARG_NONE : pick;
+
+ settingsStore.updateConfig(SETTINGS_KEYS.TOOL_CALL_SHOWN_ARG_OVERRIDES, JSON.stringify(next));
+ }
function toggleExpanded(key: string) {
if (expandedGroups.has(key)) {
@@ -81,6 +138,13 @@
<span class="w-16 shrink-0 text-center">Enabled</span>
<span class="w-20 shrink-0 text-center">Always allow</span>
+
+ <span
+ class="w-32 shrink-0"
+ title="The argument a call's line shows when the call has it"
+ >
+ Shown argument
+ </span>
</div>
{#each group.tools as entry (entry.key)}
@@ -94,6 +158,7 @@
{@const isEnabled = conversationsStore.preferences.isToolEnabled(entry.key)}
{@const permissionKey = entry.key}
{@const isAlwaysAllowed = permissionsStore.hasTool(permissionKey)}
+ {@const shownArg = shownArgPick(toolName)}
<div
class="flex items-center gap-2 rounded px-2 py-1.5 text-body-sm hover:bg-muted/50"
@@ -128,6 +193,41 @@
}}
/>
</div>
+
+ <div class="w-32 shrink-0">
+ <Select.Root
+ onValueChange={(value) => setShownArg(toolName, value)}
+ type="single"
+ value={shownArg}
+ >
+ <Select.Trigger
+ aria-label="Argument shown for {displayLabel}"
+ class="h-7 w-full px-2 text-caption"
+ size="sm"
+ >
+ <span class="truncate">
+ {shownArg === SHOWN_ARG_DEFAULT ? 'Default' : shownArgLabel(shownArg)}
+ </span>
+ </Select.Trigger>
+
+ <Select.Content>
+ <Select.Item
+ label={shownArgLabel(SHOWN_ARG_DEFAULT)}
+ value={SHOWN_ARG_DEFAULT}
+ >
+ {shownArgLabel(SHOWN_ARG_DEFAULT)}
+ </Select.Item>
+
+ <Select.Item label="None" value={SHOWN_ARG_NONE}>None</Select.Item>
+
+ {#each argNames(entry.definition) as arg (arg)}
+ <Select.Item label={arg} value={arg}>
+ <span class="font-mono">{arg}</span>
+ </Select.Item>
+ {/each}
+ </Select.Content>
+ </Select.Root>
+ </div>
</div>
{/each}
</div>
diff --git a/ui/apps/chat/src/lib/constants/css-classes.constants.ts b/ui/apps/chat/src/lib/constants/css-classes.constants.ts
index 12de5176b..4e9150396 100644
--- a/ui/apps/chat/src/lib/constants/css-classes.constants.ts
+++ b/ui/apps/chat/src/lib/constants/css-classes.constants.ts
@@ -66,6 +66,3 @@ export const ICON_CLASS_SM = 'size-icon-sm';
/** Extra-small Tailwind size class for inline icons. */
export const ICON_CLASS_XS = 'size-icon-xs';
-
-/** Icon size + spinning animation; used for live-streaming tool indicators. */
-export const ICON_CLASS_SPIN = 'size-icon-md animate-spin';
diff --git a/ui/apps/chat/src/lib/constants/index.ts b/ui/apps/chat/src/lib/constants/index.ts
index 399e75ac7..fd00ac7f3 100644
--- a/ui/apps/chat/src/lib/constants/index.ts
+++ b/ui/apps/chat/src/lib/constants/index.ts
@@ -19,6 +19,7 @@ export * from './conversation-search.constants';
export * from './binary-detection.constants';
export * from './content-detection.constants';
export * from './tool-call-args.constants';
+export * from './tool-call-phrasing.constants';
export * from './tool-ui.constants';
export * from './cache.constants';
export * from './chat-form.constants';
diff --git a/ui/apps/chat/src/lib/constants/settings-keys.constants.ts b/ui/apps/chat/src/lib/constants/settings-keys.constants.ts
index 5bb1bb4ec..b3d37b0e0 100644
--- a/ui/apps/chat/src/lib/constants/settings-keys.constants.ts
+++ b/ui/apps/chat/src/lib/constants/settings-keys.constants.ts
@@ -6,6 +6,7 @@
*/
export const SETTINGS_KEYS = {
AGENTIC_MAX_TURNS: 'agenticMaxTurns',
+ ALWAYS_SHOW_MESSAGE_STATS: 'alwaysShowMessageStats',
ALWAYS_SHOW_SIDEBAR_ON_DESKTOP: 'alwaysShowSidebarOnDesktop',
ALWAYS_SHOW_TOOL_CALL_CONTENT: 'alwaysShowToolCallContent',
API_KEY: 'apiKey',
@@ -82,6 +83,8 @@ export const SETTINGS_KEYS = {
TITLE_GENERATION_PROMPT: 'titleGenerationPrompt',
TITLE_GENERATION_USE_FIRST_LINE: 'titleGenerationUseFirstLine',
TITLE_GENERATION_USE_LLM: 'titleGenerationUseLLM',
+ TOOL_CALL_SHOWN_ARG: 'toolCallShownArg',
+ TOOL_CALL_SHOWN_ARG_OVERRIDES: 'toolCallShownArgOverrides',
TOP_K: 'top_k',
TOP_P: 'top_p',
TYP_P: 'typ_p',
diff --git a/ui/apps/chat/src/lib/constants/settings.constants.ts b/ui/apps/chat/src/lib/constants/settings.constants.ts
index 4df67abef..0c4d4c250 100644
--- a/ui/apps/chat/src/lib/constants/settings.constants.ts
+++ b/ui/apps/chat/src/lib/constants/settings.constants.ts
@@ -4,6 +4,7 @@ import { COMPACTION } from './compaction.constants';
import { DEFAULT_MCP_CONFIG } from './mcp.constants';
import { SETTINGS_KEYS } from './settings-keys.constants';
import { TITLE_GENERATION } from './title-generation.constants';
+import { TOOL_CALL_SHOWN_ARG_DEFAULT } from './tool-call-phrasing.constants';
import { VOICE_TRANSCRIPTION_MODEL_AUTO } from './voice.constants';
import { FILE_GLOB_SEARCH_PICKERS } from './working-directory.constants';
import { VOICE_MICROPHONE_AUTO } from '@ggml-org/llama-voice';
@@ -277,14 +278,22 @@ export const SETTINGS_REGISTRY: SettingsSectionEntry[] = [
type: SettingsFieldType.CHECKBOX
},
{
- defaultValue: true,
+ defaultValue: false,
+ dependsOn: SETTINGS_KEYS.SHOW_MESSAGE_STATS,
+ help: 'Keep the generation statistics under every message in view. When off, they show under the latest exchange and appear on earlier messages when you point at them. Message actions always work that way.',
+ key: SETTINGS_KEYS.ALWAYS_SHOW_MESSAGE_STATS,
+ label: 'Always show message statistics',
+ type: SettingsFieldType.CHECKBOX
+ },
+ {
+ defaultValue: false,
help: 'Expand thought process by default when generating messages.',
key: SETTINGS_KEYS.SHOW_THOUGHT_IN_PROGRESS,
label: 'Show thought in progress',
type: SettingsFieldType.CHECKBOX
},
{
- defaultValue: true,
+ defaultValue: false,
help: 'Expand tool call details while the call is being generated and executed, and collapse them again once its result is in. Mirrors "Show thought in progress". Tool calls you expand or collapse by hand keep your choice.',
key: SETTINGS_KEYS.SHOW_TOOL_CALL_IN_PROGRESS,
label: 'Show tool call in progress',
@@ -297,6 +306,14 @@ export const SETTINGS_REGISTRY: SettingsSectionEntry[] = [
label: 'Always show tool call content',
type: SettingsFieldType.CHECKBOX
},
+ {
+ defaultValue: TOOL_CALL_SHOWN_ARG_DEFAULT,
+ help: 'A tool call\'s line shows this argument when the call has it, for any tool, built-in or MCP. Calls without it read as a plain sentence, e.g. "Read package.json". Settings > Tools can pick another argument for each tool. Leave it empty to always use the sentence.',
+ key: SETTINGS_KEYS.TOOL_CALL_SHOWN_ARG,
+ label: 'Tool call argument to show',
+ placeholder: 'None',
+ type: SettingsFieldType.INPUT
+ },
{
defaultValue: true,
help: 'Render user messages using markdown formatting in the chat. Turn this off to keep a message exactly as typed; @-mention badges show either way.',
@@ -509,6 +526,14 @@ export const SETTINGS_REGISTRY: SettingsSectionEntry[] = [
label: 'MCP servers',
standaloneField: false,
type: SettingsFieldType.INPUT
+ },
+ {
+ defaultValue: '{}',
+ help: 'Argument shown in the line of each tool, by tool name, as a JSON object. Use the Tools tab to edit.',
+ key: SETTINGS_KEYS.TOOL_CALL_SHOWN_ARG_OVERRIDES,
+ label: 'Tool call argument to show, per tool',
+ standaloneField: false,
+ type: SettingsFieldType.INPUT
}
],
slug: SETTINGS_SECTION_SLUGS.TOOLS,
diff --git a/ui/apps/chat/src/lib/constants/tool-call-phrasing.constants.ts b/ui/apps/chat/src/lib/constants/tool-call-phrasing.constants.ts
new file mode 100644
index 000000000..e811ee243
--- /dev/null
+++ b/ui/apps/chat/src/lib/constants/tool-call-phrasing.constants.ts
@@ -0,0 +1,175 @@
+// Plain-language phrasing for tool calls in the chat trace: the line each
+// call reads as ("Read a file", "Searched for 'issue'"), the live
+// description while it runs ("Reading package.json") and the counts in a
+// group summary ("Ran 3 commands, read 2 files").
+
+import { BuiltInTool, ToolCallSummaryKind } from '#lib/enums/index.ts';
+import type { ToolCallPhrasing } from '#lib/types/index.ts';
+
+/**
+ * A tool that loads tools on demand, and the `select:` prefix its query uses
+ * to name tools to load rather than search for them. The UI reads the prefix
+ * to count them; the convention lives with that tool.
+ */
+export const TOOL_SEARCH_PHRASING_NAME = 'tool_search';
+export const TOOL_SEARCH_PHRASING_SELECT_PREFIX = 'select:';
+
+/** Longest target shown after the verb before it is cut with "...". */
+export const TOOL_CALL_TARGET_MAX_CHARS = 60;
+
+/** Fewest consecutive tool calls that collapse into one group row. */
+export const TOOL_CALL_GROUP_MIN_CALLS = 2;
+
+/** Live title of a tool group while the model thinks inside it. */
+export const TOOL_CALL_THINKING_LABEL = 'Thinking';
+
+/** Status shown while a reply waits on the server and no finer status is known. */
+export const REPLY_STATUS_FALLBACK = 'Processing...';
+
+/** Args a generic (MCP or unknown) tool call is described by, first match wins. */
+export const TOOL_CALL_MAIN_ARG_KEYS: readonly string[] = [
+ 'query',
+ 'q',
+ 'path',
+ 'file_path',
+ 'filePath',
+ 'url',
+ 'name',
+ 'command',
+ 'pattern',
+ 'prompt',
+ 'text',
+ 'id'
+];
+
+/** Args that count as "simple" stay below this length and on one line. */
+export const TOOL_CALL_SIMPLE_ARG_MAX_CHARS = 200;
+
+export const TOOL_CALL_PHRASING: Readonly<Record<string, ToolCallPhrasing>> = {
+ // its own row reads "Current time is ...", so this entry serves group titles
+ [BuiltInTool.BROWSER_GET_DATETIME]: {
+ object: 'the time',
+ past: 'Checked',
+ present: 'Checking',
+ summary: ToolCallSummaryKind.OTHER
+ },
+ [BuiltInTool.BROWSER_READ_MEDIA]: {
+ object: 'media',
+ past: 'Viewed',
+ present: 'Viewing',
+ summary: ToolCallSummaryKind.VIEW
+ },
+ [BuiltInTool.BROWSER_RUN_JAVASCRIPT]: {
+ object: 'JavaScript',
+ past: 'Ran',
+ present: 'Running',
+ summary: ToolCallSummaryKind.SCRIPT
+ },
+ [BuiltInTool.BROWSER_SEARCH_CHATS]: {
+ object: 'chats',
+ past: 'Searched',
+ present: 'Searching',
+ quoteTarget: true,
+ summary: ToolCallSummaryKind.SEARCH,
+ targetObject: 'chats for'
+ },
+ [BuiltInTool.SERVER_EDIT_FILE]: {
+ object: 'a file',
+ past: 'Edited',
+ present: 'Editing',
+ summary: ToolCallSummaryKind.EDIT
+ },
+ [BuiltInTool.SERVER_EXEC_SHELL_COMMAND]: {
+ object: 'a command',
+ past: 'Ran',
+ present: 'Running',
+ summary: ToolCallSummaryKind.COMMAND
+ },
+ [BuiltInTool.SERVER_FILE_GLOB_SEARCH]: {
+ object: 'files',
+ past: 'Listed',
+ present: 'Listing',
+ quoteTarget: true,
+ summary: ToolCallSummaryKind.SEARCH,
+ targetObject: 'files matching'
+ },
+ [BuiltInTool.SERVER_GET_INFO]: {
+ object: 'runtime info',
+ past: 'Checked',
+ present: 'Checking',
+ summary: ToolCallSummaryKind.OTHER
+ },
+ [BuiltInTool.SERVER_GREP_SEARCH]: {
+ object: 'files',
+ past: 'Searched',
+ present: 'Searching',
+ quoteTarget: true,
+ summary: ToolCallSummaryKind.SEARCH,
+ targetObject: 'for'
+ },
+ [BuiltInTool.SERVER_READ_FILE]: {
+ object: 'a file',
+ past: 'Read',
+ present: 'Reading',
+ summary: ToolCallSummaryKind.READ
+ },
+ [BuiltInTool.SERVER_WRITE_FILE]: {
+ object: 'a file',
+ past: 'Wrote',
+ present: 'Writing',
+ summary: ToolCallSummaryKind.WRITE
+ }
+};
+
+export const TOOL_SEARCH_LOAD_PHRASING: ToolCallPhrasing = {
+ object: 'tools',
+ past: 'Loaded',
+ present: 'Loading',
+ summary: ToolCallSummaryKind.LOAD_TOOLS,
+ targetObject: 'tools'
+};
+
+export const TOOL_SEARCH_QUERY_PHRASING: ToolCallPhrasing = {
+ object: 'tools',
+ past: 'Searched',
+ present: 'Searching',
+ quoteTarget: true,
+ summary: ToolCallSummaryKind.SEARCH,
+ targetObject: 'tools for'
+};
+
+export const WEB_SEARCH_PHRASING: ToolCallPhrasing = {
+ object: 'the web',
+ past: 'Searched',
+ present: 'Searching',
+ quoteTarget: true,
+ summary: ToolCallSummaryKind.SEARCH,
+ targetObject: 'the web for'
+};
+
+function counted(n: number, singular: string, plural: string): string {
+ return `${n} ${n === 1 ? singular : plural}`;
+}
+
+/** Group summary clause per kind, in lower case; the summary capitalizes the first one. */
+export const TOOL_CALL_SUMMARY: Readonly<Record<ToolCallSummaryKind, (n: number) => string>> = {
+ [ToolCallSummaryKind.COMMAND]: (n) => `ran ${counted(n, 'command', 'commands')}`,
+ [ToolCallSummaryKind.EDIT]: (n) => `edited ${counted(n, 'file', 'files')}`,
+ [ToolCallSummaryKind.LOAD_TOOLS]: (n) => `loaded ${counted(n, 'tool', 'tools')}`,
+ [ToolCallSummaryKind.OTHER]: (n) => `used ${counted(n, 'tool', 'tools')}`,
+ [ToolCallSummaryKind.READ]: (n) => `read ${counted(n, 'file', 'files')}`,
+ [ToolCallSummaryKind.SCRIPT]: (n) => `ran ${counted(n, 'script', 'scripts')}`,
+ [ToolCallSummaryKind.SEARCH]: (n) => (n === 1 ? 'searched once' : `searched ${n} times`),
+ [ToolCallSummaryKind.VIEW]: (n) => `viewed ${counted(n, 'media file', 'media files')}`,
+ [ToolCallSummaryKind.WRITE]: (n) => `wrote ${counted(n, 'file', 'files')}`
+};
+
+/**
+ * Arg a call's line shows by default when the call has it: tools that want a
+ * readable line declare it in their own schema, and the line reads it as the
+ * model wrote it. Settings can pick another arg, globally or per tool.
+ */
+export const TOOL_CALL_SHOWN_ARG_DEFAULT = 'description';
+
+/** Per-tool choice that turns the shown arg off and keeps the sentence. */
+export const TOOL_CALL_SHOWN_ARG_NONE = '';
diff --git a/ui/apps/chat/src/lib/enums/index.ts b/ui/apps/chat/src/lib/enums/index.ts
index c92a906d0..1c42190aa 100644
--- a/ui/apps/chat/src/lib/enums/index.ts
+++ b/ui/apps/chat/src/lib/enums/index.ts
@@ -117,6 +117,7 @@ export {
GlobSearchType,
SearchChatsMessageSelection,
SearchChatsOrder,
+ ToolCallSummaryKind,
ToolSource,
ToolPermissionDecision,
ToolResponseField
diff --git a/ui/apps/chat/src/lib/enums/tools.enums.ts b/ui/apps/chat/src/lib/enums/tools.enums.ts
index 2bda68722..5049be5cb 100644
--- a/ui/apps/chat/src/lib/enums/tools.enums.ts
+++ b/ui/apps/chat/src/lib/enums/tools.enums.ts
@@ -67,3 +67,16 @@ export enum SearchChatsOrder {
ASC = 'asc',
DESC = 'desc'
}
+
+/** Bucket a tool call counts in for a tool-call group's summary line. */
+export enum ToolCallSummaryKind {
+ COMMAND = 'command',
+ EDIT = 'edit',
+ LOAD_TOOLS = 'load_tools',
+ OTHER = 'other',
+ READ = 'read',
+ SCRIPT = 'script',
+ SEARCH = 'search',
+ VIEW = 'view',
+ WRITE = 'write'
+}
diff --git a/ui/apps/chat/src/lib/hooks/use-stick-to-bottom.svelte.ts b/ui/apps/chat/src/lib/hooks/use-stick-to-bottom.svelte.ts
index cb7c48181..1ae4f6920 100644
--- a/ui/apps/chat/src/lib/hooks/use-stick-to-bottom.svelte.ts
+++ b/ui/apps/chat/src/lib/hooks/use-stick-to-bottom.svelte.ts
@@ -26,6 +26,38 @@ const FAR_FROM_BOTTOM_PX = 240;
* opening a preview), so it must not drag the viewport down with it.
*/
const INTERACTION_GRACE_MS = 400;
+/**
+ * How fast a glide closes the distance to the bottom: the time constant of an
+ * exponential ease, so it starts quickly and settles softly, and a target that
+ * moves mid-way ( late layout, the first tokens ) bends the motion instead of
+ * restarting it.
+ */
+const GLIDE_TIME_CONSTANT_MS = 90;
+/** A glide animates at least this long, to still be running when the new rows land. */
+const GLIDE_MIN_MS = 450;
+/** A glide that has not settled after animating this long ends with a jump. */
+const GLIDE_MAX_MS = 2000;
+/**
+ * After a glide, corrections this soon are glided too: measured heights and
+ * fonts settle a moment after the rows land, and a jump there reads as a glitch.
+ */
+const GLIDE_SETTLE_MS = 2500;
+/** A late frame advances the glide by no more than this, about two frames. */
+const GLIDE_MAX_FRAME_MS = 34;
+/** A glide ends once it has rested at the bottom this long. */
+const GLIDE_SETTLED_MS = 150;
+/** Close enough to the bottom for a glide to stop. */
+const GLIDE_DONE_PX = 0.5;
+const GLIDE_CANCEL_EVENTS = ['wheel', 'touchstart', 'keydown'] as const;
+const GLIDE_SCROLL_KEYS: readonly string[] = [
+ ' ',
+ 'ArrowDown',
+ 'ArrowUp',
+ 'End',
+ 'Home',
+ 'PageDown',
+ 'PageUp'
+];
/** Set on the scroller while the pin is its only scroll anchor. */
const STICK_ATTRIBUTE = 'data-stick-to-bottom';
const NATIVE_ANCHORING = typeof CSS !== 'undefined' && CSS.supports('overflow-anchor', 'none');
@@ -38,8 +70,25 @@ export class StickToBottom {
/** The reader is at the bottom, so new content should follow. */
stick = $state(true);
+ private cancelGlide = (event?: Event): void => {
+ if (this.glideFrame === null) return;
+
+ // typing the next message is not scrolling; only scroll keys outside a field are
+ if (event instanceof KeyboardEvent) {
+ const target = event.target as HTMLElement | null;
+ const typing = target?.isContentEditable || target?.matches?.('input, textarea, select');
+
+ if (typing || !GLIDE_SCROLL_KEYS.includes(event.key)) return;
+ }
+
+ this.stopGlide();
+ this.glideSettleUntil = 0;
+ this.measure();
+ };
private container: HTMLElement | undefined;
private enabled = true;
+ private glideFrame: number | null = null;
+ private glideSettleUntil = 0;
private graceTimer: ReturnType<typeof setTimeout> | undefined;
private lastScrollHeight = 0;
private lastScrollTop = 0;
@@ -51,11 +100,12 @@ export class StickToBottom {
};
private native = false;
private observer: ResizeObserver | null = null;
-
// -Infinity, not 0: performance.now() starts at page load, so 0 would read
// as a press during the first moments after a refresh, when a chat lands
private pressedAt = -Infinity;
+ private settleTimer: ReturnType<typeof setTimeout> | undefined;
+
/**
* Binds the scroller and the element whose growth should be followed.
* `content` defaults to the scroller's first child, which is what a panel
@@ -90,6 +140,9 @@ export class StickToBottom {
}
detach(): void {
+ this.stopGlide();
+ this.glideSettleUntil = 0;
+ clearTimeout(this.settleTimer);
this.observer?.disconnect();
this.observer = null;
clearTimeout(this.graceTimer);
@@ -111,6 +164,48 @@ export class StickToBottom {
return () => observer.disconnect();
}
+ /**
+ * Carries the reader to the bottom with a short eased scroll, for the moment
+ * a message is sent: the rows that land after this call slide into place
+ * instead of appearing there. The target is read again every frame, so
+ * content that is still settling bends the motion and never ends it with a
+ * jump. Any scroll input from the reader takes over at once.
+ *
+ * Why not `scrollToBottom('smooth')`: this is called before the new rows
+ * exist, so a native smooth scroll aims at the old bottom and ends there.
+ * When the rows land, `follow()` and the anchoring pin then snap to the new
+ * bottom in one frame, which is the jump this replaces; native smooth
+ * scrolling cannot be retargeted mid-flight, and it cannot hold either of
+ * those off. The press reset mirrors `scrollToBottom`: asking for the
+ * bottom outranks the press that led here.
+ */
+ glideToBottom(): void {
+ const el = this.container;
+
+ if (!el) return;
+
+ this.stick = true;
+ this.pressedAt = -Infinity;
+
+ if (
+ !this.enabled ||
+ typeof requestAnimationFrame === 'undefined' ||
+ window.matchMedia?.('(prefers-reduced-motion: reduce)').matches
+ ) {
+ this.scrollToBottom();
+
+ return;
+ }
+
+ this.atBottom = true;
+ this.farFromBottom = false;
+ this.glideSettleUntil = performance.now() + GLIDE_SETTLE_MS;
+ // once the window is over the pin anchors again, without waiting for a scroll
+ clearTimeout(this.settleTimer);
+ this.settleTimer = setTimeout(() => this.syncAnchor(), GLIDE_SETTLE_MS + 1);
+ this.startGlide();
+ }
+
/** Reader scrolls are the only thing that re-arms or stops following. */
handleScroll(): void {
this.measure();
@@ -143,12 +238,7 @@ export class StickToBottom {
* window's own height is the room it really shows.
*/
private distanceFromBottom(el: HTMLElement): number {
- const shown =
- el === document.documentElement
- ? Math.max(el.clientHeight, window.innerHeight)
- : el.clientHeight;
-
- return Math.max(0, el.scrollHeight - shown - el.scrollTop);
+ return Math.max(0, el.scrollHeight - this.shownHeight(el) - el.scrollTop);
}
private follow(ignoreGrace = false): void {
@@ -156,6 +246,21 @@ export class StickToBottom {
if (!el) return;
+ // a running glide reads the new bottom on its next frame
+ if (this.glideFrame !== null) return;
+
+ // shortly after a send, late layout is glided to as well
+ if (
+ this.enabled &&
+ this.stick &&
+ performance.now() < this.glideSettleUntil &&
+ this.distanceFromBottom(el) > GLIDE_DONE_PX
+ ) {
+ this.startGlide();
+
+ return;
+ }
+
const pressedRecently =
!ignoreGrace && performance.now() - this.pressedAt < INTERACTION_GRACE_MS;
const atBottom = this.distanceFromBottom(el) <= AT_BOTTOM_PX;
@@ -192,6 +297,14 @@ export class StickToBottom {
const height = el.scrollHeight;
const distance = this.distanceFromBottom(el);
+ // a glide is on its way to the bottom: its own steps are not the reader's
+ if (this.glideFrame !== null) {
+ this.lastScrollHeight = height;
+ this.lastScrollTop = top;
+
+ return;
+ }
+
this.atBottom = distance <= AT_BOTTOM_PX;
this.farFromBottom = distance > FAR_FROM_BOTTOM_PX;
@@ -206,13 +319,86 @@ export class StickToBottom {
this.syncAnchor();
}
- /** The pin anchors only while following, so a reader who scrolled up keeps their rows anchored. */
+ private shownHeight(el: HTMLElement): number {
+ return el === document.documentElement
+ ? Math.max(el.clientHeight, window.innerHeight)
+ : el.clientHeight;
+ }
+
+ private startGlide(): void {
+ const el = this.container;
+
+ if (!el || this.glideFrame !== null) return;
+
+ let previous = performance.now();
+ // time spent animating: a frame that arrives late ( the page was busy
+ // rendering the new rows ) counts as one frame, not as the wait before it
+ let elapsed = 0;
+ let settledFor = 0;
+ // kept apart from scrollTop, which rounds: steps under a pixel still add up
+ let position = el.scrollTop;
+
+ const step = (now: number): void => {
+ const dt = Math.min(now - previous, GLIDE_MAX_FRAME_MS);
+ const target = el.scrollHeight - this.shownHeight(el);
+
+ previous = now;
+ elapsed += dt;
+
+ // the browser moved the page itself ( its own anchoring, a clamp ): go on from there
+ if (Math.abs(el.scrollTop - position) > 1) position = el.scrollTop;
+
+ const remaining = target - position;
+
+ settledFor = Math.abs(remaining) <= GLIDE_DONE_PX ? settledFor + dt : 0;
+
+ if (elapsed >= GLIDE_MAX_MS || (elapsed >= GLIDE_MIN_MS && settledFor >= GLIDE_SETTLED_MS)) {
+ this.stopGlide();
+ el.scrollTop = el.scrollHeight;
+ this.measure();
+
+ return;
+ }
+
+ position += remaining * (1 - Math.exp(-dt / GLIDE_TIME_CONSTANT_MS));
+ el.scrollTop = position;
+ this.glideFrame = requestAnimationFrame(step);
+ };
+
+ for (const type of GLIDE_CANCEL_EVENTS) {
+ window.addEventListener(type, this.cancelGlide, { capture: true, passive: true });
+ }
+
+ this.glideFrame = requestAnimationFrame(step);
+ // no pin anchoring while gliding: the browser would jump to it
+ this.syncAnchor();
+ }
+
+ private stopGlide(): void {
+ if (this.glideFrame === null) return;
+
+ cancelAnimationFrame(this.glideFrame);
+ this.glideFrame = null;
+
+ for (const type of GLIDE_CANCEL_EVENTS) {
+ window.removeEventListener(type, this.cancelGlide, { capture: true });
+ }
+
+ this.syncAnchor();
+ }
+
+ /**
+ * The pin anchors only while following, so a reader who scrolled up keeps their rows
+ * anchored. Not during a glide or the settle window after it either: there the glide
+ * does the following, and the pin would get there first with a jump.
+ */
private syncAnchor(): void {
const pressedRecently = performance.now() - this.pressedAt < INTERACTION_GRACE_MS;
+ const gliding = this.glideFrame !== null || performance.now() < this.glideSettleUntil;
this.container?.toggleAttribute(
STICK_ATTRIBUTE,
- this.native && this.enabled && this.stick && !pressedRecently
+ this.native && this.enabled && this.stick && !pressedRecently && !gliding
);
}
}
diff --git a/ui/apps/chat/src/lib/services/migration.service.ts b/ui/apps/chat/src/lib/services/migration.service.ts
index 238e31f9a..dccb02da2 100644
--- a/ui/apps/chat/src/lib/services/migration.service.ts
+++ b/ui/apps/chat/src/lib/services/migration.service.ts
@@ -867,6 +867,40 @@ const searchChatsDefaultDisabledMigration: Migration = {
}
}
};
+const IN_PROGRESS_COLLAPSED_MIGRATION_ID = 'in-progress-collapsed-default-v1';
+/**
+ * Thoughts and tool calls now stay collapsed while a reply generates. The
+ * persisted config carries every key, so a saved `true` cannot be told apart
+ * from the old default: both keys are dropped once so the new default
+ * applies. That also resets anyone who had left them on by choice, which is
+ * the known cost of the change; they turn them back on in Settings.
+ */
+const inProgressCollapsedMigration: Migration = {
+ description: 'Collapse thoughts and tool calls while generating by default',
+ id: IN_PROGRESS_COLLAPSED_MIGRATION_ID,
+
+ async run(): Promise<void> {
+ const configRaw = localStorage.getItem(CONFIG_LOCALSTORAGE_KEY);
+
+ if (configRaw === null) return;
+
+ let config: Record<string, unknown>;
+
+ try {
+ config = JSON.parse(configRaw);
+ } catch {
+ // an unreadable config has no saved default to drop; without this
+ // the migration would fail and run again on every start
+ return;
+ }
+
+ if (!config || typeof config !== 'object') return;
+
+ delete config[SETTINGS_KEYS.SHOW_THOUGHT_IN_PROGRESS];
+ delete config[SETTINGS_KEYS.SHOW_TOOL_CALL_IN_PROGRESS];
+ localStorage.setItem(CONFIG_LOCALSTORAGE_KEY, JSON.stringify(config));
+ }
+};
const migrations: Migration[] = [
localStorageMigration,
idxdbMigration,
@@ -879,7 +913,8 @@ const migrations: Migration[] = [
renderKeysMigration,
modelOrgNameKeyMigration,
mcpServerOverridesToToolPolicyMigration,
- searchChatsDefaultDisabledMigration
+ searchChatsDefaultDisabledMigration,
+ inProgressCollapsedMigration
];
export const MigrationService = {
diff --git a/ui/apps/chat/src/lib/stores/agentic/gates.svelte.ts b/ui/apps/chat/src/lib/stores/agentic/gates.svelte.ts
index a7df5c878..217f9205b 100644
--- a/ui/apps/chat/src/lib/stores/agentic/gates.svelte.ts
+++ b/ui/apps/chat/src/lib/stores/agentic/gates.svelte.ts
@@ -11,7 +11,11 @@ import { ToolPermissionDecision } from '#lib/enums/index.ts';
// direct imports between stores, not via the barrel, to avoid circular deps
import { permissionsStore } from '#lib/stores/permissions.svelte.ts';
import { toolsStore } from '#lib/stores/tools.svelte.ts';
-import type { DatabaseMessageExtra, SteeringMessage } from '#lib/types/index.ts';
+import type {
+ DatabaseMessageExtra,
+ PendingPermissionRequest,
+ SteeringMessage
+} from '#lib/types/index.ts';
import { SvelteMap } from 'svelte/reactivity';
export class AgenticGates {
@@ -21,10 +25,7 @@ export class AgenticGates {
private pendingContinueRequests = new SvelteMap<string, boolean>();
/** Dedicated reactive state for pending permission requests (ensures immediate UI updates) */
- private pendingPermissions = new SvelteMap<
- string,
- { toolName: string; serverLabel: string } | null
- >();
+ private pendingPermissions = new SvelteMap<string, PendingPermissionRequest | null>();
/** Resolve functions for pending permission Promises; nothing derives from this map */
private permissionResolvers = new SvelteMap<string, (decision: ToolPermissionDecision) => void>();
@@ -67,9 +68,7 @@ export class AgenticGates {
return this.pendingContinueRequests.get(conversationId) ?? false;
}
- getPendingPermissionRequest(
- conversationId: string
- ): { toolName: string; serverLabel: string } | null {
+ getPendingPermissionRequest(conversationId: string): PendingPermissionRequest | null {
return this.pendingPermissions.get(conversationId) ?? null;
}
@@ -133,6 +132,7 @@ export class AgenticGates {
conversationId: string,
toolName: string,
serverLabel: string,
+ toolCallId: string,
signal?: AbortSignal
): Promise<ToolPermissionDecision> {
const permissionKey = toolsStore.getPermissionKey(toolName);
@@ -141,7 +141,7 @@ export class AgenticGates {
return ToolPermissionDecision.ONCE;
}
- this.pendingPermissions.set(conversationId, { serverLabel, toolName });
+ this.pendingPermissions.set(conversationId, { serverLabel, toolCallId, toolName });
return new Promise<ToolPermissionDecision>((resolve) => {
if (signal?.aborted) {
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 2eb93ad3a..b4e0fa335 100644
--- a/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts
+++ b/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts
@@ -46,6 +46,7 @@ import type {
AgenticMessage,
AgenticToolCallList,
AgenticToolPolicy,
+ PendingPermissionRequest,
SteeringMessage
} from '#lib/types/agentic.js';
import type {
@@ -93,6 +94,7 @@ function createDefaultSession(): AgenticSession {
lastError: null,
liveLlm: null,
pendingPermissionRequest: null,
+ startedAt: null,
streamingToolCall: null,
totalToolCalls: 0
};
@@ -144,6 +146,8 @@ function toAgenticMessages(messages: ApiChatMessageData[]): AgenticMessage[] {
}
class AgenticStore {
+ /** When each running flow started, keyed by its timings object; see buildFinalTimings */
+ private flowStarts = new WeakMap<ChatMessageAgenticTimings, number>();
// permission, continue and steering gates the loop waits on between turns
private gates = new AgenticGates();
private sessions = new SvelteMap<string, AgenticSession>();
@@ -243,9 +247,7 @@ class AgenticStore {
return this.gates.getPendingContinueRequest(conversationId);
}
- getPendingPermissionRequest(
- conversationId: string
- ): { toolName: string; serverLabel: string } | null {
+ getPendingPermissionRequest(conversationId: string): PendingPermissionRequest | null {
return this.gates.getPendingPermissionRequest(conversationId);
}
@@ -268,6 +270,11 @@ class AgenticStore {
return session;
}
+ /** When the running flow started (ms since epoch), or null when idle. */
+ getStartedAt(conversationId: string): number | null {
+ return this.sessions.get(conversationId)?.startedAt ?? null;
+ }
+
getStreamingToolCall(conversationId: string): { name: string; arguments: string } | null {
return this.sessions.get(conversationId)?.streamingToolCall ?? null;
}
@@ -358,6 +365,7 @@ class AgenticStore {
isRunning: true,
lastError: null,
liveLlm: null,
+ startedAt: Date.now(),
totalToolCalls: 0
});
@@ -386,7 +394,8 @@ class AgenticStore {
this.updateSession(conversationId, {
flowRootMessageId: null,
isRunning: false,
- liveLlm: null
+ liveLlm: null,
+ startedAt: null
});
if (hasMcpServers) {
@@ -413,8 +422,13 @@ class AgenticStore {
): ChatMessageTimings | undefined {
if (agenticTimings.toolCallsCount === 0) return capturedTimings;
+ const startedAt = this.flowStarts.get(agenticTimings);
+
return {
- agentic: agenticTimings,
+ agentic:
+ startedAt === undefined
+ ? agenticTimings
+ : { ...agenticTimings, totalMs: Date.now() - startedAt },
cache_n: capturedTimings?.cache_n,
predicted_ms: capturedTimings?.predicted_ms,
predicted_n: capturedTimings?.predicted_n,
@@ -461,6 +475,11 @@ class AgenticStore {
toolsMs: 0,
turns: 0
};
+
+ // the run's start travels with its timings, so every exit of the loop
+ // stamps the total task time without being handed it
+ this.flowStarts.set(agenticTimings, this.sessions.get(conversationId)?.startedAt ?? Date.now());
+
const maxTurns = agenticConfig.maxTurns;
const effectiveModel = options.model || modelsStore.models[0]?.model || '';
@@ -749,6 +768,7 @@ class AgenticStore {
conversationId,
toolName,
serverLabel,
+ toolCall.id,
signal
);
diff --git a/ui/apps/chat/src/lib/stores/index.ts b/ui/apps/chat/src/lib/stores/index.ts
index 3a2c5914c..eef37b252 100644
--- a/ui/apps/chat/src/lib/stores/index.ts
+++ b/ui/apps/chat/src/lib/stores/index.ts
@@ -31,6 +31,9 @@ export { contextStatsStore } from './chat/context-stats.svelte';
// AGENTIC (multi-turn tool orchestration)
export { agenticStore } from './agentic/index.svelte';
+// CONVERSATION MEDIA (one slideshow of the thread's images, audio and video)
+export { mediaGalleryStore } from './media-gallery.svelte';
+
// CONVERSATIONS
export { sidebarDragStore } from './sidebar-drag.svelte';
export { conversationsStore } from './conversations/index.svelte';
diff --git a/ui/apps/chat/src/lib/stores/mcp/index.svelte.ts b/ui/apps/chat/src/lib/stores/mcp/index.svelte.ts
index d65653a14..8b9536769 100644
--- a/ui/apps/chat/src/lib/stores/mcp/index.svelte.ts
+++ b/ui/apps/chat/src/lib/stores/mcp/index.svelte.ts
@@ -691,6 +691,7 @@ class MCPStore implements McpHealthHost {
}
/**
+ * @deprecated No caller any more: the tool call rows dropped their icons.
* Resolve the favicon URL for an MCP server by one of its tool names.
* Returns `null` if the tool is not provided by any configured MCP server,
* or if the owning server has no icon to show.
diff --git a/ui/apps/chat/src/lib/stores/media-gallery.svelte.ts b/ui/apps/chat/src/lib/stores/media-gallery.svelte.ts
new file mode 100644
index 000000000..d77ecc6e2
--- /dev/null
+++ b/ui/apps/chat/src/lib/stores/media-gallery.svelte.ts
@@ -0,0 +1,52 @@
+/**
+ * The conversation's media in one slideshow: every image, audio clip and video
+ * in the open thread, user attachments and tool results alike, in the order
+ * they appear. A thumbnail anywhere in the chat opens it at its own item.
+ */
+
+import { conversationsStore } from './conversations/index.svelte';
+import type { DatabaseMessageExtra } from '#lib/types/index.ts';
+import { isMediaExtra } from '#lib/utils/index.ts';
+
+/**
+ * Two references to one item: the same object, or the same data copied over.
+ * Reactive state hands out proxies, so the thumbnail's object is not always
+ * identical to the one in the thread, and the data is the fallback.
+ */
+function isSameItem(a: DatabaseMessageExtra, b: DatabaseMessageExtra): boolean {
+ if (a === b) return true;
+
+ if (a.type !== b.type || a.name !== b.name) return false;
+
+ const dataOf = (extra: DatabaseMessageExtra) =>
+ 'base64Url' in extra ? extra.base64Url : 'base64Data' in extra ? extra.base64Data : undefined;
+ const dataA = dataOf(a);
+ const dataB = dataOf(b);
+
+ // lengths first: two different files of the same name almost never share
+ // one, so the payloads themselves are compared only for a real match
+ return dataA !== undefined && dataA.length === dataB?.length && dataA === dataB;
+}
+
+class MediaGalleryStore {
+ index = $state(0);
+ items = $state<DatabaseMessageExtra[]>([]);
+ open = $state(false);
+
+ /**
+ * Opens the slideshow of the open conversation at `item`. An item not in the
+ * thread ( a draft, another chat ) opens on its own.
+ */
+ show(item: DatabaseMessageExtra): void {
+ const items = conversationsStore.activeMessages.flatMap((message) =>
+ (message.extra ?? []).filter(isMediaExtra)
+ );
+ const index = items.findIndex((candidate) => isSameItem(candidate, item));
+
+ this.items = index >= 0 ? items : [item];
+ this.index = Math.max(index, 0);
+ this.open = true;
+ }
+}
+
+export const mediaGalleryStore = new MediaGalleryStore();
diff --git a/ui/apps/chat/src/lib/types/agentic.d.ts b/ui/apps/chat/src/lib/types/agentic.d.ts
index d038da448..709b8f40e 100644
--- a/ui/apps/chat/src/lib/types/agentic.d.ts
+++ b/ui/apps/chat/src/lib/types/agentic.d.ts
@@ -67,6 +67,16 @@ export type AgenticChatCompletionRequest = Omit<ApiChatCompletionRequest, 'messa
tools?: ApiChatCompletionRequest['tools'];
};
+/**
+ * The tool call the loop is asking to run. The id names that exact call, so a
+ * card can show what would run, not a same-named call sitting next to it.
+ */
+export interface PendingPermissionRequest {
+ serverLabel: string;
+ toolCallId: string;
+ toolName: string;
+}
+
/**
* Per-conversation agentic session state.
* Enables parallel agentic flows across multiple chats.
@@ -77,7 +87,7 @@ export interface AgenticSession {
totalToolCalls: number;
lastError: Error | null;
streamingToolCall: { name: string; arguments: string } | null;
- pendingPermissionRequest: { toolName: string; serverLabel: string } | null;
+ pendingPermissionRequest: PendingPermissionRequest | null;
/** ID of the tool call whose output is currently being streamed back
* (e.g. exec_shell_command outputting to /tools?stream=true). Lets the
* matching tool renderer flip into live-update mode while chunks
@@ -89,6 +99,8 @@ export interface AgenticSession {
/** ID of the flow's first assistant message (the one the UI groups the
* whole run under); null when idle. */
flowRootMessageId: string | null;
+ /** When the running flow started (ms since epoch); null when idle. */
+ startedAt: number | null;
}
/**
diff --git a/ui/apps/chat/src/lib/types/chat.d.ts b/ui/apps/chat/src/lib/types/chat.d.ts
index a72a8dfff..ab6fe352a 100644
--- a/ui/apps/chat/src/lib/types/chat.d.ts
+++ b/ui/apps/chat/src/lib/types/chat.d.ts
@@ -116,6 +116,8 @@ export interface ChatMessageAgenticTimings {
toolsMs: number;
toolCalls?: ChatMessageToolCallTiming[];
perTurn?: ChatMessageAgenticTurnStats[];
+ /** Wall time of the whole task, from the prompt to the last token, waits included. */
+ totalMs?: number;
llm: {
predicted_n: number;
predicted_ms: number;
diff --git a/ui/apps/chat/src/lib/types/index.ts b/ui/apps/chat/src/lib/types/index.ts
index bfed7569c..b931f76ee 100644
--- a/ui/apps/chat/src/lib/types/index.ts
+++ b/ui/apps/chat/src/lib/types/index.ts
@@ -231,6 +231,7 @@ export type {
AgenticFlowParams,
AgenticFlowResult,
SteeringMessage,
+ PendingPermissionRequest,
AgenticSection,
ToolResultLine,
ContinueIntent
@@ -244,6 +245,8 @@ export type {
EditFileEdit,
EditFileMeta,
EditFileTitleMeta,
+ ToolCallDescription,
+ ToolCallPhrasing,
ToolEntry,
ToolGroup,
ToolUiEntry,
diff --git a/ui/apps/chat/src/lib/types/tools.d.ts b/ui/apps/chat/src/lib/types/tools.d.ts
index 4f1ab120a..a96a7e3ce 100644
--- a/ui/apps/chat/src/lib/types/tools.d.ts
+++ b/ui/apps/chat/src/lib/types/tools.d.ts
@@ -1,5 +1,5 @@
import type { OpenAIToolDefinition } from './mcp';
-import type { ToolSource } from '#lib/enums/index.ts';
+import type { ToolCallSummaryKind, ToolSource } from '#lib/enums/index.ts';
import type { Component } from 'svelte';
/**
@@ -81,3 +81,32 @@ export interface EditFileTitleMeta {
editsApplied?: number;
errorMessage?: string;
}
+
+/** How a tool call reads in the chat trace; see TOOL_CALL_PHRASING. */
+export interface ToolCallPhrasing {
+ /** Verb once the call is done, e.g. "Read". */
+ past: string;
+ /** Verb while the call runs, e.g. "Reading". */
+ present: string;
+ /** Words after the verb when the call has no target, e.g. "a file". */
+ object: string;
+ /** Words between the verb and the target, e.g. "for". */
+ targetObject?: string;
+ /** Show the target in quotes, for search terms. */
+ quoteTarget?: boolean;
+ summary: ToolCallSummaryKind;
+}
+
+/** A tool call as one plain sentence: label, then an optional target. */
+export interface ToolCallDescription {
+ /** Verb and object, e.g. "Read a file" or "Searched for". */
+ label: string;
+ /** What the call acted on, e.g. a file name or a search term. */
+ target?: string;
+ quoted: boolean;
+ summary: ToolCallSummaryKind;
+ /** How many things the call counts as in the group summary. */
+ count: number;
+ /** True when the label is the model's own description of the call. */
+ described?: boolean;
+}
diff --git a/ui/apps/chat/src/lib/utils/agentic.ts b/ui/apps/chat/src/lib/utils/agentic.ts
index f29164919..638d6aee8 100644
--- a/ui/apps/chat/src/lib/utils/agentic.ts
+++ b/ui/apps/chat/src/lib/utils/agentic.ts
@@ -620,3 +620,34 @@ export function classifyContinueIntent(messages: DatabaseMessage[], idx: number)
return { kind: ContinueIntentKind.RERUN_TURN, truncateAfter: idx - 1 };
}
+
+/**
+ * Whether a live reply shows its status row ( "Processing 40%" ) after its
+ * sections. The row shows only while nothing else in the reply is moving: a
+ * section that is still streaming already says what is happening, and text
+ * keeps streaming without a status. After a finished row the reply is waiting
+ * on the next turn, so the row shows even before a finer status is known.
+ *
+ * @param statusText - What the server is doing, empty while tokens stream, null when the reply is not live
+ * @param last - The reply's last section, if it has any
+ * @param isStreaming - Whether this reply is the one streaming
+ */
+export function showsReplyStatus(
+ statusText: string | null,
+ last: AgenticSection | undefined,
+ isStreaming: boolean
+): boolean {
+ if (statusText === null) return false;
+
+ if (!last) return true;
+
+ if (last.type === AgenticSectionType.REASONING_PENDING) return false;
+
+ const isToolCallInFlight =
+ last.type === AgenticSectionType.TOOL_CALL_PENDING ||
+ last.type === AgenticSectionType.TOOL_CALL_STREAMING;
+
+ if (isStreaming && isToolCallInFlight) return false;
+
+ return statusText !== '' || last.type !== AgenticSectionType.TEXT;
+}
diff --git a/ui/apps/chat/src/lib/utils/attachment-type.ts b/ui/apps/chat/src/lib/utils/attachment-type.ts
index b245bff42..11d9848c4 100644
--- a/ui/apps/chat/src/lib/utils/attachment-type.ts
+++ b/ui/apps/chat/src/lib/utils/attachment-type.ts
@@ -1,4 +1,5 @@
import { AttachmentType, FileTypeCategory } from '#lib/enums/index.ts';
+import type { DatabaseMessageExtraImageFile } from '#lib/types/index.ts';
import { getFileTypeCategory, getFileTypeCategoryByExtension } from '#lib/utils/index.ts';
/**
@@ -124,3 +125,21 @@ export function isVideoFile(
return false;
}
+
+/** The image attachments among `extras`, e.g. the images a tool call produced. */
+export function imageExtras(
+ extras: readonly DatabaseMessageExtra[] | undefined
+): DatabaseMessageExtraImageFile[] {
+ return (extras ?? []).filter(
+ (extra): extra is DatabaseMessageExtraImageFile => extra.type === AttachmentType.IMAGE
+ );
+}
+
+/** True for an attachment the media preview can show: an image, audio clip or video. */
+export function isMediaExtra(extra: DatabaseMessageExtra): boolean {
+ return (
+ extra.type === AttachmentType.IMAGE ||
+ extra.type === AttachmentType.AUDIO ||
+ extra.type === AttachmentType.VIDEO
+ );
+}
diff --git a/ui/apps/chat/src/lib/utils/index.ts b/ui/apps/chat/src/lib/utils/index.ts
index c6fdbb0d7..c1e2ee4a1 100644
--- a/ui/apps/chat/src/lib/utils/index.ts
+++ b/ui/apps/chat/src/lib/utils/index.ts
@@ -15,7 +15,15 @@ export { validateApiKey } from './api-key-validation';
// Attachment utilities
export { getAttachmentDisplayItems, isMcpPrompt, isMcpResource } from './attachment-display';
-export { isTextFile, isImageFile, isPdfFile, isAudioFile, isVideoFile } from './attachment-type';
+export {
+ imageExtras,
+ isAudioFile,
+ isImageFile,
+ isMediaExtra,
+ isPdfFile,
+ isTextFile,
+ isVideoFile
+} from './attachment-type';
// Textarea utilities
export { default as autoResizeTextarea } from './autoresize-textarea';
@@ -277,6 +285,7 @@ export {
splitSearchSummaryList,
hasAgenticContent,
isSectionExpandedByDefault,
+ showsReplyStatus,
classifyToolResult,
classifyContinueIntent
} from './agentic';
@@ -285,6 +294,7 @@ export {
export { computeLineDiff, prefixFor, renderUnifiedDiff, type DiffLine } from './compute-line-diff';
// Partial-incremental JSON parser for streaming tool arguments
+export { memoizeBounded } from './memoize-bounded';
export { parsePartialJsonArgs } from './parse-partial-json-args';
// `exec_shell_command` result parsing
@@ -337,6 +347,7 @@ export {
// This module only carries the helpers that genuinely cross tool
// boundaries (currently: parsing the tool-result blob into a JSON
// object).
+export { parseToolCallShownArgOverrides, toolCallShownArg } from './tool-call-shown-arg';
export { tryParseToolResultObject } from './tool-call-meta';
// Per-tool UI metadata (label + icon) used by the tool-call chrome.
diff --git a/ui/apps/chat/src/lib/utils/memoize-bounded.ts b/ui/apps/chat/src/lib/utils/memoize-bounded.ts
new file mode 100644
index 000000000..66959b75a
--- /dev/null
+++ b/ui/apps/chat/src/lib/utils/memoize-bounded.ts
@@ -0,0 +1,28 @@
+/**
+ * Memoizes `fn` by a string key, holding at most `maxSize` results: once full
+ * the cache is emptied, which is enough for values that are cheap to rebuild.
+ * `keyOf` returns null for a call that should not be cached.
+ */
+export function memoizeBounded<Args extends unknown[], Result>(
+ fn: (...args: Args) => Result,
+ keyOf: (...args: Args) => string | null,
+ maxSize: number
+): (...args: Args) => Result {
+ const cache = new Map<string, Result>();
+
+ return (...args) => {
+ const key = keyOf(...args);
+
+ if (key === null) return fn(...args);
+
+ if (cache.has(key)) return cache.get(key) as Result;
+
+ const result = fn(...args);
+
+ if (cache.size >= maxSize) cache.clear();
+
+ cache.set(key, result);
+
+ return result;
+ };
+}
diff --git a/ui/apps/chat/src/lib/utils/tool-call-shown-arg.ts b/ui/apps/chat/src/lib/utils/tool-call-shown-arg.ts
new file mode 100644
index 000000000..8a0ea300d
--- /dev/null
+++ b/ui/apps/chat/src/lib/utils/tool-call-shown-arg.ts
@@ -0,0 +1,39 @@
+import { SETTINGS_KEYS, TOOL_CALL_SHOWN_ARG_NONE } from '#lib/constants/index.ts';
+import type { SettingsConfigType } from '#lib/types/index.ts';
+
+/** The per-tool choices, by tool name; an unreadable value counts as none. */
+export function parseToolCallShownArgOverrides(raw: unknown): Record<string, string> {
+ if (typeof raw !== 'string' || !raw.trim()) return {};
+
+ try {
+ const parsed: unknown = JSON.parse(raw);
+
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {};
+
+ return Object.fromEntries(
+ Object.entries(parsed).filter(
+ (entry): entry is [string, string] => typeof entry[1] === 'string'
+ )
+ );
+ } catch {
+ return {};
+ }
+}
+
+/**
+ * The arg a tool's calls show in their line: the tool's own choice when it
+ * has one, else the global one; null when the line is the plain sentence.
+ */
+export function toolCallShownArg(
+ config: Partial<SettingsConfigType>,
+ toolName: string | undefined
+): string | null {
+ const overrides = parseToolCallShownArgOverrides(
+ config[SETTINGS_KEYS.TOOL_CALL_SHOWN_ARG_OVERRIDES]
+ );
+ const own = toolName !== undefined ? overrides[toolName] : undefined;
+ const global = config[SETTINGS_KEYS.TOOL_CALL_SHOWN_ARG];
+ const arg = own ?? (typeof global === 'string' ? global : TOOL_CALL_SHOWN_ARG_NONE);
+
+ return arg.trim() || null;
+}
diff --git a/ui/apps/chat/tests/client/README-perf.md b/ui/apps/chat/tests/client/README-perf.md
index 198b21956..24299e65d 100644
--- a/ui/apps/chat/tests/client/README-perf.md
+++ b/ui/apps/chat/tests/client/README-perf.md
@@ -4,7 +4,7 @@ Two tiers, both reusing the existing vitest projects (see `vite.config.ts`).
## Tier 1 - `agentic-stream.perf.svelte.test.ts` (project: `client`, real Chromium)
-Mounts `ChatMessageAgenticContent` and replays a stream, replacing the message
+Mounts `ChatMessageAgentTrace` and replays a stream, replacing the message
object on each chunk exactly as the real pipeline does:
- `chat.svelte.ts` `updateStreamingUI()` runs per SSE chunk
diff --git a/ui/apps/chat/tests/client/agentic-stream.perf.svelte.test.ts b/ui/apps/chat/tests/client/agentic-stream.perf.svelte.test.ts
index 70dc6a6c5..82f060aa2 100644
--- a/ui/apps/chat/tests/client/agentic-stream.perf.svelte.test.ts
+++ b/ui/apps/chat/tests/client/agentic-stream.perf.svelte.test.ts
@@ -1,6 +1,6 @@
// Tier 1 perf harness for the agentic thread.
//
-// Drives ChatMessageAgenticContent the way the real streaming pipeline does:
+// Drives ChatMessageAgentTrace the way the real streaming pipeline does:
// chat.svelte.ts -> conversations.svelte.ts:184 replaces the message object per
// SSE chunk (`{ ...old, ...updates }`), which changes prop identity and cascades
// through deriveAgenticSections into every tool-call block in the message.
diff --git a/ui/apps/chat/tests/client/assistant-response.svelte.test.ts b/ui/apps/chat/tests/client/assistant-response.svelte.test.ts
new file mode 100644
index 000000000..f587a9577
--- /dev/null
+++ b/ui/apps/chat/tests/client/assistant-response.svelte.test.ts
@@ -0,0 +1,63 @@
+// Guards the two ways a reply renders: a basic chat reply is its reasoning and
+// its answer (ChatMessageAssistantResponse), with no trace rows; a reply that
+// called tools is an Agent Trace (ChatMessageAgentTrace), with its calls
+// grouped. hasAgenticContent is what tells them apart.
+
+import ChatMessageAssistantResponse from '#lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistantResponse.svelte';
+import ChatMessageAgentTrace from '#lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte';
+import { MessageRole, MessageType } from '#lib/enums/index.ts';
+import type { DatabaseMessage } from '#lib/types/index.ts';
+import { hasAgenticContent } from '#lib/utils/index.ts';
+import { tick } from 'svelte';
+import { describe, expect, it } from 'vitest';
+import { render } from 'vitest-browser-svelte';
+
+function reply(overrides: Partial<DatabaseMessage> = {}): DatabaseMessage {
+ return {
+ children: [],
+ content: 'The answer is 42.',
+ convId: 'conv-1',
+ id: 'assistant-1',
+ parent: null,
+ reasoningContent: 'Thinking it over.',
+ role: MessageRole.ASSISTANT,
+ timestamp: 0,
+ toolCalls: '',
+ type: MessageType.TEXT,
+ ...overrides
+ };
+}
+
+const withTools = reply({
+ toolCalls: JSON.stringify([
+ { function: { arguments: '{"path":"a.ts"}', name: 'read_file' }, id: 'c1' },
+ { function: { arguments: '{"path":"b.ts"}', name: 'read_file' }, id: 'c2' }
+ ])
+});
+
+describe('assistant reply views', () => {
+ it('treats only a reply that called tools as an agent trace', () => {
+ expect(hasAgenticContent(reply())).toBe(false);
+ expect(hasAgenticContent(withTools)).toBe(true);
+ });
+
+ it('renders a basic reply as its reasoning and its answer', async () => {
+ const { container } = render(ChatMessageAssistantResponse, { message: reply() });
+
+ await tick();
+
+ expect(container.textContent).toContain('Reasoning');
+ // the answer renders as markdown, which settles a moment later
+ await expect.poll(() => container.textContent).toContain('The answer is 42.');
+ expect(container.querySelector('.tool-call-group')).toBeNull();
+ });
+
+ it('renders a reply with tool calls as a grouped trace', async () => {
+ const { container } = render(ChatMessageAgentTrace, { message: withTools });
+
+ await tick();
+
+ expect(container.querySelector('.tool-call-group')).not.toBeNull();
+ expect(container.textContent).toContain('Read 2 files');
+ });
+});
diff --git a/ui/apps/chat/tests/client/components/AgenticPerfWrapper.svelte b/ui/apps/chat/tests/client/components/AgenticPerfWrapper.svelte
index ac41c8ffa..88abff932 100644
--- a/ui/apps/chat/tests/client/components/AgenticPerfWrapper.svelte
+++ b/ui/apps/chat/tests/client/components/AgenticPerfWrapper.svelte
@@ -1,12 +1,12 @@
<script lang="ts">
import { perfState } from './agentic-perf-state.svelte';
import * as Tooltip from '@ggml-org/llama-ui/ui/tooltip';
- import ChatMessageAgenticContent from '#lib/components/app/chat/ChatMessages/ChatMessageAgenticContent.svelte';
+ import ChatMessageAgentTrace from '#lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte';
</script>
<Tooltip.Provider>
{#if perfState.message}
- <ChatMessageAgenticContent
+ <ChatMessageAgentTrace
isLastAssistantMessage
isStreaming={perfState.isStreaming}
message={perfState.message}
diff --git a/ui/apps/chat/tests/client/exec-shell-command-streaming.svelte.test.ts b/ui/apps/chat/tests/client/exec-shell-command-streaming.svelte.test.ts
index 024dd53e9..0503f8e2e 100644
--- a/ui/apps/chat/tests/client/exec-shell-command-streaming.svelte.test.ts
+++ b/ui/apps/chat/tests/client/exec-shell-command-streaming.svelte.test.ts
@@ -1,11 +1,12 @@
-// Guards the exec_shell_command title while the call is still being
-// generated: the command must stream into the terminal title from the
-// first character (args arrive as partial JSON), with a blinking cursor
-// while the args are incomplete, and the conversation cwd standing in
-// for the x-tool-cwd value that only arrives with the result message.
+// Guards the exec_shell_command block while the call is still being
+// generated: the command must stream into the title and the terminal's
+// prompt line from the first character (args arrive as partial JSON), with
+// a blinking cursor while the args are incomplete, and the conversation cwd
+// standing in for the x-tool-cwd value that only arrives with the result
+// message.
import ChatMessageToolCallBlockExecShellCommand from '#lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockExecShellCommand.svelte';
-import ChatMessageAgenticContent from '#lib/components/app/chat/ChatMessages/ChatMessageAgenticContent.svelte';
+import ChatMessageAgentTrace from '#lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte';
import { SETTINGS_KEYS } from '#lib/constants/index.ts';
import { AgenticSectionType, BuiltInTool, MessageRole, MessageType } from '#lib/enums/index.ts';
import { conversationsStore, settingsStore } from '#lib/stores/index.ts';
@@ -55,6 +56,10 @@ function triggerText(container: Element): string {
return container.querySelector('[data-slot="collapsible-trigger"]')?.textContent ?? '';
}
+function promptText(container: Element): string {
+ return container.querySelector('.exec-prompt-line')?.textContent ?? '';
+}
+
function hasCursor(container: Element): boolean {
return container.querySelector('.exec-cursor') !== null;
}
@@ -80,7 +85,7 @@ describe('exec_shell_command streaming title', () => {
});
it('streams the partial command into the title with a cursor', async () => {
- const { container } = render(ChatMessageAgenticContent, {
+ const { container } = render(ChatMessageAgentTrace, {
isLastAssistantMessage: true,
isStreaming: true,
message: messageWithArgs('{"command":"git sta'),
@@ -89,16 +94,15 @@ describe('exec_shell_command streaming title', () => {
await tick();
- const title = triggerText(container);
-
- expect(title).toContain('git sta');
- expect(title).toContain('$');
- expect(title).toContain(CWD);
+ expect(triggerText(container)).toContain('git sta');
+ expect(promptText(container)).toContain('git sta');
+ expect(promptText(container)).toContain('$');
+ expect(promptText(container)).toContain(CWD);
expect(hasCursor(container)).toBe(true);
});
it('drops the cursor once the args JSON is complete', async () => {
- const screen = render(ChatMessageAgenticContent, {
+ const screen = render(ChatMessageAgentTrace, {
isLastAssistantMessage: true,
isStreaming: true,
message: messageWithArgs('{"command":"git sta'),
@@ -122,7 +126,7 @@ describe('exec_shell_command streaming title', () => {
});
it('switches the prompt from the conversation cwd to the persisted one', async () => {
- const screen = render(ChatMessageAgenticContent, {
+ const screen = render(ChatMessageAgentTrace, {
isLastAssistantMessage: true,
isStreaming: true,
message: messageWithArgs('{"command":"git status"}'),
@@ -131,7 +135,7 @@ describe('exec_shell_command streaming title', () => {
await tick();
- expect(triggerText(screen.container)).toContain(CWD);
+ expect(promptText(screen.container)).toContain(CWD);
// Result message lands: its x-tool-cwd takes over the prompt.
screen.rerender({
@@ -142,12 +146,12 @@ describe('exec_shell_command streaming title', () => {
});
await tick();
- expect(triggerText(screen.container)).toContain('/other/dir');
- expect(triggerText(screen.container)).not.toContain(CWD);
+ expect(promptText(screen.container)).toContain('/other/dir');
+ expect(promptText(screen.container)).not.toContain(CWD);
});
it('shows the executing label only after the command finishes streaming', async () => {
- const screen = render(ChatMessageAgenticContent, {
+ const screen = render(ChatMessageAgentTrace, {
isLastAssistantMessage: true,
isStreaming: true,
message: messageWithArgs('{"command":"git sta'),
@@ -198,7 +202,7 @@ describe('exec_shell_command streaming title', () => {
// writes growing toolCalls strings into the same store row per delta.
conversationsStore.activeMessages = [messageWithArgs('')];
- const screen = render(ChatMessageAgenticContent, {
+ const screen = render(ChatMessageAgentTrace, {
isLastAssistantMessage: true,
isStreaming: true,
message: conversationsStore.activeMessages[0]!,
@@ -232,7 +236,7 @@ describe('exec_shell_command interrupted call', () => {
});
it('marks a call without a result as interrupted once streaming stops', async () => {
- const { container } = render(ChatMessageAgenticContent, {
+ const { container } = render(ChatMessageAgentTrace, {
isLastAssistantMessage: true,
isStreaming: false,
message: messageWithArgs('{"command":"git status"}'),
@@ -249,7 +253,7 @@ describe('exec_shell_command interrupted call', () => {
it('marks a command stopped before any output as interrupted', async () => {
// exec_shell_command creates its result message before running, so a
// stop mid-run leaves an empty result rather than none.
- const { container } = render(ChatMessageAgenticContent, {
+ const { container } = render(ChatMessageAgentTrace, {
isLastAssistantMessage: true,
isStreaming: false,
message: messageWithArgs('{"command":"sleep 40"}'),
@@ -263,7 +267,7 @@ describe('exec_shell_command interrupted call', () => {
});
it('does not keep spinning in an earlier message while a newer reply streams', async () => {
- const { container } = render(ChatMessageAgenticContent, {
+ const { container } = render(ChatMessageAgentTrace, {
isLastAssistantMessage: false,
isStreaming: true,
message: messageWithArgs('{"command":"git status"}'),
diff --git a/ui/apps/chat/tests/client/media-gallery.svelte.test.ts b/ui/apps/chat/tests/client/media-gallery.svelte.test.ts
new file mode 100644
index 000000000..3a6279c25
--- /dev/null
+++ b/ui/apps/chat/tests/client/media-gallery.svelte.test.ts
@@ -0,0 +1,75 @@
+// Guards the conversation slideshow: a thumbnail opens every image, audio clip
+// and video in the open thread, in thread order, at the item that was clicked,
+// whether it came from a user attachment or a tool result.
+
+import { AttachmentType, MessageRole, MessageType } from '#lib/enums/index.ts';
+import { conversationsStore, mediaGalleryStore } from '#lib/stores/index.ts';
+import type { DatabaseMessage, DatabaseMessageExtra } from '#lib/types/index.ts';
+import { afterEach, describe, expect, it } from 'vitest';
+
+function image(name: string): DatabaseMessageExtra {
+ return { base64Url: `data:image/png;base64,${name}`, name, type: AttachmentType.IMAGE };
+}
+
+function message(id: string, role: MessageRole, extra: DatabaseMessageExtra[]): DatabaseMessage {
+ return {
+ children: [],
+ content: '',
+ convId: 'conv-1',
+ extra,
+ id,
+ parent: null,
+ role,
+ timestamp: 0,
+ toolCalls: '',
+ type: MessageType.TEXT
+ };
+}
+
+afterEach(() => {
+ conversationsStore.activeMessages = [];
+ mediaGalleryStore.open = false;
+});
+
+describe('mediaGalleryStore', () => {
+ it('opens the media of the whole thread at the clicked item', () => {
+ const pasted = image('pasted');
+ const shot = image('shot');
+ const text: DatabaseMessageExtra = {
+ content: 'x',
+ name: 'notes.txt',
+ type: AttachmentType.TEXT
+ };
+
+ conversationsStore.activeMessages = [
+ message('u1', MessageRole.USER, [pasted, text]),
+ message('t1', MessageRole.TOOL, [shot])
+ ];
+
+ mediaGalleryStore.show(shot);
+
+ expect(mediaGalleryStore.open).toBe(true);
+ expect(mediaGalleryStore.items).toEqual([pasted, shot]);
+ expect(mediaGalleryStore.index).toBe(1);
+ });
+
+ it('finds an item passed as a copy of the stored one', () => {
+ conversationsStore.activeMessages = [message('t1', MessageRole.TOOL, [image('a'), image('b')])];
+
+ mediaGalleryStore.show({ ...image('b') });
+
+ expect(mediaGalleryStore.index).toBe(1);
+ expect(mediaGalleryStore.items).toHaveLength(2);
+ });
+
+ it('opens an item outside the thread on its own', () => {
+ conversationsStore.activeMessages = [message('t1', MessageRole.TOOL, [image('a')])];
+
+ const stray = image('elsewhere');
+
+ mediaGalleryStore.show(stray);
+
+ expect(mediaGalleryStore.items).toEqual([stray]);
+ expect(mediaGalleryStore.index).toBe(0);
+ });
+});
diff --git a/ui/apps/chat/tests/client/permission-request-command.svelte.test.ts b/ui/apps/chat/tests/client/permission-request-command.svelte.test.ts
new file mode 100644
index 000000000..b804a991b
--- /dev/null
+++ b/ui/apps/chat/tests/client/permission-request-command.svelte.test.ts
@@ -0,0 +1,67 @@
+// Guards what the reader approves: the trace row of a shell call may show the
+// model's own description of it, so the permission card must show the command
+// that would actually run, and the row must keep the command beside the
+// description.
+
+import ChatMessageActionCardPermissionRequest from '#lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardPermissionRequest.svelte';
+import ChatMessageAgentTrace from '#lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte';
+import { BuiltInTool, MessageRole, MessageType } from '#lib/enums/index.ts';
+import type { DatabaseMessage } from '#lib/types/index.ts';
+import { tick } from 'svelte';
+import { describe, expect, it } from 'vitest';
+import { render } from 'vitest-browser-svelte';
+
+const COMMAND = 'rm -rf ./build';
+const DESCRIPTION = 'List files';
+
+function shellCall(): DatabaseMessage {
+ return {
+ children: [],
+ content: '',
+ convId: 'conv-1',
+ id: 'assistant-1',
+ parent: null,
+ role: MessageRole.ASSISTANT,
+ timestamp: 0,
+ toolCalls: JSON.stringify([
+ {
+ function: {
+ arguments: JSON.stringify({ command: COMMAND, description: DESCRIPTION }),
+ name: BuiltInTool.SERVER_EXEC_SHELL_COMMAND
+ },
+ id: 'c1'
+ }
+ ]),
+ type: MessageType.TEXT
+ };
+}
+
+describe('approving a shell command', () => {
+ it('shows the command in the permission card', async () => {
+ const { container } = render(ChatMessageActionCardPermissionRequest, {
+ command: COMMAND,
+ onDecision: () => {},
+ serverLabel: 'Server Tools',
+ toolName: BuiltInTool.SERVER_EXEC_SHELL_COMMAND
+ });
+
+ await tick();
+
+ expect(container.querySelector('pre')?.textContent).toBe(COMMAND);
+ });
+
+ it('keeps the command beside a model description in the collapsed row', async () => {
+ const { container } = render(ChatMessageAgentTrace, {
+ isLastAssistantMessage: true,
+ isStreaming: true,
+ message: shellCall()
+ });
+
+ await tick();
+
+ const title = container.querySelector('[data-slot="collapsible-trigger"]')?.textContent ?? '';
+
+ expect(title).toContain(DESCRIPTION);
+ expect(title).toContain(COMMAND);
+ });
+});
diff --git a/ui/apps/chat/tests/client/stick-to-bottom.svelte.test.ts b/ui/apps/chat/tests/client/stick-to-bottom.svelte.test.ts
index cc8589e44..d229bba0f 100644
--- a/ui/apps/chat/tests/client/stick-to-bottom.svelte.test.ts
+++ b/ui/apps/chat/tests/client/stick-to-bottom.svelte.test.ts
@@ -1,7 +1,8 @@
// Guards the follow rules of StickToBottom: right after a press, growth of the
// content stays put (the reader expanded something), while growth of an element
// passed to followSizeOf - the chat form expanding on the reader's click - is
-// still followed, so the latest message stays in view above it.
+// still followed, so the latest message stays in view above it. A send glides to
+// the bottom: eased, never jumping, and handed back the moment the reader scrolls.
import { createStickToBottom } from '#lib/hooks/use-stick-to-bottom.svelte.ts';
import { afterEach, describe, expect, it } from 'vitest';
@@ -47,6 +48,26 @@ async function resizeObserved() {
await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
}
+function frame() {
+ return new Promise((resolve) => requestAnimationFrame(resolve));
+}
+
+/**
+ * Waits until the container rests at its bottom. A glide counts animated
+ * time, not wall time, so a runner that drops frames takes longer to get
+ * there: the deadline is only a guard against a glide that never arrives,
+ * set far beyond what one can take.
+ */
+const SETTLE_DEADLINE_MS = 20_000;
+
+async function settled(container: HTMLElement) {
+ const deadline = performance.now() + SETTLE_DEADLINE_MS;
+
+ while (distanceFromBottom(container) > 1 && performance.now() < deadline) {
+ await frame();
+ }
+}
+
function distanceFromBottom(el: HTMLElement) {
return el.scrollHeight - el.clientHeight - el.scrollTop;
}
@@ -86,4 +107,83 @@ describe('StickToBottom', () => {
expect(container.scrollTop).toBe(0);
});
+
+ it('glides to the new bottom after a send instead of jumping there', async () => {
+ const { container, content, stick } = setup();
+
+ stick.glideToBottom();
+ content.style.height = '1400px';
+
+ const tops: number[] = [];
+
+ // the first frames after the growth are on their way, not there yet
+ await frame();
+ tops.push(container.scrollTop);
+ await frame();
+ tops.push(container.scrollTop);
+
+ expect(distanceFromBottom(container)).toBeGreaterThan(200);
+
+ await settled(container);
+
+ for (let i = 0; i < 5; i++) {
+ tops.push(container.scrollTop);
+ await frame();
+ }
+
+ expect(distanceFromBottom(container)).toBeLessThanOrEqual(1);
+ // only ever down: no overshoot, no step back
+ expect(tops).toEqual([...tops].sort((a, b) => a - b));
+ });
+
+ it('glides to layout that settles shortly after a send', async () => {
+ const { container, content, stick } = setup();
+
+ stick.glideToBottom();
+ content.style.height = '1400px';
+ await settled(container);
+
+ content.style.height = '1700px';
+ await resizeObserved();
+
+ expect(distanceFromBottom(container)).toBeGreaterThan(100);
+
+ await settled(container);
+
+ expect(distanceFromBottom(container)).toBeLessThanOrEqual(1);
+ });
+
+ it('hands the page back the moment the reader scrolls', async () => {
+ const { container, content, stick } = setup();
+
+ stick.glideToBottom();
+ content.style.height = '1400px';
+ await frame();
+ await frame();
+ window.dispatchEvent(new WheelEvent('wheel'));
+
+ const top = container.scrollTop;
+
+ await resizeObserved();
+ await frame();
+
+ expect(container.scrollTop).toBe(top);
+ expect(distanceFromBottom(container)).toBeGreaterThan(200);
+ });
+
+ it('keeps gliding while the reader types the next message', async () => {
+ const { container, content, stick } = setup();
+ const field = document.createElement('textarea');
+
+ document.body.append(field);
+ cleanup.push(() => field.remove());
+
+ stick.glideToBottom();
+ content.style.height = '1400px';
+ await frame();
+ field.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: ' ' }));
+ await settled(container);
+
+ expect(distanceFromBottom(container)).toBeLessThanOrEqual(1);
+ });
});
diff --git a/ui/apps/chat/tests/client/task-timer.svelte.test.ts b/ui/apps/chat/tests/client/task-timer.svelte.test.ts
new file mode 100644
index 000000000..5c248cc2f
--- /dev/null
+++ b/ui/apps/chat/tests/client/task-timer.svelte.test.ts
@@ -0,0 +1,84 @@
+// 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/client/tool-call-in-progress.svelte.test.ts b/ui/apps/chat/tests/client/tool-call-in-progress.svelte.test.ts
index 3d8b350df..25b3a164a 100644
--- a/ui/apps/chat/tests/client/tool-call-in-progress.svelte.test.ts
+++ b/ui/apps/chat/tests/client/tool-call-in-progress.svelte.test.ts
@@ -7,7 +7,7 @@
// finished calls open and wins on its own. A manual toggle always overrides the
// default, in both directions.
-import ChatMessageAgenticContent from '#lib/components/app/chat/ChatMessages/ChatMessageAgenticContent.svelte';
+import ChatMessageAgentTrace from '#lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte';
import { COLLAPSIBLE_TRANSITION_MS, SETTINGS_KEYS } from '#lib/constants/index.ts';
import { MessageRole, MessageType } from '#lib/enums/index.ts';
import { settingsStore } from '#lib/stores/index.ts';
@@ -94,7 +94,7 @@ describe('Show tool call in progress', () => {
it('expands a call that is still executing when the setting is on', async () => {
setSettings({ alwaysShow: false, inProgress: true });
- const { container } = render(ChatMessageAgenticContent, {
+ const { container } = render(ChatMessageAgentTrace, {
isLastAssistantMessage: true,
isStreaming: true,
message: assistantMessage(),
@@ -107,7 +107,7 @@ describe('Show tool call in progress', () => {
});
it('keeps the call collapsed while executing when the setting is off', async () => {
- const { container } = render(ChatMessageAgenticContent, {
+ const { container } = render(ChatMessageAgentTrace, {
isLastAssistantMessage: true,
isStreaming: true,
message: assistantMessage(),
@@ -124,7 +124,7 @@ describe('Show tool call in progress', () => {
it('folds the call back when its result arrives', async () => {
setSettings({ alwaysShow: false, inProgress: true });
- const screen = render(ChatMessageAgenticContent, {
+ const screen = render(ChatMessageAgentTrace, {
isLastAssistantMessage: true,
isStreaming: true,
message: assistantMessage(),
@@ -153,7 +153,7 @@ describe('Show tool call in progress', () => {
it('keeps the manual choice once the result arrives', async () => {
setSettings({ alwaysShow: false, inProgress: true });
- const screen = render(ChatMessageAgenticContent, {
+ const screen = render(ChatMessageAgentTrace, {
isLastAssistantMessage: true,
isStreaming: true,
message: assistantMessage(),
@@ -180,7 +180,7 @@ describe('Show tool call in progress', () => {
it('still expands a finished call when "always show" is on', async () => {
setSettings({ alwaysShow: true, inProgress: false });
- const { container } = render(ChatMessageAgenticContent, {
+ const { container } = render(ChatMessageAgentTrace, {
isLastAssistantMessage: true,
isStreaming: true,
message: assistantMessage(),
@@ -195,7 +195,7 @@ describe('Show tool call in progress', () => {
it('lets a manual collapse win over the in-progress default', async () => {
setSettings({ alwaysShow: false, inProgress: true });
- const screen = render(ChatMessageAgenticContent, {
+ const screen = render(ChatMessageAgentTrace, {
isLastAssistantMessage: true,
isStreaming: true,
message: assistantMessage(),
@@ -213,7 +213,7 @@ describe('Show tool call in progress', () => {
});
it('lets a manual expand win over the collapsed default', async () => {
- const screen = render(ChatMessageAgenticContent, {
+ const screen = render(ChatMessageAgentTrace, {
isLastAssistantMessage: true,
isStreaming: true,
message: assistantMessage(),
diff --git a/ui/apps/chat/tests/stories/chat/messages/ChatMessageToolCallBlock.stories.svelte b/ui/apps/chat/tests/stories/chat/messages/ChatMessageToolCallBlock.stories.svelte
index 0d0accc04..ca71b4862 100644
--- a/ui/apps/chat/tests/stories/chat/messages/ChatMessageToolCallBlock.stories.svelte
+++ b/ui/apps/chat/tests/stories/chat/messages/ChatMessageToolCallBlock.stories.svelte
@@ -20,6 +20,7 @@
runJavascriptSection,
searchResultsSection,
seedChatStory,
+ toolSearchSection,
writeFileSection
} from './fixtures';
import { defineMeta } from '@storybook/addon-svelte-csf';
@@ -125,6 +126,10 @@
<ChatMessageToolCallBlock isStreaming={false} open section={readMediaSection} />
</StateGalleryItem>
+ <StateGalleryItem label="Load tools on demand" note="tool_search select query">
+ <ChatMessageToolCallBlock isStreaming={false} open section={toolSearchSection} />
+ </StateGalleryItem>
+
<StateGalleryItem label="Search results">
<ChatMessageToolCallBlock isStreaming={false} open section={searchResultsSection} />
</StateGalleryItem>
diff --git a/ui/apps/chat/tests/stories/chat/messages/ChatMessageToolCallGroup.stories.svelte b/ui/apps/chat/tests/stories/chat/messages/ChatMessageToolCallGroup.stories.svelte
new file mode 100644
index 000000000..848eac7d6
--- /dev/null
+++ b/ui/apps/chat/tests/stories/chat/messages/ChatMessageToolCallGroup.stories.svelte
@@ -0,0 +1,70 @@
+<script lang="ts" module>
+ import {
+ seedChatStory,
+ TOOL_GROUP_EXECUTING_ID,
+ toolGroupImageSections,
+ toolGroupMcpSections,
+ toolGroupRunningSections,
+ toolGroupSections,
+ toolGroupShellRunningSections
+ } from './fixtures';
+ import ToolCallGroupStoryHost from './ToolCallGroupStoryHost.svelte';
+ import { defineMeta } from '@storybook/addon-svelte-csf';
+ import ChatMessageToolCallGroup from '#lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallGroup.svelte';
+ import StateGallery from '$llama-ui-stories/helpers/StateGallery.svelte';
+ import StateGalleryItem from '$llama-ui-stories/helpers/StateGalleryItem.svelte';
+
+ const { Story } = defineMeta({
+ component: ChatMessageToolCallGroup,
+ parameters: {
+ layout: 'padded'
+ },
+ title: 'Llama Chat/Chat/ChatMessages/ChatMessageToolCallGroup'
+ });
+</script>
+
+<Story asChild beforeEach={() => seedChatStory()} name="States">
+ <StateGallery columns={1} title="Done">
+ <StateGalleryItem label="Collapsed" note="a summary of what the calls did">
+ <ToolCallGroupStoryHost sections={toolGroupSections} />
+ </StateGalleryItem>
+
+ <StateGalleryItem label="Expanded" note="one row per call">
+ <ToolCallGroupStoryHost open sections={toolGroupSections} />
+ </StateGalleryItem>
+
+ <StateGalleryItem
+ label="With images"
+ note="a thumbnail per image under the title, a carousel when they overflow"
+ >
+ <ToolCallGroupStoryHost sections={toolGroupImageSections} />
+ </StateGalleryItem>
+
+ <StateGalleryItem label="MCP and on-demand tools" note="tool_search and generic tools">
+ <ToolCallGroupStoryHost open sections={toolGroupMcpSections} />
+ </StateGalleryItem>
+ </StateGallery>
+
+ <StateGallery columns={1} title="Running">
+ <StateGalleryItem label="Reading a file" note="what happens now">
+ <ToolCallGroupStoryHost isStreaming sections={toolGroupRunningSections} />
+ </StateGalleryItem>
+
+ <StateGalleryItem label="Running a command" note="streaming tool, live output">
+ <ToolCallGroupStoryHost
+ executingToolCallId={TOOL_GROUP_EXECUTING_ID}
+ isStreaming
+ sections={toolGroupShellRunningSections}
+ />
+ </StateGalleryItem>
+
+ <StateGalleryItem label="Running a command, expanded">
+ <ToolCallGroupStoryHost
+ executingToolCallId={TOOL_GROUP_EXECUTING_ID}
+ isStreaming
+ open
+ sections={toolGroupShellRunningSections}
+ />
+ </StateGalleryItem>
+ </StateGallery>
+</Story>
diff --git a/ui/apps/chat/tests/stories/chat/messages/ToolCallGroupStoryHost.svelte b/ui/apps/chat/tests/stories/chat/messages/ToolCallGroupStoryHost.svelte
new file mode 100644
index 000000000..dbbaa1163
--- /dev/null
+++ b/ui/apps/chat/tests/stories/chat/messages/ToolCallGroupStoryHost.svelte
@@ -0,0 +1,46 @@
+<script lang="ts">
+ // Story-only host: keeps the open state of a tool-call group and of each
+ // call in it, as ChatMessageAgentTrace does.
+ import ChatMessageToolCallBlock from '#lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlock.svelte';
+ import ChatMessageToolCallGroup from '#lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallGroup.svelte';
+ import type { AgenticSection } from '#lib/types/index.ts';
+
+ interface Props {
+ sections: AgenticSection[];
+ open?: boolean;
+ isStreaming?: boolean;
+ executingToolCallId?: string | null;
+ }
+
+ let {
+ executingToolCallId = null,
+ isStreaming = false,
+ open: initialOpen = false,
+ sections
+ }: Props = $props();
+
+ // svelte-ignore state_referenced_locally
+ let open = $state(initialOpen);
+ let openCalls: Record<number, boolean> = $state({});
+</script>
+
+<ChatMessageToolCallGroup
+ {executingToolCallId}
+ {isStreaming}
+ onToggle={() => (open = !open)}
+ {open}
+ {sections}
+>
+ {#each sections as section, i (i)}
+ {@const executing = section.toolCallId === executingToolCallId}
+ <ChatMessageToolCallBlock
+ attachments={section.toolResultExtras}
+ conversationCwd="/home/user/projects/app"
+ isExecuting={executing}
+ {isStreaming}
+ onToggle={() => (openCalls[i] = !(openCalls[i] ?? executing))}
+ open={openCalls[i] ?? executing}
+ {section}
+ />
+ {/each}
+</ChatMessageToolCallGroup>
diff --git a/ui/apps/chat/tests/stories/chat/messages/fixtures.ts b/ui/apps/chat/tests/stories/chat/messages/fixtures.ts
index 41aae1b3d..a686c958f 100644
--- a/ui/apps/chat/tests/stories/chat/messages/fixtures.ts
+++ b/ui/apps/chat/tests/stories/chat/messages/fixtures.ts
@@ -592,6 +592,73 @@ export const searchResultsSection = toolSection(
].join('\n')
);
+export const toolSearchSection = toolSection(
+ 'tool_search',
+ { max_results: 1, query: 'select:Monitor' },
+ 'Loaded 1 tool: Monitor'
+);
+
+/* Tool call groups: runs of consecutive calls shown as one row */
+
+function withId(section: AgenticSection, toolCallId: string): AgenticSection {
+ return { ...section, toolCallId };
+}
+
+const IMAGE_SECTION_COUNT = 4;
+
+export const toolGroupSections: AgenticSection[] = [
+ withId(getInfoSection, 'group-info'),
+ withId(readFileSection, 'group-read'),
+ withId(grepSearchSection, 'group-grep'),
+ withId(editFileSection, 'group-edit'),
+ withId(execShellSection, 'group-exec'),
+ withId(writeFileSection, 'group-write')
+];
+
+export const toolGroupImageSections: AgenticSection[] = [
+ withId(execShellSection, 'image-exec'),
+ ...Array.from({ length: IMAGE_SECTION_COUNT }, (_, i) => ({
+ ...readMediaSection,
+ toolArgs: JSON.stringify({ path: `/home/user/charts/chart-${i + 1}.svg` }),
+ toolCallId: `image-media-${i}`,
+ toolResultExtras: [
+ {
+ base64Url: i % 2 === 0 ? CHART_IMAGE_URL : SVG_IMAGE_URL,
+ name: 'mcp-attachment-usage.svg',
+ type: AttachmentType.IMAGE as const
+ }
+ ]
+ }))
+];
+
+export const toolGroupRunningSections: AgenticSection[] = [
+ withId(readFileSection, 'running-read'),
+ withId(grepSearchSection, 'running-grep'),
+ toolSection(
+ BuiltInTool.SERVER_READ_FILE,
+ { path: 'package.json' },
+ undefined,
+ AgenticSectionType.TOOL_CALL_PENDING
+ )
+];
+
+export const TOOL_GROUP_EXECUTING_ID = 'running-exec';
+
+export const toolGroupShellRunningSections: AgenticSection[] = [
+ withId(readFileSection, 'shell-read'),
+ {
+ ...withId(execShellPendingSection, TOOL_GROUP_EXECUTING_ID),
+ toolResult: '> app@0.1.0 build\n> vite build\n\nvite v7.0.0 building for production...\n',
+ type: AgenticSectionType.TOOL_CALL
+ }
+];
+
+export const toolGroupMcpSections: AgenticSection[] = [
+ withId(toolSearchSection, 'mcp-search'),
+ withId(defaultToolSection, 'mcp-weather'),
+ withId(defaultToolMarkdownSection, 'mcp-issue')
+];
+
/* Reasoning sections */
export const reasoningSection: AgenticSection = {
diff --git a/ui/apps/chat/tests/unit/settings-tool-call-in-progress.test.ts b/ui/apps/chat/tests/unit/settings-tool-call-in-progress.test.ts
index 792239f76..5c11b43f0 100644
--- a/ui/apps/chat/tests/unit/settings-tool-call-in-progress.test.ts
+++ b/ui/apps/chat/tests/unit/settings-tool-call-in-progress.test.ts
@@ -27,9 +27,9 @@ describe('showToolCallInProgress setting', () => {
expect(field?.label).toBe('Show tool call in progress');
});
- it('ships enabled, like "Show thought in progress"', () => {
- expect(SETTING_CONFIG_DEFAULT[SETTINGS_KEYS.SHOW_TOOL_CALL_IN_PROGRESS]).toBe(true);
- expect(SETTING_CONFIG_DEFAULT[SETTINGS_KEYS.SHOW_THOUGHT_IN_PROGRESS]).toBe(true);
+ it('ships disabled, like "Show thought in progress", so the trace stays collapsed', () => {
+ expect(SETTING_CONFIG_DEFAULT[SETTINGS_KEYS.SHOW_TOOL_CALL_IN_PROGRESS]).toBe(false);
+ expect(SETTING_CONFIG_DEFAULT[SETTINGS_KEYS.SHOW_THOUGHT_IN_PROGRESS]).toBe(false);
});
it('is listed next to its "always show" counterpart', () => {
diff --git a/ui/apps/chat/tests/unit/tool-call-phrasing.test.ts b/ui/apps/chat/tests/unit/tool-call-phrasing.test.ts
new file mode 100644
index 000000000..1433d3225
--- /dev/null
+++ b/ui/apps/chat/tests/unit/tool-call-phrasing.test.ts
@@ -0,0 +1,344 @@
+import {
+ describeToolActivity,
+ describeToolCall,
+ formatToolCallLine,
+ groupToolCallRuns,
+ humanizeArgKey,
+ simpleToolArgFields,
+ summarizeToolCalls
+} from '#lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/tool-call-phrasing.ts';
+import { AgenticSectionType, BuiltInTool } from '#lib/enums/index.ts';
+import type { AgenticSection } from '#lib/types/index.ts';
+import { describe, expect, it } from 'vitest';
+
+function call(
+ toolName: string,
+ args: Record<string, unknown> | string = {},
+ type = AgenticSectionType.TOOL_CALL,
+ toolCallId?: string
+): AgenticSection {
+ return {
+ content: '',
+ toolArgs: typeof args === 'string' ? args : JSON.stringify(args),
+ toolCallId,
+ toolName,
+ toolResult: type === AgenticSectionType.TOOL_CALL ? 'ok' : undefined,
+ type
+ };
+}
+
+function line(toolName: string, args: Record<string, unknown> | string = {}, running = false) {
+ return formatToolCallLine(
+ describeToolCall(toolName, typeof args === 'string' ? args : JSON.stringify(args), running)
+ );
+}
+
+describe('describeToolCall', () => {
+ it('phrases built-in tools in the past tense', () => {
+ expect(line(BuiltInTool.SERVER_EXEC_SHELL_COMMAND, { command: 'git status' })).toBe(
+ 'Ran git status'
+ );
+ expect(line(BuiltInTool.SERVER_READ_FILE, { path: '/tmp/x/sheet_new.jpg' })).toBe(
+ 'Read sheet_new.jpg'
+ );
+ expect(line(BuiltInTool.SERVER_EDIT_FILE, { edits: [], path: 'a/harness-roadmap.html' })).toBe(
+ 'Edited harness-roadmap.html'
+ );
+ expect(line(BuiltInTool.SERVER_WRITE_FILE, { content: 'x', file_path: 'b/notes.md' })).toBe(
+ 'Wrote notes.md'
+ );
+ expect(line(BuiltInTool.SERVER_GREP_SEARCH, { path: '.', pattern: 'issue' })).toBe(
+ "Searched for 'issue'"
+ );
+ expect(line(BuiltInTool.SERVER_FILE_GLOB_SEARCH, { include: '*.ts', path: '.' })).toBe(
+ "Listed files matching '*.ts'"
+ );
+ expect(line(BuiltInTool.SERVER_FILE_GLOB_SEARCH, { include: '**', path: '.' })).toBe(
+ 'Listed files'
+ );
+ expect(line(BuiltInTool.BROWSER_SEARCH_CHATS, { by_matches: ['llama', 'gguf'] })).toBe(
+ "Searched chats for 'llama, gguf'"
+ );
+ expect(line(BuiltInTool.SERVER_GET_INFO)).toBe('Checked runtime info');
+ expect(line(BuiltInTool.BROWSER_RUN_JAVASCRIPT, { code: '1+1' })).toBe('Ran JavaScript');
+ });
+
+ it('uses the present tense while running', () => {
+ expect(line(BuiltInTool.SERVER_EXEC_SHELL_COMMAND, { command: 'ls' }, true)).toBe('Running ls');
+ expect(line(BuiltInTool.SERVER_EXEC_SHELL_COMMAND, '{"comm', true)).toBe('Running a command');
+ expect(line(BuiltInTool.SERVER_READ_FILE, { path: 'package.json' }, true)).toBe(
+ 'Reading package.json'
+ );
+ expect(line(BuiltInTool.BROWSER_SEARCH_CHATS, {}, true)).toBe('Searching chats');
+ });
+
+ it('falls back to the object when the target has not streamed yet', () => {
+ expect(line(BuiltInTool.SERVER_READ_FILE, '{"pa', true)).toBe('Reading a file');
+ expect(line(BuiltInTool.SERVER_GREP_SEARCH, '')).toBe('Searched files');
+ });
+
+ it('reads a path from partial args', () => {
+ expect(
+ line(BuiltInTool.SERVER_WRITE_FILE, '{"path": "src/app.ts", "content": "abc', true)
+ ).toBe('Writing app.ts');
+ });
+
+ it('phrases tool_search select queries as loading tools', () => {
+ expect(line('tool_search', { query: 'select:Monitor' })).toBe('Loaded tools Monitor');
+ expect(line('tool_search', { query: 'select:a, b' }, true)).toBe('Loading tools a, b');
+ expect(line('tool_search', { query: 'slack messages' })).toBe(
+ "Searched tools for 'slack messages'"
+ );
+ });
+
+ it('phrases web search tools', () => {
+ expect(line('web_search_exa', { query: 'llama.cpp' })).toBe("Searched the web for 'llama.cpp'");
+ });
+
+ it('gives MCP and unknown tools a generic line with their main argument', () => {
+ expect(line('get_weather', { city: 'Warsaw' })).toBe('Used get_weather Warsaw');
+ expect(line('fetch_page', { timeout: 5, url: 'https://example.com' })).toBe(
+ 'Used fetch_page https://example.com'
+ );
+ expect(line('list_things', {})).toBe('Used list_things');
+ expect(line('summarize_issue', { issue: 31273 })).toBe('Used summarize_issue 31273');
+ expect(line('list_things', {}, true)).toBe('Using list_things');
+ });
+
+ it('shortens long targets to one line', () => {
+ const text = describeToolCall('my_tool', JSON.stringify({ query: 'word '.repeat(40) })).target;
+
+ expect(text?.length).toBe(60);
+ expect(text?.endsWith('...')).toBe(true);
+ expect(text).not.toContain('\n');
+ });
+});
+
+describe('the shown argument', () => {
+ const args = { command: 'git status', description: 'Check which files changed.' };
+
+ it('shows the description as the model wrote it, in both tenses', () => {
+ expect(line(BuiltInTool.SERVER_EXEC_SHELL_COMMAND, args)).toBe('Check which files changed');
+ expect(line(BuiltInTool.SERVER_EXEC_SHELL_COMMAND, args, true)).toBe(
+ 'Check which files changed'
+ );
+ expect(
+ describeToolCall(BuiltInTool.SERVER_EXEC_SHELL_COMMAND, JSON.stringify(args)).described
+ ).toBe(true);
+ });
+
+ it('does not rewrite a description that starts with something other than a verb', () => {
+ const nouns = { command: 'ls', description: 'All files in src' };
+
+ expect(line(BuiltInTool.SERVER_EXEC_SHELL_COMMAND, nouns)).toBe('All files in src');
+ expect(line(BuiltInTool.SERVER_EXEC_SHELL_COMMAND, nouns, true)).toBe('All files in src');
+ });
+
+ it('keeps the command in the line while a later arg is still streaming', () => {
+ expect(line(BuiltInTool.SERVER_EXEC_SHELL_COMMAND, '{"command":"date","timeout":', true)).toBe(
+ 'Running date'
+ );
+ });
+
+ it('works for any tool that has the argument, MCP ones included', () => {
+ expect(line('get_weather', { city: 'Warsaw', description: 'Check the weather' })).toBe(
+ 'Check the weather'
+ );
+ });
+
+ it('falls back to the sentence when the call does not have it', () => {
+ expect(line('get_weather', { city: 'Warsaw' })).toBe('Used get_weather Warsaw');
+ });
+
+ it('reads the argument the settings pick, or none', () => {
+ const weather = JSON.stringify({
+ city: 'Warsaw',
+ description: 'Check the weather',
+ units: 'metric'
+ });
+
+ expect(formatToolCallLine(describeToolCall('get_weather', weather, false, 'units'))).toBe(
+ 'metric'
+ );
+ expect(formatToolCallLine(describeToolCall('get_weather', weather, false, null))).toBe(
+ 'Used get_weather Warsaw'
+ );
+ });
+
+ it('does not repeat the target the row already shows', () => {
+ expect(
+ formatToolCallLine(
+ describeToolCall(
+ BuiltInTool.SERVER_EXEC_SHELL_COMMAND,
+ JSON.stringify(args),
+ false,
+ 'command'
+ )
+ )
+ ).toBe('Ran git status');
+ });
+
+ it('ignores an argument name that is not a plain key', () => {
+ expect(
+ formatToolCallLine(
+ describeToolCall('get_weather', JSON.stringify({ city: 'Warsaw' }), false, '.*')
+ )
+ ).toBe('Used get_weather Warsaw');
+ });
+});
+
+describe('summarizeToolCalls', () => {
+ it('counts calls per kind in first-seen order', () => {
+ const sections = [
+ call(BuiltInTool.SERVER_EXEC_SHELL_COMMAND, { command: 'a' }),
+ call(BuiltInTool.SERVER_READ_FILE, { path: 'a' }),
+ call(BuiltInTool.SERVER_EXEC_SHELL_COMMAND, { command: 'b' }),
+ call(BuiltInTool.SERVER_WRITE_FILE, { path: 'c' }),
+ call(BuiltInTool.SERVER_WRITE_FILE, { path: 'd' }),
+ call(BuiltInTool.SERVER_READ_FILE, { path: 'b' })
+ ];
+
+ expect(summarizeToolCalls(sections)).toBe('Ran 2 commands, read 2 files, wrote 2 files');
+ });
+
+ it('uses singular forms and merges search tools', () => {
+ const sections = [
+ call(BuiltInTool.SERVER_EDIT_FILE, { path: 'a' }),
+ call(BuiltInTool.SERVER_GREP_SEARCH, { pattern: 'x' }),
+ call(BuiltInTool.BROWSER_SEARCH_CHATS, { by_matches: ['y'] })
+ ];
+
+ expect(summarizeToolCalls(sections)).toBe('Edited 1 file, searched 2 times');
+ expect(summarizeToolCalls([call(BuiltInTool.SERVER_GREP_SEARCH)])).toBe('Searched once');
+ });
+
+ it('puts other tools last', () => {
+ const sections = [call(BuiltInTool.SERVER_GET_INFO), call(BuiltInTool.SERVER_READ_FILE)];
+
+ expect(summarizeToolCalls(sections)).toBe('Read 1 file, used 1 tool');
+ });
+
+ it('counts each tool a select query loads', () => {
+ const sections = [
+ call('tool_search', { query: 'select:Monitor,Notebook' }),
+ call('get_weather', { city: 'x' }),
+ call('get_time')
+ ];
+
+ expect(summarizeToolCalls(sections)).toBe('Loaded 2 tools, used 2 tools');
+ });
+});
+
+describe('describeToolActivity', () => {
+ it('describes the last running call', () => {
+ const sections = [
+ call(BuiltInTool.SERVER_READ_FILE, { path: 'a.ts' }),
+ call(
+ BuiltInTool.SERVER_READ_FILE,
+ { path: 'package.json' },
+ AgenticSectionType.TOOL_CALL_PENDING
+ )
+ ];
+
+ expect(describeToolActivity(sections, true)).toBe('Reading package.json');
+ });
+
+ it('returns null when nothing runs or the reply stopped', () => {
+ const pending = [call(BuiltInTool.SERVER_READ_FILE, {}, AgenticSectionType.TOOL_CALL_PENDING)];
+
+ expect(describeToolActivity([call(BuiltInTool.SERVER_READ_FILE)], true)).toBeNull();
+ expect(describeToolActivity(pending, false)).toBeNull();
+ });
+
+ it('says the model is thinking while reasoning streams at the end of the run', () => {
+ const thinking: AgenticSection = {
+ content: '',
+ type: AgenticSectionType.REASONING_PENDING
+ };
+ const sections = [call(BuiltInTool.SERVER_READ_FILE, { path: 'a.ts' }), thinking];
+
+ expect(describeToolActivity(sections, true)).toBe('Thinking');
+ expect(describeToolActivity(sections, false)).toBeNull();
+ });
+
+ it('treats the executing call as running even once its result exists', () => {
+ const sections = [
+ call(
+ BuiltInTool.SERVER_EXEC_SHELL_COMMAND,
+ { command: 'ls' },
+ AgenticSectionType.TOOL_CALL,
+ 'c1'
+ )
+ ];
+
+ expect(describeToolActivity(sections, true, 'c1')).toBe('Running ls');
+ });
+});
+
+describe('simpleToolArgFields', () => {
+ it('lists short scalar args as labelled fields', () => {
+ expect(
+ simpleToolArgFields(JSON.stringify({ max_results: 1, query: 'select:Monitor' }))
+ ).toEqual([
+ { label: 'Max results', value: '1' },
+ { label: 'Query', value: 'select:Monitor' }
+ ]);
+ });
+
+ it('returns null for nested, multi-line, long or invalid args', () => {
+ expect(simpleToolArgFields(JSON.stringify({ a: { b: 1 } }))).toBeNull();
+ expect(simpleToolArgFields(JSON.stringify({ a: 'x\ny' }))).toBeNull();
+ expect(simpleToolArgFields(JSON.stringify({ a: 'x'.repeat(300) }))).toBeNull();
+ expect(simpleToolArgFields('{"a":')).toBeNull();
+ expect(simpleToolArgFields('{}')).toBeNull();
+ expect(simpleToolArgFields(undefined)).toBeNull();
+ });
+});
+
+describe('humanizeArgKey', () => {
+ it('turns snake and camel case into words', () => {
+ expect(humanizeArgKey('max_results')).toBe('Max results');
+ expect(humanizeArgKey('filePath')).toBe('File path');
+ expect(humanizeArgKey('q')).toBe('Q');
+ });
+});
+
+describe('groupToolCallRuns', () => {
+ const text: AgenticSection = { content: 'hi', type: AgenticSectionType.TEXT };
+ const tool = call(BuiltInTool.SERVER_READ_FILE);
+
+ it('groups runs of consecutive calls and keeps single calls apart', () => {
+ const sections = [text, tool, tool, tool, text, tool, text];
+
+ expect(groupToolCallRuns(sections, [0, 1, 2, 3, 4, 5, 6], 2)).toEqual([0, [1, 2, 3], 4, 5, 6]);
+ });
+
+ const think: AgenticSection = { content: 'hm', type: AgenticSectionType.REASONING };
+
+ it('takes in all the reasoning around the calls, up to the answer', () => {
+ // think, call, think, call, think, text
+ const sections = [think, tool, think, tool, think, text];
+
+ expect(groupToolCallRuns(sections, [0, 1, 2, 3, 4, 5], 2)).toEqual([[0, 1, 2, 3, 4], 5]);
+ });
+
+ it('groups one call with reasoning beside it', () => {
+ expect(groupToolCallRuns([think, tool, think, text], [0, 1, 2, 3], 2)).toEqual([[0, 1, 2], 3]);
+ expect(groupToolCallRuns([text, tool, think], [0, 1, 2], 2)).toEqual([0, [1, 2]]);
+ });
+
+ it('keeps a lone call, and reasoning with no call in reach, apart', () => {
+ expect(groupToolCallRuns([text, tool, text], [0, 1, 2], 2)).toEqual([0, 1, 2]);
+ expect(groupToolCallRuns([think, text, think], [0, 1, 2], 2)).toEqual([0, 1, 2]);
+ });
+
+ it('does not count reasoning as a call in the summary', () => {
+ expect(summarizeToolCalls([think, tool, think, tool])).toBe('Read 2 files');
+ });
+
+ it('works on a subset of indices and a trailing run', () => {
+ const sections = [text, text, tool, tool];
+
+ expect(groupToolCallRuns(sections, [1, 2, 3], 2)).toEqual([1, [2, 3]]);
+ });
+});
diff --git a/ui/apps/chat/tests/unit/tool-call-shown-arg.test.ts b/ui/apps/chat/tests/unit/tool-call-shown-arg.test.ts
new file mode 100644
index 000000000..7bc637259
--- /dev/null
+++ b/ui/apps/chat/tests/unit/tool-call-shown-arg.test.ts
@@ -0,0 +1,38 @@
+import { SETTINGS_KEYS } from '#lib/constants/index.ts';
+import { parseToolCallShownArgOverrides, toolCallShownArg } from '#lib/utils/index.ts';
+import { describe, expect, it } from 'vitest';
+
+function config(shownArg: string, overrides: Record<string, string> | string = {}) {
+ return {
+ [SETTINGS_KEYS.TOOL_CALL_SHOWN_ARG]: shownArg,
+ [SETTINGS_KEYS.TOOL_CALL_SHOWN_ARG_OVERRIDES]:
+ typeof overrides === 'string' ? overrides : JSON.stringify(overrides)
+ };
+}
+
+describe('toolCallShownArg', () => {
+ it('uses the global argument for a tool without its own', () => {
+ expect(toolCallShownArg(config('description'), 'get_weather')).toBe('description');
+ });
+
+ it("prefers the tool's own argument", () => {
+ expect(toolCallShownArg(config('description', { get_weather: 'city' }), 'get_weather')).toBe(
+ 'city'
+ );
+ expect(toolCallShownArg(config('description', { get_weather: 'city' }), 'other')).toBe(
+ 'description'
+ );
+ });
+
+ it('returns null for none, globally or per tool', () => {
+ expect(toolCallShownArg(config(''), 'get_weather')).toBeNull();
+ expect(toolCallShownArg(config('description', { get_weather: '' }), 'get_weather')).toBeNull();
+ });
+
+ it('reads unreadable overrides as none', () => {
+ expect(parseToolCallShownArgOverrides('not json')).toEqual({});
+ expect(parseToolCallShownArgOverrides('[1]')).toEqual({});
+ expect(parseToolCallShownArgOverrides('{"a":"x","b":1}')).toEqual({ a: 'x' });
+ expect(toolCallShownArg(config('description', 'not json'), 'get_weather')).toBe('description');
+ });
+});