3 ChatMessageAgenticContent,
4 ChatMessageActionIcons,
9 } from '$lib/components/app';
10 import { getMessageEditContext } from '$lib/contexts';
11 import { useProcessingState } from '$lib/hooks/use-processing-state.svelte';
12 import { isLoading, isChatStreaming } from '$lib/stores/chat.svelte';
13 import { copyToClipboard, deriveAgenticSections } from '$lib/utils';
14 import { AgenticSectionType } from '$lib/enums';
15 import { REASONING_TAGS } from '$lib/constants/agentic';
16 import { tick } from 'svelte';
17 import { fade } from 'svelte/transition';
18 import { MessageRole, ChatMessageStatsView } from '$lib/enums';
19 import { config } from '$lib/stores/settings.svelte';
20 import { isRouterMode } from '$lib/stores/server.svelte';
21 import { modelsStore } from '$lib/stores/models.svelte';
22 import { ServerModelStatus } from '$lib/enums';
24 import { hasAgenticContent } from '$lib/utils';
31 assistantMessages: number;
32 messageTypes: string[];
34 isLastAssistantMessage?: boolean;
35 message: DatabaseMessage;
36 toolMessages?: DatabaseMessage[];
37 messageContent: string | undefined;
39 onConfirmDelete: () => void;
40 onContinue?: () => void;
43 onForkConversation?: (options: { name: string; includeAttachments: boolean }) => void;
44 onNavigateToSibling?: (siblingId: string) => void;
45 onRegenerate: (modelOverride?: string) => void;
46 onShowDeleteDialogChange: (show: boolean) => void;
47 showDeleteDialog: boolean;
48 siblingInfo?: ChatMessageSiblingInfo | null;
49 textareaElement?: HTMLTextAreaElement;
53 class: className = '',
55 isLastAssistantMessage = false,
67 onShowDeleteDialogChange,
70 textareaElement = $bindable()
74 const editCtx = getMessageEditContext();
76 const isAgentic = $derived(hasAgenticContent(message, toolMessages));
77 const processingState = useProcessingState();
79 let currentConfig = $derived(config());
80 let isRouter = $derived(isRouterMode());
81 let showRawOutput = $state(false);
83 let rawOutputContent = $derived.by(() => {
84 const sections = deriveAgenticSections(message, toolMessages, [], false);
85 const parts: string[] = [];
87 for (const section of sections) {
88 switch (section.type) {
89 case AgenticSectionType.REASONING:
90 case AgenticSectionType.REASONING_PENDING:
91 parts.push(`${REASONING_TAGS.START}\n${section.content}\n${REASONING_TAGS.END}`);
94 case AgenticSectionType.TEXT:
95 parts.push(section.content);
98 case AgenticSectionType.TOOL_CALL:
99 case AgenticSectionType.TOOL_CALL_PENDING:
100 case AgenticSectionType.TOOL_CALL_STREAMING: {
101 const callObj: Record<string, unknown> = { name: section.toolName };
103 if (section.toolArgs) {
105 callObj.arguments = JSON.parse(section.toolArgs);
107 callObj.arguments = section.toolArgs;
111 parts.push(JSON.stringify(callObj, null, 2));
113 if (section.toolResult) {
114 parts.push(`[Tool Result]\n${section.toolResult}`);
122 return parts.join('\n\n\n');
125 let activeStatsView = $state<ChatMessageStatsView>(ChatMessageStatsView.GENERATION);
126 let statsContainerEl: HTMLDivElement | undefined = $state();
128 function getScrollParent(el: HTMLElement): HTMLElement | null {
129 let parent = el.parentElement;
131 const style = getComputedStyle(parent);
132 if (/(auto|scroll)/.test(style.overflowY)) {
135 parent = parent.parentElement;
140 async function handleStatsViewChange(view: ChatMessageStatsView) {
141 const el = statsContainerEl;
143 activeStatsView = view;
148 const scrollParent = getScrollParent(el);
150 activeStatsView = view;
155 const yBefore = el.getBoundingClientRect().top;
157 activeStatsView = view;
161 const delta = el.getBoundingClientRect().top - yBefore;
163 scrollParent.scrollTop += delta;
166 // Correct any drift after browser paint
167 requestAnimationFrame(() => {
168 const drift = el.getBoundingClientRect().top - yBefore;
170 if (Math.abs(drift) > 1) {
171 scrollParent.scrollTop += drift;
176 let highlightAgenticTurns = $derived(
178 (currentConfig.alwaysShowAgenticTurns || activeStatsView === ChatMessageStatsView.SUMMARY)
181 let displayedModel = $derived(message.model ?? null);
183 let isCurrentlyLoading = $derived(isLoading());
184 let isStreaming = $derived(isChatStreaming());
185 let hasNoContent = $derived(!message?.content?.trim());
186 let isActivelyProcessing = $derived(isCurrentlyLoading || isStreaming);
188 let showProcessingInfoTop = $derived(
189 message?.role === MessageRole.ASSISTANT &&
190 isActivelyProcessing &&
193 isLastAssistantMessage
196 let showProcessingInfoBottom = $derived(
197 message?.role === MessageRole.ASSISTANT &&
198 isActivelyProcessing &&
199 (!hasNoContent || isAgentic) &&
200 isLastAssistantMessage
203 function handleCopyModel() {
204 void copyToClipboard(displayedModel ?? '');
208 if (showProcessingInfoTop || showProcessingInfoBottom) {
209 processingState.startMonitoring();
215 class="text-md group w-full leading-7.5 {className}"
217 aria-label="Assistant message with actions"
219 {#if showProcessingInfoTop}
220 <div class="mt-6 w-full max-w-[48rem]" in:fade>
221 <div class="processing-container">
222 <span class="processing-text">
223 {processingState.getPromptProgressText() ??
224 processingState.getProcessingMessage() ??
231 {#if editCtx.isEditing}
232 <ChatMessageEditForm />
233 {:else if message.role === MessageRole.ASSISTANT}
235 <pre class="raw-output">{rawOutputContent || ''}</pre>
237 <ChatMessageAgenticContent
240 isStreaming={isChatStreaming()}
241 {isLastAssistantMessage}
242 highlightTurns={highlightAgenticTurns}
246 <div class="text-sm whitespace-pre-wrap">
251 {#if showProcessingInfoBottom}
252 <div class="mt-4 w-full max-w-[48rem]" in:fade>
253 <div class="processing-container">
254 <span class="processing-text">
255 {processingState.getPromptProgressText() ??
256 processingState.getProcessingMessage() ??
263 <div class="info my-6 grid gap-4 tabular-nums">
266 bind:this={statsContainerEl}
267 class="inline-flex flex-wrap items-start gap-2 text-xs text-muted-foreground"
270 <ModelsSelectorDropdown
271 currentModel={displayedModel}
272 disabled={isLoading()}
273 onModelChange={async (modelId: string, modelName: string) => {
274 const status = modelsStore.getModelStatus(modelId);
276 if (status !== ServerModelStatus.LOADED) {
277 await modelsStore.loadModel(modelId);
280 onRegenerate(modelName);
285 <ModelBadge model={displayedModel || undefined} onclick={handleCopyModel} />
288 {#if currentConfig.showMessageStats && message.timings && message.timings.predicted_n && message.timings.predicted_ms}
289 {@const agentic = message.timings.agentic}
290 <ChatMessageStatistics
291 promptTokens={agentic ? agentic.llm.prompt_n : message.timings.prompt_n}
292 promptMs={agentic ? agentic.llm.prompt_ms : message.timings.prompt_ms}
293 predictedTokens={agentic ? agentic.llm.predicted_n : message.timings.predicted_n}
294 predictedMs={agentic ? agentic.llm.predicted_ms : message.timings.predicted_ms}
295 agenticTimings={agentic}
296 onActiveViewChange={handleStatsViewChange}
298 {:else if isLoading() && currentConfig.showMessageStats}
299 {@const liveStats = processingState.getLiveProcessingStats()}
300 {@const genStats = processingState.getLiveGenerationStats()}
301 {@const promptProgress = processingState.processingState?.promptProgress}
302 {@const isStillProcessingPrompt =
303 promptProgress && promptProgress.processed < promptProgress.total}
305 {#if liveStats || genStats}
306 <ChatMessageStatistics
308 isProcessingPrompt={!!isStillProcessingPrompt}
309 promptTokens={liveStats?.tokensProcessed}
310 promptMs={liveStats?.timeMs}
311 predictedTokens={genStats?.tokensGenerated}
312 predictedMs={genStats?.timeMs}
320 {#if message.timestamp && !editCtx.isEditing}
321 <ChatMessageActionIcons
322 role={MessageRole.ASSISTANT}
324 actionsPosition="left"
331 onContinue={currentConfig.enableContinueGeneration ? onContinue : undefined}
335 {onNavigateToSibling}
336 {onShowDeleteDialogChange}
337 showRawOutputSwitch={currentConfig.showRawOutputSwitch}
338 rawOutputEnabled={showRawOutput}
339 onRawOutputToggle={(enabled) => (showRawOutput = enabled)}
345 .processing-container {
347 flex-direction: column;
348 align-items: flex-start;
353 background: linear-gradient(
355 var(--muted-foreground),
357 var(--muted-foreground)
359 background-size: 200% 100%;
360 background-clip: text;
361 -webkit-background-clip: text;
362 -webkit-text-fill-color: transparent;
363 animation: shine 1s linear infinite;
370 background-position: -200% 0;
378 padding: 1rem 1.25rem;
380 background: hsl(var(--muted) / 0.3);
381 color: var(--foreground);
384 white-space: pre-wrap;
385 word-break: break-word;