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 function handleCopyModel() {
211 void copyToClipboard(displayedModel ?? '');
215 if (showProcessingInfoTop || showProcessingInfoBottom) {
216 processingState.startMonitoring();
222 class="text-md group w-full leading-7.5 {className}"
224 aria-label="Assistant message with actions"
226 {#if showProcessingInfoTop}
227 <div class="mt-6 w-full max-w-[48rem]" in:fade>
228 <div class="processing-container">
229 <span class="processing-text">
231 processingState.getPromptProgressText() ??
232 processingState.getProcessingMessage() ??
239 {#if editCtx.isEditing}
240 <ChatMessageEditForm />
241 {:else if message.role === MessageRole.ASSISTANT}
243 <pre class="raw-output">{rawOutputContent || ''}</pre>
245 <ChatMessageAgenticContent
248 isStreaming={isChatStreaming()}
249 {isLastAssistantMessage}
250 highlightTurns={highlightAgenticTurns}
254 <div class="text-sm whitespace-pre-wrap">
259 {#if showProcessingInfoBottom}
260 <div class="mt-4 w-full max-w-[48rem]" in:fade>
261 <div class="processing-container">
262 <span class="processing-text">
264 processingState.getPromptProgressText() ??
265 processingState.getProcessingMessage() ??
272 <div class="info my-6 grid gap-4 tabular-nums">
275 bind:this={statsContainerEl}
276 class="inline-flex flex-wrap items-start gap-2 text-xs text-muted-foreground"
279 <ModelsSelectorDropdown
280 currentModel={displayedModel}
281 disabled={isLoading()}
282 onModelChange={async (modelId: string, modelName: string) => {
283 const status = modelsStore.getModelStatus(modelId);
285 if (status !== ServerModelStatus.LOADED) {
286 await modelsStore.loadModel(modelId);
289 onRegenerate(modelName);
294 <ModelBadge model={displayedModel || undefined} onclick={handleCopyModel} />
297 {#if currentConfig.showMessageStats && message.timings && message.timings.predicted_n && message.timings.predicted_ms}
298 {@const agentic = message.timings.agentic}
299 <ChatMessageStatistics
300 promptTokens={agentic ? agentic.llm.prompt_n : message.timings.prompt_n}
301 promptMs={agentic ? agentic.llm.prompt_ms : message.timings.prompt_ms}
302 predictedTokens={agentic ? agentic.llm.predicted_n : message.timings.predicted_n}
303 predictedMs={agentic ? agentic.llm.predicted_ms : message.timings.predicted_ms}
304 agenticTimings={agentic}
305 onActiveViewChange={handleStatsViewChange}
307 {:else if isLoading() && currentConfig.showMessageStats}
308 {@const liveStats = processingState.getLiveProcessingStats()}
309 {@const genStats = processingState.getLiveGenerationStats()}
310 {@const promptProgress = processingState.processingState?.promptProgress}
311 {@const isStillProcessingPrompt =
312 promptProgress && promptProgress.processed < promptProgress.total}
314 {#if liveStats || genStats}
315 <ChatMessageStatistics
317 isProcessingPrompt={!!isStillProcessingPrompt}
318 promptTokens={liveStats?.tokensProcessed}
319 promptMs={liveStats?.timeMs}
320 predictedTokens={genStats?.tokensGenerated}
321 predictedMs={genStats?.timeMs}
329 {#if message.timestamp && !editCtx.isEditing}
330 <ChatMessageActionIcons
331 role={MessageRole.ASSISTANT}
333 actionsPosition="left"
340 onContinue={currentConfig.enableContinueGeneration ? onContinue : undefined}
344 {onNavigateToSibling}
345 {onShowDeleteDialogChange}
346 showRawOutputSwitch={currentConfig.showRawOutputSwitch}
347 rawOutputEnabled={showRawOutput}
348 onRawOutputToggle={(enabled) => (showRawOutput = enabled)}
354 .processing-container {
356 flex-direction: column;
357 align-items: flex-start;
362 background: linear-gradient(
364 var(--muted-foreground),
366 var(--muted-foreground)
368 background-size: 200% 100%;
369 background-clip: text;
370 -webkit-background-clip: text;
371 -webkit-text-fill-color: transparent;
372 animation: shine 1s linear infinite;
379 background-position: -200% 0;
387 padding: 1rem 1.25rem;
389 background: hsl(var(--muted) / 0.3);
390 color: var(--foreground);
393 white-space: pre-wrap;
394 word-break: break-word;