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, modelLoadProgressText } 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 // during a router auto-load the message has no model yet, so target the selected one
189 let loadTargetModel = $derived(message.model ?? modelsStore.selectedModelName);
190 let modelLoadProgress = $derived(
191 isRouter && loadTargetModel ? modelsStore.getLoadProgress(loadTargetModel) : null
193 let modelLoadingText = $derived(modelLoadProgressText(modelLoadProgress));
195 let showProcessingInfoTop = $derived(
196 message?.role === MessageRole.ASSISTANT &&
197 isActivelyProcessing &&
200 isLastAssistantMessage
203 let showProcessingInfoBottom = $derived(
204 message?.role === MessageRole.ASSISTANT &&
205 isActivelyProcessing &&
206 (!hasNoContent || isAgentic) &&
207 isLastAssistantMessage
210 let assistantEl: HTMLDivElement | undefined = $state();
211 let lastUserMessageHeight = $state(0);
212 let assistantMarginTop = $state(0);
215 if (!assistantEl) return;
217 assistantMarginTop = Math.round(parseFloat(getComputedStyle(assistantEl).marginTop));
219 const chatMessageEl = assistantEl.closest('.chat-message');
220 const previousChatMessage = chatMessageEl?.previousElementSibling;
221 const userMessageEl = previousChatMessage?.querySelector(
223 ) as HTMLElement | null;
225 if (!userMessageEl) {
226 lastUserMessageHeight = 0;
230 const updateHeight = () => {
231 const rect = userMessageEl.getBoundingClientRect();
232 const marginTop = Math.round(parseFloat(getComputedStyle(userMessageEl).marginTop));
233 lastUserMessageHeight = Math.round(rect.height + marginTop);
238 const resizeObserver = new ResizeObserver(updateHeight);
239 resizeObserver.observe(userMessageEl);
242 resizeObserver.disconnect();
246 function handleCopyModel() {
247 void copyToClipboard(displayedModel ?? '');
251 if (showProcessingInfoTop || showProcessingInfoBottom) {
252 processingState.startMonitoring();
258 bind:this={assistantEl}
259 class="chat-message-assistant text-md group w-full leading-7.5 {className}"
260 style:--last-user-message-height={lastUserMessageHeight > 0
261 ? `${lastUserMessageHeight}px`
263 style:--assistant-margin-top={assistantMarginTop > 0 ? `${assistantMarginTop}px` : undefined}
265 aria-label="Assistant message with actions"
267 {#if showProcessingInfoTop}
268 <div class="mt-6 w-full max-w-3xl" in:fade>
269 <div class="processing-container">
270 <span class="processing-text">
272 processingState.getPromptProgressText() ??
273 processingState.getProcessingMessage() ??
280 {#if editCtx.isEditing}
281 <ChatMessageEditForm />
282 {:else if message.role === MessageRole.ASSISTANT}
284 <pre class="raw-output">{rawOutputContent || ''}</pre>
286 <ChatMessageAgenticContent
289 isStreaming={isChatStreaming()}
290 {isLastAssistantMessage}
291 highlightTurns={highlightAgenticTurns}
295 <div class="text-sm whitespace-pre-wrap">
300 {#if showProcessingInfoBottom}
301 <div class="mt-4 w-full max-w-3xl" in:fade>
302 <div class="processing-container">
303 <span class="processing-text">
305 processingState.getPromptProgressText() ??
306 processingState.getProcessingMessage() ??
313 <div class="info my-6 grid gap-4 tabular-nums">
316 bind:this={statsContainerEl}
317 class="inline-flex flex-wrap items-start gap-2 text-xs text-muted-foreground"
320 <ModelsSelectorDropdown
321 currentModel={displayedModel}
322 disabled={isLoading()}
323 onModelChange={async (modelId: string, modelName: string) => {
324 const status = modelsStore.getModelStatus(modelId);
326 if (status !== ServerModelStatus.LOADED) {
327 await modelsStore.loadModel(modelId);
330 onRegenerate(modelName);
335 <ModelBadge model={displayedModel || undefined} onclick={handleCopyModel} />
338 {#if currentConfig.showMessageStats && message.timings && message.timings.predicted_n && message.timings.predicted_ms}
339 {@const agentic = message.timings.agentic}
340 <ChatMessageStatistics
341 promptTokens={agentic ? agentic.llm.prompt_n : message.timings.prompt_n}
342 promptMs={agentic ? agentic.llm.prompt_ms : message.timings.prompt_ms}
343 predictedTokens={agentic ? agentic.llm.predicted_n : message.timings.predicted_n}
344 predictedMs={agentic ? agentic.llm.predicted_ms : message.timings.predicted_ms}
345 agenticTimings={agentic}
346 onActiveViewChange={handleStatsViewChange}
348 {:else if isLoading() && currentConfig.showMessageStats}
349 {@const liveStats = processingState.getLiveProcessingStats()}
350 {@const genStats = processingState.getLiveGenerationStats()}
351 {@const promptProgress = processingState.processingState?.promptProgress}
352 {@const isStillProcessingPrompt =
353 promptProgress && promptProgress.processed < promptProgress.total}
355 {#if liveStats || genStats}
356 <ChatMessageStatistics
358 isProcessingPrompt={!!isStillProcessingPrompt}
359 promptTokens={liveStats?.tokensProcessed}
360 promptMs={liveStats?.timeMs}
361 predictedTokens={genStats?.tokensGenerated}
362 predictedMs={genStats?.timeMs}
370 {#if message.timestamp && !editCtx.isEditing}
371 <ChatMessageActionIcons
372 role={MessageRole.ASSISTANT}
374 actionsPosition="left"
381 onContinue={currentConfig.enableContinueGeneration ? onContinue : undefined}
385 {onNavigateToSibling}
386 {onShowDeleteDialogChange}
387 showRawOutputSwitch={currentConfig.showRawOutputSwitch}
388 rawOutputEnabled={showRawOutput}
389 onRawOutputToggle={(enabled) => (showRawOutput = enabled)}
395 :global(.chat-message):last-child .chat-message-assistant {
396 --assistant-min-height-offset: calc(
397 var(--last-user-message-height, 19rem) + var(--chat-form-height, 6rem) +
398 var(--chat-form-bottom-position, 0.5rem) + var(--chat-form-padding-top, 6rem) +
399 var(--assistant-margin-top, 3rem)
401 min-height: calc(100dvh - var(--assistant-min-height-offset));
403 @media (width > 768px) {
404 --assistant-min-height-offset: calc(
405 var(--last-user-message-height, 18rem) + var(--chat-form-height, 6rem) +
406 var(--chat-form-bottom-position, 1rem) + var(--chat-form-padding-top, 6rem) +
407 var(--assistant-margin-top, 3rem)
412 .processing-container {
414 flex-direction: column;
415 align-items: flex-start;
420 background: linear-gradient(
422 var(--muted-foreground),
424 var(--muted-foreground)
426 background-size: 200% 100%;
427 background-clip: text;
428 -webkit-background-clip: text;
429 -webkit-text-fill-color: transparent;
430 animation: shine 1s linear infinite;
437 background-position: -200% 0;
445 padding: 1rem 1.25rem;
447 background: hsl(var(--muted) / 0.3);
448 color: var(--foreground);
451 white-space: pre-wrap;
452 word-break: break-word;