Commit 2e11b8a8d for llama.cpp
commit 2e11b8a8dd0b796d75c59d3e9249576687a3590b
Author: Aleksander Grygier <aleksander.grygier@gmail.com>
Date: Tue Dec 1 15:42:06 2026 +0100
ui: list the conversation's background tasks under the chat form (#33211)
Built on llama-server's background tasks (#33391). Shell calls now carry the
X-Conversation-Id header, so a command can move to the background: the model
asks for it with `background: true`, and the user with "Move to background"
under a running call.
The chip under the chat form counts the conversation's running tasks, followed
over GET /tools/tasks/events while the tab is visible. Its dialog lists them;
each row shows the task's output, read from GET /tools/tasks/output while it
is open, and Stop ends it with everything it started through DELETE
/tools/tasks. A task leaves the list when it ends.
Llama UI gains a Chip (now used by the system message chip too), an xs button
size and a danger-secondary button variant for Stop; the shell prompt line is
one component shared by the tool call and the task rows.
Assisted-by: Claude (Opus 5.5 Medium)
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte
index 89cabf0c8..2312183f7 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte
@@ -8,6 +8,7 @@
ChatAttachmentsList,
ChatFormActions,
ChatFormActionsRecording,
+ ChatFormBackgroundTasks,
ChatFormCurrentWorkingDirectory,
ChatFormInput,
ChatFormInputFileInputInvisible,
@@ -90,6 +91,8 @@
isLoading?: boolean;
placeholder?: string;
showAddButton?: boolean;
+ /** List the conversation's background tasks under the form; one form on the page does. */
+ showBackgroundTasks?: boolean;
showModelSelector?: boolean;
/** Writing the system message: the form takes the system message's dashed, muted look. */
systemMode?: boolean;
@@ -124,6 +127,7 @@
onValueChange,
placeholder = 'Type a message...',
showAddButton = true,
+ showBackgroundTasks = false,
showModelSelector = true,
singleRow = false,
systemMode = false,
@@ -1012,6 +1016,10 @@
{#if systemMessageChip}
<ChatFormSystemMessageChip content={systemMessageChip} {disabled} />
{/if}
+
+ {#if showBackgroundTasks}
+ <ChatFormBackgroundTasks />
+ {/if}
</div>
</form>
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormBackgroundTasks/ChatFormBackgroundTaskRow.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormBackgroundTasks/ChatFormBackgroundTaskRow.svelte
new file mode 100644
index 000000000..2508bdf8b
--- /dev/null
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormBackgroundTasks/ChatFormBackgroundTaskRow.svelte
@@ -0,0 +1,113 @@
+<script lang="ts">
+ // One background task in the dialog: its description and a Stop action, above the same
+ // terminal block as a shell tool call, collapsed, with what the task printed inside.
+ import { Button } from '@ggml-org/llama-ui/ui/button';
+ import { Square } from '@lucide/svelte';
+ import { CollapsibleTerminalBlock, ShellPromptLine } from '#lib/components/app/index.ts';
+ import {
+ BACKGROUND_TASK_NO_OUTPUT_LABEL,
+ BACKGROUND_TASK_SKIPPED_LABEL,
+ BACKGROUND_TASK_STOP_ARIA_LABEL,
+ BACKGROUND_TASK_STOP_LABEL,
+ MS_PER_SECOND,
+ TOOL_RUNTIME_SCROLL_AT_BOTTOM_THRESHOLD_PX
+ } from '#lib/constants/index.ts';
+ import { backgroundTasksStore } from '#lib/stores/index.ts';
+ import type { BackgroundTask } from '#lib/types/index.ts';
+ import { formatRelativeTime } from '#lib/utils/index.ts';
+
+ interface Props {
+ task: BackgroundTask;
+ }
+
+ let { task }: Props = $props();
+
+ const log = $derived(backgroundTasksStore.log(task.id));
+
+ let open = $state(false);
+ let stopping = $state(false);
+ let logEl: HTMLPreElement | undefined = $state();
+ // the output follows its end as it grows, until the user scrolls up to read
+ let pinned = true;
+
+ // the output is read only while the block is open: the store reads what is new each time the
+ // server says the task printed
+ $effect(() => {
+ if (!open) return;
+
+ return backgroundTasksStore.watchOutput(task.id);
+ });
+
+ $effect(() => {
+ void log.text;
+
+ if (!pinned) return;
+
+ requestAnimationFrame(() => {
+ if (logEl) logEl.scrollTop = logEl.scrollHeight;
+ });
+ });
+
+ function handleScroll() {
+ if (!logEl) return;
+
+ pinned =
+ logEl.scrollHeight - logEl.scrollTop - logEl.clientHeight <=
+ TOOL_RUNTIME_SCROLL_AT_BOTTOM_THRESHOLD_PX;
+ }
+
+ async function stop(event: MouseEvent) {
+ event.stopPropagation();
+ stopping = true;
+
+ try {
+ await backgroundTasksStore.stop(task.id);
+ } finally {
+ stopping = false;
+ }
+ }
+</script>
+
+<div class="grid gap-2" data-background-task={task.id}>
+ <div class="flex items-center gap-2">
+ <span class="min-w-0 flex-1 truncate text-body-sm font-medium">
+ {task.description || task.command}
+ </span>
+
+ <Button
+ aria-label={BACKGROUND_TASK_STOP_ARIA_LABEL}
+ disabled={stopping}
+ onclick={stop}
+ size="xs"
+ variant="danger-secondary"
+ >
+ <Square />
+
+ {BACKGROUND_TASK_STOP_LABEL}
+ </Button>
+ </div>
+
+ <CollapsibleTerminalBlock bind:open>
+ {#snippet titleSnippet()}
+ <ShellPromptLine command={task.command} cwd={task.cwd} singleLine />
+ {/snippet}
+
+ <div class="grid gap-2">
+ <div class="font-mono text-caption text-muted-foreground">
+ task {task.id} · started
+ {formatRelativeTime(task.started_at * MS_PER_SECOND)}
+ </div>
+
+ {#if log.skipped > 0}
+ <div class="font-mono text-caption text-muted-foreground">
+ {BACKGROUND_TASK_SKIPPED_LABEL(log.skipped)}
+ </div>
+ {/if}
+
+ <pre
+ bind:this={logEl}
+ class="max-h-80 overflow-auto font-mono text-caption leading-relaxed whitespace-pre-wrap"
+ onscroll={handleScroll}>{log.text || BACKGROUND_TASK_NO_OUTPUT_LABEL}</pre>
+ </div>
+ </CollapsibleTerminalBlock>
+</div>
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormBackgroundTasks/ChatFormBackgroundTasks.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormBackgroundTasks/ChatFormBackgroundTasks.svelte
new file mode 100644
index 000000000..06217388d
--- /dev/null
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormBackgroundTasks/ChatFormBackgroundTasks.svelte
@@ -0,0 +1,77 @@
+<script lang="ts">
+ // The chip under the chat form that counts the commands llama-server keeps running for this
+ // conversation (dev servers, watchers, builds), and the dialog it opens to read and stop them.
+ import ChatFormBackgroundTaskRow from './ChatFormBackgroundTaskRow.svelte';
+ import { Button } from '@ggml-org/llama-ui/ui/button';
+ import { Chip } from '@ggml-org/llama-ui/ui/chip';
+ import * as Dialog from '@ggml-org/llama-ui/ui/dialog';
+ import { SquareTerminal, X } from '@lucide/svelte';
+ import {
+ BACKGROUND_TASKS_DIALOG_DESCRIPTION,
+ BACKGROUND_TASKS_DIALOG_TITLE,
+ BACKGROUND_TASKS_EMPTY_LABEL,
+ BACKGROUND_TASKS_RUNNING_LABEL,
+ BACKGROUND_TASKS_STOP_ALL_LABEL
+ } from '#lib/constants/index.ts';
+ import { backgroundTasksStore as store, conversationsStore } from '#lib/stores/index.ts';
+
+ // a hidden tab lets go of its event stream: a browser only opens a few connections to one
+ // server, across all of its tabs
+ let hidden = $state(globalThis.document?.hidden ?? false);
+
+ // derived, so the stream is opened again only when one of the two really changes
+ const conversationId = $derived(conversationsStore.activeConversation?.id ?? '');
+ const follow = $derived(store.available && !hidden);
+
+ $effect(() => store.watch(conversationId, follow));
+
+ const count = $derived(store.tasks.length);
+</script>
+
+<svelte:document onvisibilitychange={() => (hidden = document.hidden)} />
+
+{#if store.available && count > 0}
+ <Chip class="mt-1.5" data-background-tasks-chip onclick={() => (store.dialogOpen = true)}>
+ <SquareTerminal />
+
+ <span class="truncate">{BACKGROUND_TASKS_RUNNING_LABEL(count)}</span>
+ </Chip>
+{/if}
+
+<Dialog.Root bind:open={store.dialogOpen}>
+ <Dialog.Content
+ class="flex max-h-[calc(100vh-4rem)] flex-col gap-0 p-0 md:w-[calc(100vw-4rem)]! md:max-w-3xl!"
+ >
+ <Dialog.Header
+ class="flex-row items-center gap-2 border-b border-border/40 p-4"
+ showCloseButton={false}
+ >
+ <Dialog.Title class="text-body-sm font-semibold">{BACKGROUND_TASKS_DIALOG_TITLE}</Dialog.Title
+ >
+
+ {#if count > 1}
+ <Button onclick={() => void store.stopAll()} size="xs" variant="secondary">
+ {BACKGROUND_TASKS_STOP_ALL_LABEL}
+ </Button>
+ {/if}
+
+ <Dialog.Close
+ aria-label="Close"
+ class="ml-auto inline-flex cursor-pointer items-center justify-center rounded-md p-1.5 text-muted-foreground/70 transition-colors hover:bg-muted-foreground/10 hover:text-foreground"
+ type="button"
+ >
+ <X class="size-icon-md" />
+ </Dialog.Close>
+ </Dialog.Header>
+
+ <Dialog.Description class="sr-only">{BACKGROUND_TASKS_DIALOG_DESCRIPTION}</Dialog.Description>
+
+ <div class="grid gap-5 overflow-y-auto p-4">
+ {#each store.tasks as task (task.id)}
+ <ChatFormBackgroundTaskRow {task} />
+ {:else}
+ <p class="text-body-sm text-muted-foreground">{BACKGROUND_TASKS_EMPTY_LABEL}</p>
+ {/each}
+ </div>
+ </Dialog.Content>
+</Dialog.Root>
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormSystemMessageChip.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormSystemMessageChip.svelte
index d797ce208..fe7ebc656 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormSystemMessageChip.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormSystemMessageChip.svelte
@@ -1,4 +1,5 @@
<script lang="ts">
+ import { Chip } from '@ggml-org/llama-ui/ui/chip';
import { MessageSquareText } from '@lucide/svelte';
import { DialogSystemMessageEdit } from '#lib/components/app/index.ts';
import { SYSTEM_MESSAGE_PLACEHOLDER } from '#lib/constants/index.ts';
@@ -19,17 +20,11 @@
{#if hasContent}
<div class="grid">
- <button
- class="mt-1.5 flex w-auto min-w-0 items-center gap-1 rounded-md px-2 py-1 text-caption text-muted-foreground backdrop-blur-2xl hover:text-foreground"
- {disabled}
- onclick={() => (isOpen = true)}
- title={content}
- type="button"
- >
- <MessageSquareText class="size-icon-sm" />
+ <Chip class="mt-1.5" {disabled} onclick={() => (isOpen = true)} title={content}>
+ <MessageSquareText />
<span class="truncate">Custom system message</span>
- </button>
+ </Chip>
</div>
<DialogSystemMessageEdit
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 d79535613..2a5096d77 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
@@ -9,16 +9,26 @@
import { parseExecShellCommandMeta } from './parsers/exec-shell-command';
import ToolCallBlock from './ToolCallBlock.svelte';
- import { AlertTriangle, Check, CircleStop, Loader2, XCircle } from '@lucide/svelte';
+ import { Button } from '@ggml-org/llama-ui/ui/button';
import {
+ AlertTriangle,
+ Check,
+ CircleStop,
+ Loader2,
+ SquareArrowDown,
+ XCircle
+ } from '@lucide/svelte';
+ import { ShellPromptLine } from '#lib/components/app/index.ts';
+ import {
+ BACKGROUND_TASK_DETACH_LABEL,
+ BACKGROUND_TASK_DETACH_TITLE,
SETTINGS_KEYS,
TOOL_RUNTIME_SCROLL_AT_BOTTOM_THRESHOLD_PX
} from '#lib/constants/index.ts';
import { AgenticSectionType, AttachmentType } from '#lib/enums/index.ts';
- import { settingsStore, toolsStore } from '#lib/stores/index.ts';
+ import { backgroundTasksStore, settingsStore } from '#lib/stores/index.ts';
import type { AgenticSection, DatabaseMessageExtra, ToolResultLine } from '#lib/types/index.ts';
import {
- abbreviateHome,
type ExecShellExitStatus,
highlightCode,
isExitCodeSummaryLine,
@@ -58,6 +68,27 @@
// is not live.
const isLive = $derived(isExecuting);
+ // a running command can move to the background: its call returns, the command goes on as a
+ // task of the conversation, listed under the chat form
+ const canDetach = $derived(
+ isLive && backgroundTasksStore.execIdOf(section.toolCallId) !== undefined
+ );
+ let detaching = $state(false);
+
+ async function detach(event: MouseEvent) {
+ event.stopPropagation();
+
+ if (!section.toolCallId) return;
+
+ detaching = true;
+
+ try {
+ await backgroundTasksStore.detach(section.toolCallId);
+ } finally {
+ detaching = false;
+ }
+ }
+
const isPreResult = $derived(
section.type === AgenticSectionType.TOOL_CALL_PENDING ||
section.type === AgenticSectionType.TOOL_CALL_STREAMING
@@ -107,8 +138,6 @@
const cwd = $derived(
section.toolCwd ?? (isStreaming && isPreResult ? conversationCwd : undefined)
);
- const home = $derived(toolsStore.serverHome);
- const wdDisplay = $derived(abbreviateHome(cwd ?? '', home));
const exitBadgeClass = $derived(
execShellExitStatus?.timedOut
@@ -213,24 +242,6 @@
});
</script>
-{#snippet promptLine()}
- {#if cwd}
- <span class="exec-wd" title={cwd}>{wdDisplay}</span>
- {/if}
-
- <span class="exec-prompt">$</span>
-
- {#if highlightedCommandHtml}
- <span class="font-mono">{@html highlightedCommandHtml}</span>
- {:else}
- <span class="font-mono">{execShellMeta?.command}</span>
- {/if}
-
- {#if commandStreaming}
- <span class="exec-cursor"></span>
- {/if}
-{/snippet}
-
<ToolCallBlock
emptyResultIsInterrupted
extraLiveStreaming={isLive}
@@ -266,7 +277,12 @@
{#snippet children(_meta, ctx)}
<div class="terminal-frame">
<div class="exec-prompt-line font-mono text-caption">
- {@render promptLine()}
+ <ShellPromptLine
+ command={execShellMeta?.command ?? ''}
+ cursor={commandStreaming}
+ {cwd}
+ highlightedHtml={highlightedCommandHtml}
+ />
</div>
{#if (ctx.isPending && !commandStreaming) || (isLive && !section.toolResult)}
@@ -334,40 +350,24 @@
{/snippet}
</ToolCallBlock>
-<style>
- :root {
- --exec-wd-margin: 0.4rem;
- }
-
- .exec-wd {
- font-family: var(--font-mono);
- color: var(--fg-muted);
- margin-right: var(--exec-wd-margin);
- }
-
- .exec-prompt {
- font-family: var(--font-mono);
- color: var(--fg-muted);
- opacity: 0.55;
- margin-right: var(--exec-wd-margin);
- }
-
- .exec-cursor {
- display: inline-block;
- width: 0.5em;
- height: 1.05em;
- margin-left: 0.15rem;
- vertical-align: text-bottom;
- background: var(--fg-default);
- animation: exec-cursor-blink 1.1s steps(1) infinite;
- }
-
- @keyframes exec-cursor-blink {
- 50% {
- opacity: 0;
- }
- }
+<!-- outside the block, so it shows whether or not the block is open -->
+{#if canDetach}
+ <div class="-mt-1 mb-2 flex">
+ <Button
+ data-detach-command
+ disabled={detaching}
+ onclick={detach}
+ size="xs"
+ title={BACKGROUND_TASK_DETACH_TITLE}
+ variant="secondary"
+ >
+ <SquareArrowDown />
+ {BACKGROUND_TASK_DETACH_LABEL}
+ </Button>
+ </div>
+{/if}
+<style>
.exec-title-command {
color: var(--fg-muted);
font-size: 0.92em;
@@ -387,10 +387,6 @@
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/ChatScreen/ChatScreenForm.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenForm.svelte
index 898d2e134..e0dda24cb 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenForm.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenForm.svelte
@@ -223,6 +223,7 @@
onSystemPromptClick={handleSystemPromptClick}
onUploadedFileRemove={handleUploadedFileRemove}
placeholder={isSystemMode ? 'System message...' : undefined}
+ showBackgroundTasks
singleRow={settingsStore.config[SETTINGS_KEYS.SINGLE_ROW_CHAT_FORM] !== false}
systemMode={isSystemMode}
/>
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 282c16e90..2276eff89 100644
--- a/ui/apps/chat/src/lib/components/app/chat/index.ts
+++ b/ui/apps/chat/src/lib/components/app/chat/index.ts
@@ -267,6 +267,7 @@ export { default as ChatFormInput } from './ChatForm/ChatFormInput/ChatFormInput
* synthetic "Set working directory to ..." user message into chat history
* and is enforced on tool calls via the `x-tool-cwd` request header.
*/
+export { default as ChatFormBackgroundTasks } from './ChatForm/ChatFormBackgroundTasks/ChatFormBackgroundTasks.svelte';
export { default as ChatFormCurrentWorkingDirectory } from './ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectory.svelte';
/**
diff --git a/ui/apps/chat/src/lib/components/app/content/ShellPromptLine.svelte b/ui/apps/chat/src/lib/components/app/content/ShellPromptLine.svelte
new file mode 100644
index 000000000..fa3dd8d84
--- /dev/null
+++ b/ui/apps/chat/src/lib/components/app/content/ShellPromptLine.svelte
@@ -0,0 +1,79 @@
+<script lang="ts">
+ // The prompt line of a shell command, as a terminal shows it: the working directory with the
+ // home folder abbreviated, a dim `$`, then the command, highlighted when given its HTML.
+ import { toolsStore } from '#lib/stores/index.ts';
+ import { abbreviateHome } from '#lib/utils/index.ts';
+
+ interface Props {
+ command: string;
+ cwd?: string;
+ /** The command highlighted as bash, rendered instead of the plain text */
+ highlightedHtml?: string;
+ /** A blinking block after the command, while it is still being written */
+ cursor?: boolean;
+ /** Keep it on one line, cutting the command short, instead of wrapping it */
+ singleLine?: boolean;
+ }
+
+ let { command, cursor = false, cwd, highlightedHtml, singleLine = false }: Props = $props();
+
+ const cwdLabel = $derived(cwd ? abbreviateHome(cwd, toolsStore.serverHome) : '');
+</script>
+
+<span class={['shell-prompt-line font-mono', singleLine && 'flex min-w-0 items-baseline']}>
+ {#if cwd}
+ <span class="shell-cwd shrink-0" title={cwd}>{cwdLabel}</span>
+ {/if}
+
+ <span class="shell-dollar shrink-0">$</span>
+
+ <span class={['shell-command', singleLine ? 'min-w-0 truncate' : 'wrap']} title={command}>
+ {#if highlightedHtml}
+ {@html highlightedHtml}
+ {:else}
+ {command}
+ {/if}
+ </span>
+
+ {#if cursor}
+ <span class="shell-cursor"></span>
+ {/if}
+</span>
+
+<style>
+ .shell-prompt-line {
+ --shell-prompt-gap: 0.4rem;
+ --shell-dollar-opacity: 0.55;
+ }
+
+ .shell-cwd,
+ .shell-dollar {
+ color: var(--fg-muted);
+ margin-right: var(--shell-prompt-gap);
+ }
+
+ .shell-dollar {
+ opacity: var(--shell-dollar-opacity);
+ }
+
+ .shell-command.wrap {
+ white-space: pre-wrap;
+ word-break: break-word;
+ }
+
+ .shell-cursor {
+ display: inline-block;
+ width: 0.5em;
+ height: 1.05em;
+ margin-left: 0.15rem;
+ vertical-align: text-bottom;
+ background: var(--fg-default);
+ animation: shell-cursor-blink 1.1s steps(1) infinite;
+ }
+
+ @keyframes shell-cursor-blink {
+ 50% {
+ opacity: 0;
+ }
+ }
+</style>
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 c3d69b6d6..7b4e7c6bd 100644
--- a/ui/apps/chat/src/lib/components/app/content/index.ts
+++ b/ui/apps/chat/src/lib/components/app/content/index.ts
@@ -126,6 +126,15 @@ export { default as CollapsibleContentBlock } from './CollapsibleContentBlock.sv
*/
export { default as CollapsibleTerminalBlock } from './CollapsibleTerminalBlock.svelte';
+/**
+ * **ShellPromptLine** - A shell command as a terminal prompt shows it
+ *
+ * The working directory (home abbreviated), a dim `$` and the command, optionally
+ * highlighted and with a typing cursor. Shared by the shell tool call and the
+ * background tasks list so both read the same.
+ */
+export { default as ShellPromptLine } from './ShellPromptLine.svelte';
+
/**
* **MermaidPreview** - Pan and zoom viewer for a diagram's svg
*
diff --git a/ui/apps/chat/src/lib/constants/api-endpoints.constants.ts b/ui/apps/chat/src/lib/constants/api-endpoints.constants.ts
index 2f6efb94c..532fa147e 100644
--- a/ui/apps/chat/src/lib/constants/api-endpoints.constants.ts
+++ b/ui/apps/chat/src/lib/constants/api-endpoints.constants.ts
@@ -24,6 +24,14 @@ export const API_TOOLS = {
LIST: '/tools'
};
+// the background tasks of a conversation: `POST` moves a running command to the background,
+// `DELETE` stops one, and both answer with the task they changed
+export const API_TOOLS_TASKS = {
+ EVENTS: '/tools/tasks/events',
+ OUTPUT: '/tools/tasks/output',
+ TASKS: '/tools/tasks'
+};
+
// resumable stream routes, the conv::model identity travels as the conv_id query param
// because model names can contain slashes that a path segment cannot carry
// resume retry cadence while the owning model is still loading (server answers 503)
diff --git a/ui/apps/chat/src/lib/constants/background-tasks.constants.ts b/ui/apps/chat/src/lib/constants/background-tasks.constants.ts
new file mode 100644
index 000000000..61aa63b55
--- /dev/null
+++ b/ui/apps/chat/src/lib/constants/background-tasks.constants.ts
@@ -0,0 +1,37 @@
+// how long the task event stream waits before it reads again after it went away, doubling
+// each time up to the maximum
+export const BACKGROUND_TASKS_RETRY_MS = 1000;
+export const BACKGROUND_TASKS_RETRY_MAX_MS = 15_000;
+
+// how much of a task's output the chat keeps, the same as the server does: the front is
+// dropped past it
+export const BACKGROUND_TASK_LOG_MAX_LENGTH = 256 * 1024;
+
+/** The background tasks dialog's title, and what it says while the conversation runs none */
+export const BACKGROUND_TASKS_DIALOG_TITLE = 'Background tasks';
+export const BACKGROUND_TASKS_EMPTY_LABEL = 'Nothing is running in the background.';
+export const BACKGROUND_TASKS_DIALOG_DESCRIPTION =
+ 'Commands llama-server keeps running for this conversation, with their output';
+
+/** What an open task row shows before the task printed anything */
+export const BACKGROUND_TASK_NO_OUTPUT_LABEL = 'No output yet';
+
+/** Stopping a task, from its row or all of them at once */
+export const BACKGROUND_TASK_STOP_LABEL = 'Stop';
+export const BACKGROUND_TASK_STOP_ARIA_LABEL = 'Stop task';
+export const BACKGROUND_TASK_STOP_FAILED = 'Could not stop the task';
+export const BACKGROUND_TASKS_STOP_ALL_LABEL = 'Stop all';
+
+/** Above an output only the end of was kept */
+export const BACKGROUND_TASK_SKIPPED_LABEL = (bytes: number): string =>
+ `[${bytes} earlier bytes dropped]`;
+
+/** The button under a running shell call that lets it go on as a background task */
+export const BACKGROUND_TASK_DETACH_LABEL = 'Move to background';
+export const BACKGROUND_TASK_DETACH_TITLE =
+ 'Keep it running as a background task and let the agent go on';
+export const BACKGROUND_TASK_DETACH_FAILED = 'Could not move the command to the background';
+
+/** The chip's label: how many tasks the conversation runs */
+export const BACKGROUND_TASKS_RUNNING_LABEL = (count: number): string =>
+ `${count} background ${count === 1 ? 'task' : 'tasks'}`;
diff --git a/ui/apps/chat/src/lib/constants/index.ts b/ui/apps/chat/src/lib/constants/index.ts
index b01f3f57f..bc482b596 100644
--- a/ui/apps/chat/src/lib/constants/index.ts
+++ b/ui/apps/chat/src/lib/constants/index.ts
@@ -4,6 +4,7 @@
export * from './agentic.constants';
export * from './api-endpoints.constants';
export * from './app.constants';
+export * from './background-tasks.constants';
export * from './backend.constants';
export * from './chat-tabs.constants';
export * from './database.constants';
diff --git a/ui/apps/chat/src/lib/constants/tool-ui.constants.ts b/ui/apps/chat/src/lib/constants/tool-ui.constants.ts
index dce125262..f0970379e 100644
--- a/ui/apps/chat/src/lib/constants/tool-ui.constants.ts
+++ b/ui/apps/chat/src/lib/constants/tool-ui.constants.ts
@@ -8,6 +8,7 @@
// ChatMessageToolCallBlockSearchResults for prior art).
import Braces from '@lucide/svelte/icons/braces';
+import CircleDashed from '@lucide/svelte/icons/circle-dashed';
import Clock from '@lucide/svelte/icons/clock';
import Eye from '@lucide/svelte/icons/eye';
import FilePen from '@lucide/svelte/icons/file-pen';
@@ -38,6 +39,11 @@ export const TOOL_UI: Readonly<Record<BuiltInTool, ToolUiEntry>> = {
label: 'Search chats',
source: ToolSource.BROWSER
},
+ [BuiltInTool.SERVER_BACKGROUND_TASK]: {
+ icon: CircleDashed,
+ label: 'Background task',
+ source: ToolSource.SERVER
+ },
[BuiltInTool.SERVER_EDIT_FILE]: { icon: FilePen, label: 'Edit file', source: ToolSource.SERVER },
[BuiltInTool.SERVER_EXEC_SHELL_COMMAND]: {
icon: Terminal,
diff --git a/ui/apps/chat/src/lib/enums/index.ts b/ui/apps/chat/src/lib/enums/index.ts
index 088d0d0c7..3e52bc46b 100644
--- a/ui/apps/chat/src/lib/enums/index.ts
+++ b/ui/apps/chat/src/lib/enums/index.ts
@@ -121,6 +121,8 @@ export {
export { KeyboardKey } from './keyboard.enums';
export {
+ BackgroundTaskStatus,
+ BackgroundTasksServerEvent,
BuiltInTool,
GlobSearchType,
SearchChatsMessageSelection,
diff --git a/ui/apps/chat/src/lib/enums/tools.enums.ts b/ui/apps/chat/src/lib/enums/tools.enums.ts
index 2bda68722..7381b3b81 100644
--- a/ui/apps/chat/src/lib/enums/tools.enums.ts
+++ b/ui/apps/chat/src/lib/enums/tools.enums.ts
@@ -46,6 +46,7 @@ export enum BuiltInTool {
BROWSER_READ_MEDIA = 'read_media',
BROWSER_RUN_JAVASCRIPT = 'run_javascript',
BROWSER_SEARCH_CHATS = 'search_chats',
+ SERVER_BACKGROUND_TASK = 'background_task',
SERVER_EDIT_FILE = 'edit_file',
SERVER_EXEC_SHELL_COMMAND = 'exec_shell_command',
SERVER_FILE_GLOB_SEARCH = 'file_glob_search',
@@ -67,3 +68,18 @@ export enum SearchChatsOrder {
ASC = 'asc',
DESC = 'desc'
}
+
+/** What a background task is doing, as llama-server names it */
+export enum BackgroundTaskStatus {
+ EXITED = 'exited',
+ RUNNING = 'running',
+ STOPPED = 'stopped'
+}
+
+/** The events llama-server sends on `GET /tools/tasks/events` */
+export enum BackgroundTasksServerEvent {
+ SNAPSHOT = 'snapshot',
+ TASK_EXITED = 'task_exited',
+ TASK_OUTPUT = 'task_output',
+ TASK_STARTED = 'task_started'
+}
diff --git a/ui/apps/chat/src/lib/services/background-tasks.service.ts b/ui/apps/chat/src/lib/services/background-tasks.service.ts
new file mode 100644
index 000000000..7fc675513
--- /dev/null
+++ b/ui/apps/chat/src/lib/services/background-tasks.service.ts
@@ -0,0 +1,87 @@
+/**
+ * BackgroundTasksService - The commands llama-server keeps running for a conversation
+ *
+ * `exec_shell_command` runs every command as a task. A task outlives its call once it moves to
+ * the background - the model asks for that when it starts the command, the user asks for it while
+ * the command runs - and it then belongs to the conversation the call carried in its
+ * `X-Conversation-Id` header, which `ToolsService` sends. Every route is scoped to the
+ * conversation the request names, so every call here names one. The server side, and what each
+ * route answers, is documented in `tools/server/README-dev.md`.
+ *
+ * No state: the tasks of the conversation the chat is on live in `backgroundTasksStore`.
+ */
+
+import { API_TOOLS_TASKS } from '#lib/constants/index.ts';
+import type {
+ BackgroundTask,
+ BackgroundTaskOutput,
+ BackgroundTasksEvent
+} from '#lib/types/index.ts';
+import { apiFetch } from '#lib/utils/api-fetch.ts';
+import { getAuthHeaders } from '#lib/utils/api-headers.ts';
+import { serverUrl } from '#lib/utils/server-config.ts';
+import { parseSseJsonStream } from '#lib/utils/sse.ts';
+
+/** The query of a route that works on one task of one conversation */
+function taskParams(conversationId: string, id: number): URLSearchParams {
+ return new URLSearchParams({ conv_id: conversationId, id: String(id) });
+}
+
+export class BackgroundTasksService {
+ /** Move a running command to the background: its call returns at once, the command goes on */
+ static detach(conversationId: string, execId: number): Promise<BackgroundTask> {
+ return apiFetch<BackgroundTask>(API_TOOLS_TASKS.TASKS, {
+ body: JSON.stringify({ conv_id: conversationId, from_exec_id: execId }),
+ method: 'POST'
+ });
+ }
+
+ /**
+ * The tasks of a conversation: a `snapshot` of them, then an event every time one starts,
+ * prints or ends. The stream stays open while the page keeps reading it, so a caller reads
+ * it again when this generator returns or throws.
+ */
+ static async *events(
+ conversationId: string,
+ signal?: AbortSignal
+ ): AsyncGenerator<BackgroundTasksEvent> {
+ const params = new URLSearchParams({ conv_ids: conversationId });
+ const response = await fetch(`${serverUrl(API_TOOLS_TASKS.EVENTS)}?${params}`, {
+ headers: { Accept: 'text/event-stream', ...getAuthHeaders() },
+ signal
+ });
+
+ if (!response.ok || !response.body) {
+ throw new Error(`background tasks answered ${response.status}`);
+ }
+
+ for await (const { data } of parseSseJsonStream<BackgroundTasksEvent>(response, signal)) {
+ yield data;
+ }
+ }
+
+ /** What a task printed since `from`; `skipped` says how much the server had dropped by then */
+ static output(
+ conversationId: string,
+ id: number,
+ from: number,
+ signal?: AbortSignal
+ ): Promise<BackgroundTaskOutput> {
+ const params = taskParams(conversationId, id);
+
+ params.set('from', String(from));
+
+ return apiFetch<BackgroundTaskOutput>(`${API_TOOLS_TASKS.OUTPUT}?${params}`, {
+ authOnly: true,
+ signal
+ });
+ }
+
+ /** Stop a task, with everything it started */
+ static stop(conversationId: string, id: number): Promise<BackgroundTask> {
+ return apiFetch<BackgroundTask>(`${API_TOOLS_TASKS.TASKS}?${taskParams(conversationId, id)}`, {
+ authOnly: true,
+ method: 'DELETE'
+ });
+ }
+}
diff --git a/ui/apps/chat/src/lib/services/tools.service.ts b/ui/apps/chat/src/lib/services/tools.service.ts
index 2f0dd8fa8..ada76941f 100644
--- a/ui/apps/chat/src/lib/services/tools.service.ts
+++ b/ui/apps/chat/src/lib/services/tools.service.ts
@@ -20,16 +20,20 @@ export class ToolsService {
* @param cwd - Working directory for the tool call, sent as the
* x-tool-cwd request header. The server resolves relative paths
* against it; the model cannot override it.
+ * @param conversationId - The conversation the call belongs to, sent as the
+ * X-Conversation-Id header: a command it starts can then move to the
+ * background as a task of that conversation.
*/
static async executeTool(
toolName: string,
params: Record<string, unknown>,
signal?: AbortSignal,
- cwd?: string
+ cwd?: string,
+ conversationId?: string
): Promise<ToolExecutionResult> {
const result = await apiFetch<Record<string, unknown>>(API_TOOLS.EXECUTE, {
body: JSON.stringify({ params, tool: toolName }),
- headers: cwd ? { [HEADERS.X_TOOL_CWD_HEADER]: cwd } : undefined,
+ headers: toolHeaders(cwd, conversationId),
method: 'POST',
signal
});
@@ -131,12 +135,10 @@ export class ToolsService {
toolName: string,
params: Record<string, unknown>,
signal?: AbortSignal,
- cwd?: string
+ cwd?: string,
+ conversationId?: string
): AsyncGenerator<ToolStreamEvent> {
- const headers = getJsonHeaders();
-
- if (cwd) headers[HEADERS.X_TOOL_CWD_HEADER] = cwd;
-
+ const headers = { ...getJsonHeaders(), ...toolHeaders(cwd, conversationId) };
const response = await fetch(serverUrl(API_TOOLS.EXECUTE), {
body: JSON.stringify({ params, stream: true, tool: toolName }),
headers,
@@ -159,7 +161,11 @@ export class ToolsService {
const event = next.value.data;
- if (event.chunk !== undefined) {
+ if (event.exec_id !== undefined) {
+ yield { chunk: null, done: false, execId: event.exec_id };
+ }
+
+ if (event.chunk) {
yield { chunk: event.chunk, done: false };
}
@@ -182,6 +188,8 @@ export interface ToolStreamEvent {
chunk: string | null;
done: boolean;
error?: string;
+ /** The server's id of the command an `exec_shell_command` call runs, sent first */
+ execId?: number;
}
/** Wire shape of one SSE event from `POST /tools?stream=true`. */
@@ -189,6 +197,18 @@ interface ToolServerEvent {
chunk?: string;
done?: boolean;
error?: string;
+ exec_id?: number;
+}
+
+/** The headers that tell the server where a tool call runs and which conversation it is for */
+function toolHeaders(cwd?: string, conversationId?: string): Record<string, string> {
+ const headers: Record<string, string> = {};
+
+ if (cwd) headers[HEADERS.X_TOOL_CWD_HEADER] = cwd;
+
+ if (conversationId) headers[HEADERS.X_CONVERSATION_ID_HEADER] = conversationId;
+
+ return headers;
}
async function formatNonOkResponse(response: Response): Promise<string> {
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 78524ba33..7d4b44978 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 { SearchChatsService } from '#lib/services/search-chats.service.ts';
import { ToolsService } from '#lib/services/tools.service.ts';
// direct imports between stores, not via the barrel, to avoid circular deps
import { AgenticGates } from '#lib/stores/agentic/gates.svelte.ts';
+import { backgroundTasksStore } from '#lib/stores/background-tasks.svelte.ts';
import { conversationsStore } from '#lib/stores/conversations/index.svelte.ts';
import { mcpStore } from '#lib/stores/mcp/index.svelte.ts';
import { modelsStore } from '#lib/stores/models/index.svelte.ts';
@@ -458,21 +459,39 @@ class AgenticStore {
let accumulated = '';
let isError = false;
- for await (const ev of ToolsService.streamTool(toolName, args, signal, cwd)) {
- if (ev.chunk !== null) {
- accumulated += ev.chunk;
- context.update(accumulated);
- }
+ // the command can move to the background from its row while it runs, as a task of
+ // this conversation
+ try {
+ for await (const ev of ToolsService.streamTool(
+ toolName,
+ args,
+ signal,
+ cwd,
+ conversationId
+ )) {
+ if (ev.execId !== undefined) {
+ backgroundTasksStore.attach(conversationId, toolCall.id, ev.execId);
+ }
- if (ev.done) {
- if (ev.error) {
- accumulated = accumulated ? `${accumulated}\nError: ${ev.error}` : `Error: ${ev.error}`;
+ if (ev.chunk !== null) {
+ accumulated += ev.chunk;
context.update(accumulated);
- isError = true;
}
- break;
+ if (ev.done) {
+ if (ev.error) {
+ accumulated = accumulated
+ ? `${accumulated}\nError: ${ev.error}`
+ : `Error: ${ev.error}`;
+ context.update(accumulated);
+ isError = true;
+ }
+
+ break;
+ }
}
+ } finally {
+ backgroundTasksStore.forget(toolCall.id);
}
return { content: accumulated, isError };
@@ -482,7 +501,7 @@ class AgenticStore {
const args = this.parseToolArguments(toolCall.function.arguments);
const cwd = conversationsStore.activeConversation?.cwd;
- return ToolsService.executeTool(toolName, args, signal, cwd);
+ return ToolsService.executeTool(toolName, args, signal, cwd, conversationId);
}
if (toolSource === ToolSource.BROWSER) {
diff --git a/ui/apps/chat/src/lib/stores/background-tasks.svelte.ts b/ui/apps/chat/src/lib/stores/background-tasks.svelte.ts
new file mode 100644
index 000000000..8509347b8
--- /dev/null
+++ b/ui/apps/chat/src/lib/stores/background-tasks.svelte.ts
@@ -0,0 +1,262 @@
+/**
+ * backgroundTasksStore - The commands the agent left running in this conversation
+ *
+ * llama-server runs every `exec_shell_command` as a task, and a task moved to the background
+ * belongs to the conversation that started it. This store follows the running tasks of the
+ * conversation the chat is on over the server's event stream, reads what they print, moves a
+ * command that is still running to the background, and stops one. The chat form lists them; a
+ * command still attached to its call is detached from its own row in the trace.
+ *
+ * The server owns the list and the processes: this only reads the stream, and a conversation
+ * keeps its tasks when the user goes back to it.
+ */
+
+import {
+ BACKGROUND_TASK_DETACH_FAILED,
+ BACKGROUND_TASK_STOP_FAILED,
+ BACKGROUND_TASKS_RETRY_MAX_MS,
+ BACKGROUND_TASKS_RETRY_MS
+} from '#lib/constants/index.ts';
+import { BackgroundTasksServerEvent, BackgroundTaskStatus, BuiltInTool } from '#lib/enums/index.ts';
+import { BackgroundTasksService } from '#lib/services/background-tasks.service.ts';
+import { agenticMode } from '#lib/stores/agentic-mode.svelte.ts';
+import { toolsStore } from '#lib/stores/tools.svelte.ts';
+import type { BackgroundTask, BackgroundTaskLog, BackgroundTasksEvent } from '#lib/types/index.ts';
+import { appendTaskOutput, emptyTaskLog, sleep } from '#lib/utils/index.ts';
+import { untrack } from 'svelte';
+import { toast } from 'svelte-sonner';
+
+class BackgroundTasksStore {
+ dialogOpen = $state(false);
+
+ // a command still attached to the call that started it: its tool call, and the server's id of it
+ private attached = $state<Record<string, { conversationId: string; execId: number }>>({});
+
+ // the running tasks of the followed conversation, by id
+ private byId = $state<Record<number, BackgroundTask>>({});
+
+ // the conversation whose tasks are kept, empty until the chat is on one
+ private followed = '';
+
+ // what has been read of each task's output
+ private logs = $state<Record<number, BackgroundTaskLog>>({});
+
+ // rows open on screen: only their tasks are read when the server says there is new output
+ private open = new Set<number>();
+
+ // a read of a task in flight, so two events do not read it twice
+ private reading = new Set<number>();
+
+ // tasks that printed again while a read was in flight: read once more when it lands
+ private stale = new Set<number>();
+
+ /** The server runs commands, and keeps the ones that outlive their call */
+ get available(): boolean {
+ return agenticMode.enabled && toolsStore.hasServerTool(BuiltInTool.SERVER_BACKGROUND_TASK);
+ }
+
+ /** The conversation's running tasks, the newest first */
+ get tasks(): BackgroundTask[] {
+ return Object.values(this.byId).sort((a, b) => b.started_at - a.started_at || b.id - a.id);
+ }
+
+ /** A call whose command is running and can still be moved to the background */
+ attach(conversationId: string, toolCallId: string, execId: number): void {
+ this.attached[toolCallId] = { conversationId, execId };
+ }
+
+ /**
+ * Moves the command of a running call to the background: its call returns at once and the
+ * command keeps running as a task of the conversation.
+ */
+ async detach(toolCallId: string): Promise<void> {
+ const call = this.attached[toolCallId];
+
+ if (!call) return;
+
+ try {
+ const task = await BackgroundTasksService.detach(call.conversationId, call.execId);
+
+ this.forget(toolCallId);
+ this.keep(call.conversationId, task);
+ } catch (error) {
+ // a command that ended on its own a moment before has left `attached`: nothing to say
+ if (this.attached[toolCallId]) {
+ toast.error(BACKGROUND_TASK_DETACH_FAILED, {
+ description: error instanceof Error ? error.message : undefined
+ });
+ }
+ }
+ }
+
+ /** The command a running call is still attached to, by the id of that call */
+ execIdOf(toolCallId?: string): number | undefined {
+ return toolCallId ? this.attached[toolCallId]?.execId : undefined;
+ }
+
+ /** Its call is over: the command either ended with it or is a task the list shows */
+ forget(toolCallId: string): void {
+ delete this.attached[toolCallId];
+ }
+
+ /** What the chat has read of a task's output */
+ log(taskId: number): BackgroundTaskLog {
+ return this.logs[taskId] ?? emptyTaskLog();
+ }
+
+ /** Stops a task, with everything it started */
+ async stop(taskId: number): Promise<void> {
+ const conversationId = this.followed;
+
+ if (!this.byId[taskId]) return;
+
+ try {
+ this.keep(conversationId, await BackgroundTasksService.stop(conversationId, taskId));
+ } catch (error) {
+ // a task that ended on its own a moment before has left the list: nothing to say
+ if (conversationId === this.followed && this.byId[taskId]) {
+ toast.error(BACKGROUND_TASK_STOP_FAILED, {
+ description: error instanceof Error ? error.message : undefined
+ });
+ }
+ }
+ }
+
+ async stopAll(): Promise<void> {
+ await Promise.all(this.tasks.map((task) => this.stop(task.id)));
+ }
+
+ /**
+ * Keeps the tasks of a conversation, and reads their event stream while `follow` is set;
+ * call it from an `$effect` and hand the effect the return value. The list starts empty
+ * when the chat moves to another conversation; a stream that stops and starts again on the
+ * same one (the tab was hidden, the server went away) keeps what was read.
+ */
+ watch(conversationId: string, follow: boolean): void | (() => void) {
+ if (conversationId !== this.followed) this.reset(conversationId);
+
+ if (!conversationId || !follow) return;
+
+ const controller = new AbortController();
+
+ // the request reads settings for its headers: none of that is this effect's business
+ untrack(() => void this.follow(conversationId, controller.signal));
+
+ return () => controller.abort();
+ }
+
+ /**
+ * Reads a task's output while its row is open, and once at once to fill the row in;
+ * give the return value to an `$effect`.
+ */
+ watchOutput(taskId: number): () => void {
+ this.open.add(taskId);
+ void this.read(taskId);
+
+ return () => this.open.delete(taskId);
+ }
+
+ /** One event of the task stream */
+ private apply(conversationId: string, event: BackgroundTasksEvent): void {
+ switch (event.event) {
+ case BackgroundTasksServerEvent.SNAPSHOT:
+ this.byId = {};
+
+ for (const task of event.tasks) this.keep(conversationId, task);
+
+ // the stream may have missed what the open rows printed while it was away
+ for (const taskId of this.open) void this.read(taskId);
+
+ break;
+ case BackgroundTasksServerEvent.TASK_STARTED:
+ case BackgroundTasksServerEvent.TASK_EXITED:
+ this.keep(conversationId, event.task);
+
+ break;
+ case BackgroundTasksServerEvent.TASK_OUTPUT:
+ if (this.open.has(event.id)) void this.read(event.id);
+
+ break;
+ }
+ }
+
+ // Reads the task stream of a conversation, again when it goes away, until it is aborted.
+ private async follow(conversationId: string, signal: AbortSignal): Promise<void> {
+ let delay = BACKGROUND_TASKS_RETRY_MS;
+
+ while (!signal.aborted) {
+ try {
+ for await (const event of BackgroundTasksService.events(conversationId, signal)) {
+ if (signal.aborted) return;
+
+ delay = BACKGROUND_TASKS_RETRY_MS;
+ this.apply(conversationId, event);
+ }
+ } catch {
+ // the server went away: read again below
+ }
+
+ if (signal.aborted) return;
+
+ await sleep(delay);
+ delay = Math.min(delay * 2, BACKGROUND_TASKS_RETRY_MAX_MS);
+ }
+ }
+
+ // A task as the server last answered it: listed while it runs, gone once it is done. An
+ // answer that lands after the chat moved to another conversation is not this list's.
+ private keep(conversationId: string, task: BackgroundTask): void {
+ if (conversationId !== this.followed) return;
+
+ if (task.status === BackgroundTaskStatus.RUNNING) {
+ this.byId[task.id] = task;
+ } else {
+ delete this.byId[task.id];
+ delete this.logs[task.id];
+ }
+ }
+
+ // What a running task printed since the last read
+ private async read(taskId: number): Promise<void> {
+ const conversationId = this.followed;
+
+ if (!this.byId[taskId]) return;
+
+ if (this.reading.has(taskId)) {
+ this.stale.add(taskId);
+
+ return;
+ }
+
+ this.reading.add(taskId);
+
+ try {
+ const read = await BackgroundTasksService.output(
+ conversationId,
+ taskId,
+ this.logs[taskId]?.offset ?? 0
+ );
+
+ if (conversationId === this.followed) {
+ this.logs[taskId] = appendTaskOutput(this.logs[taskId], read);
+ }
+ } catch {
+ // the server went away, or the task left its list: keep what is known of it
+ } finally {
+ this.reading.delete(taskId);
+ }
+
+ if (this.stale.delete(taskId)) await this.read(taskId);
+ }
+
+ /** The chat moved to another conversation: start its list empty */
+ private reset(conversationId: string): void {
+ this.followed = conversationId;
+ this.byId = {};
+ this.logs = {};
+ this.open.clear();
+ this.stale.clear();
+ }
+}
+
+export const backgroundTasksStore = new BackgroundTasksStore();
diff --git a/ui/apps/chat/src/lib/stores/index.ts b/ui/apps/chat/src/lib/stores/index.ts
index 3ca69b1d9..438810960 100644
--- a/ui/apps/chat/src/lib/stores/index.ts
+++ b/ui/apps/chat/src/lib/stores/index.ts
@@ -34,6 +34,9 @@ export { agenticStore } from './agentic/index.svelte';
// CONVERSATION MEDIA (one slideshow of the thread's images, audio and video)
export { mediaGalleryStore } from './media-gallery.svelte';
+// BACKGROUND TASKS (commands llama-server keeps running for a conversation, e.g. dev servers)
+export { backgroundTasksStore } from './background-tasks.svelte';
+
// CONVERSATIONS
export { sidebarDragStore } from './sidebar-drag.svelte';
export { conversationsStore } from './conversations/index.svelte';
diff --git a/ui/apps/chat/src/lib/stores/tools.svelte.ts b/ui/apps/chat/src/lib/stores/tools.svelte.ts
index 153e44389..87ebfc836 100644
--- a/ui/apps/chat/src/lib/stores/tools.svelte.ts
+++ b/ui/apps/chat/src/lib/stores/tools.svelte.ts
@@ -360,6 +360,10 @@ class ToolsStore {
});
}
+ hasServerTool(name: BuiltInTool): boolean {
+ return this._serverTools.some((def) => def.function.name === name);
+ }
+
/**
* Load persisted disabled tools and fetch the builtin tool list.
* Called by initStores() after migrations have run.
@@ -524,10 +528,6 @@ class ToolsStore {
}
}
- private hasServerTool(name: BuiltInTool): boolean {
- return this._serverTools.some((def) => def.function.name === name);
- }
-
private inferTypeFromDefault(value: unknown): string | undefined {
if (typeof value === 'string') return 'string';
diff --git a/ui/apps/chat/src/lib/types/index.ts b/ui/apps/chat/src/lib/types/index.ts
index eb3ef0701..3c416a960 100644
--- a/ui/apps/chat/src/lib/types/index.ts
+++ b/ui/apps/chat/src/lib/types/index.ts
@@ -242,6 +242,10 @@ export type { DesktopIconStripItem, MenuAction } from './navigation';
// Tools types
export type {
+ BackgroundTask,
+ BackgroundTaskLog,
+ BackgroundTaskOutput,
+ BackgroundTasksEvent,
EditFileEdit,
EditFileMeta,
EditFileTitleMeta,
diff --git a/ui/apps/chat/src/lib/types/tools.d.ts b/ui/apps/chat/src/lib/types/tools.d.ts
index 4f1ab120a..4c5313065 100644
--- a/ui/apps/chat/src/lib/types/tools.d.ts
+++ b/ui/apps/chat/src/lib/types/tools.d.ts
@@ -1,5 +1,9 @@
import type { OpenAIToolDefinition } from './mcp';
-import type { ToolSource } from '#lib/enums/index.ts';
+import type {
+ BackgroundTasksServerEvent,
+ BackgroundTaskStatus,
+ ToolSource
+} from '#lib/enums/index.ts';
import type { Component } from 'svelte';
/**
@@ -81,3 +85,50 @@ export interface EditFileTitleMeta {
editsApplied?: number;
errorMessage?: string;
}
+
+/**
+ * A command llama-server keeps running for one conversation after the tool call
+ * that started it returned, as its routes answer it (`tools/server/README-dev.md`).
+ * The server owns the list; Llama Chat only reads it.
+ */
+export interface BackgroundTask {
+ /** the server's id of the command: the call that started it and the task it became share it */
+ id: number;
+ command: string;
+ /** the model's description of the call, may be empty */
+ description: string;
+ /** the working directory the command runs in */
+ cwd: string;
+ /** unix seconds */
+ started_at: number;
+ status: BackgroundTaskStatus;
+}
+
+/** One read of `GET /tools/tasks/output`: the task, and what it printed since the offset asked */
+export interface BackgroundTaskOutput extends BackgroundTask {
+ output: string;
+ /** where the read after this one starts */
+ next: number;
+ /** bytes the server dropped between the offset asked and where `output` starts */
+ skipped?: number;
+}
+
+/** What the chat has read of a task's output, so a re-read only asks for the new bytes */
+export interface BackgroundTaskLog {
+ text: string;
+ /** the offset the next read starts at */
+ offset: number;
+ /** what was dropped from the front, so the text does not start at the beginning */
+ skipped: number;
+}
+
+/** One event of `GET /tools/tasks/events` */
+export type BackgroundTasksEvent =
+ /** the conversation's tasks right now, sent first */
+ | { event: BackgroundTasksServerEvent.SNAPSHOT; tasks: BackgroundTask[] }
+ | {
+ event: BackgroundTasksServerEvent.TASK_EXITED | BackgroundTasksServerEvent.TASK_STARTED;
+ task: BackgroundTask;
+ }
+ /** a task printed: the offset its output reaches now */
+ | { event: BackgroundTasksServerEvent.TASK_OUTPUT; id: number; offset: number };
diff --git a/ui/apps/chat/src/lib/utils/background-tasks.ts b/ui/apps/chat/src/lib/utils/background-tasks.ts
new file mode 100644
index 000000000..cdad2657b
--- /dev/null
+++ b/ui/apps/chat/src/lib/utils/background-tasks.ts
@@ -0,0 +1,26 @@
+import { BACKGROUND_TASK_LOG_MAX_LENGTH } from '#lib/constants/index.ts';
+import type { BackgroundTaskLog, BackgroundTaskOutput } from '#lib/types/index.ts';
+
+/** An output nothing has been read of yet */
+export function emptyTaskLog(): BackgroundTaskLog {
+ return { offset: 0, skipped: 0, text: '' };
+}
+
+/**
+ * A read added to what the chat has of a task's output. Only the end of a long output is
+ * kept: what is cut from the front counts as skipped, like what the server dropped.
+ */
+export function appendTaskOutput(
+ current: BackgroundTaskLog | undefined,
+ read: BackgroundTaskOutput
+): BackgroundTaskLog {
+ const log = current ?? emptyTaskLog();
+ const text = log.text + read.output;
+ const cut = Math.max(0, text.length - BACKGROUND_TASK_LOG_MAX_LENGTH);
+
+ return {
+ offset: Math.max(log.offset, read.next),
+ skipped: log.skipped + (read.skipped ?? 0) + cut,
+ text: text.slice(cut)
+ };
+}
diff --git a/ui/apps/chat/src/lib/utils/index.ts b/ui/apps/chat/src/lib/utils/index.ts
index ed7d04d70..68b48a588 100644
--- a/ui/apps/chat/src/lib/utils/index.ts
+++ b/ui/apps/chat/src/lib/utils/index.ts
@@ -223,6 +223,8 @@ export {
// Data URL utilities
export { createBase64DataUrl } from './data-url';
+export { sleep } from './sleep';
+export { appendTaskOutput, emptyTaskLog } from './background-tasks';
// Header utilities
export { parseHeadersToArray, serializeHeaders } from './headers';
diff --git a/ui/apps/chat/src/lib/utils/sleep.ts b/ui/apps/chat/src/lib/utils/sleep.ts
new file mode 100644
index 000000000..254db906f
--- /dev/null
+++ b/ui/apps/chat/src/lib/utils/sleep.ts
@@ -0,0 +1,4 @@
+/** Resolves after `ms` milliseconds */
+export function sleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
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 0503f8e2e..09c12cca0 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
@@ -61,7 +61,7 @@ function promptText(container: Element): string {
}
function hasCursor(container: Element): boolean {
- return container.querySelector('.exec-cursor') !== null;
+ return container.querySelector('.shell-cursor') !== null;
}
describe('exec_shell_command streaming title', () => {
diff --git a/ui/apps/chat/tests/stories/chat/form/ChatFormBackgroundTaskRow.stories.svelte b/ui/apps/chat/tests/stories/chat/form/ChatFormBackgroundTaskRow.stories.svelte
new file mode 100644
index 000000000..d8b8c896c
--- /dev/null
+++ b/ui/apps/chat/tests/stories/chat/form/ChatFormBackgroundTaskRow.stories.svelte
@@ -0,0 +1,49 @@
+<script lang="ts" module>
+ import { defineMeta } from '@storybook/addon-svelte-csf';
+ import ChatFormBackgroundTaskRow from '#lib/components/app/chat/ChatForm/ChatFormBackgroundTasks/ChatFormBackgroundTaskRow.svelte';
+ import { MS_PER_SECOND } from '#lib/constants/index.ts';
+ import { BackgroundTaskStatus } from '#lib/enums/index.ts';
+ import type { BackgroundTask } from '#lib/types/index.ts';
+ import StateGallery from '$llama-ui-stories/helpers/StateGallery.svelte';
+ import StateGalleryItem from '$llama-ui-stories/helpers/StateGalleryItem.svelte';
+
+ // one task of the background tasks dialog: its description, Stop, and its shell
+ // command over the output it printed
+ const { Story } = defineMeta({
+ component: ChatFormBackgroundTaskRow,
+ parameters: {
+ layout: 'padded'
+ },
+ title: 'Llama Chat/Chat/ChatForm/ChatFormBackgroundTaskRow'
+ });
+
+ const STARTED_AT = Math.floor(Date.now() / MS_PER_SECOND);
+
+ const task = (overrides: Partial<BackgroundTask>): BackgroundTask => ({
+ command: 'npx -y http-server /tmp/hello-world -p 8780',
+ cwd: '/tmp',
+ description: 'Serve the hello world page',
+ id: 1,
+ started_at: STARTED_AT,
+ status: BackgroundTaskStatus.RUNNING,
+ ...overrides
+ });
+</script>
+
+<Story asChild name="States">
+ <StateGallery columns={1}>
+ <StateGalleryItem label="With a description">
+ <ChatFormBackgroundTaskRow task={task({ id: 1 })} />
+ </StateGalleryItem>
+
+ <StateGalleryItem label="Command only">
+ <ChatFormBackgroundTaskRow
+ task={task({
+ command: 'npm run build -- --watch',
+ description: '',
+ id: 2
+ })}
+ />
+ </StateGalleryItem>
+ </StateGallery>
+</Story>
diff --git a/ui/apps/chat/tests/unit/background-tasks.test.ts b/ui/apps/chat/tests/unit/background-tasks.test.ts
new file mode 100644
index 000000000..a5289c4c0
--- /dev/null
+++ b/ui/apps/chat/tests/unit/background-tasks.test.ts
@@ -0,0 +1,48 @@
+import { BACKGROUND_TASK_LOG_MAX_LENGTH } from '#lib/constants/index.ts';
+import { BackgroundTaskStatus } from '#lib/enums/index.ts';
+import type { BackgroundTaskOutput } from '#lib/types/index.ts';
+import { appendTaskOutput } from '#lib/utils/background-tasks.ts';
+import { describe, expect, it } from 'vitest';
+
+const read = (overrides: Partial<BackgroundTaskOutput>): BackgroundTaskOutput => ({
+ command: 'npx -y http-server /tmp/hello-world -p 8780',
+ cwd: '/tmp',
+ description: 'Serve the hello world page',
+ id: 7,
+ next: 0,
+ output: '',
+ started_at: 1_800_000_000,
+ status: BackgroundTaskStatus.RUNNING,
+ ...overrides
+});
+
+describe('appendTaskOutput', () => {
+ it('adds what a task printed since the last read', () => {
+ const log = appendTaskOutput(undefined, read({ next: 6, output: 'hello ' }));
+
+ expect(log).toEqual({ offset: 6, skipped: 0, text: 'hello ' });
+ expect(appendTaskOutput(log, read({ next: 11, output: 'world' }))).toEqual({
+ offset: 11,
+ skipped: 0,
+ text: 'hello world'
+ });
+ });
+
+ it('counts what the server dropped before the read', () => {
+ expect(appendTaskOutput(undefined, read({ next: 500, output: 'end', skipped: 497 }))).toEqual({
+ offset: 500,
+ skipped: 497,
+ text: 'end'
+ });
+ });
+
+ it('keeps only the end of a long output', () => {
+ const extra = 10;
+ const output = 'a'.repeat(extra) + 'b'.repeat(BACKGROUND_TASK_LOG_MAX_LENGTH);
+ const log = appendTaskOutput(undefined, read({ next: output.length, output }));
+
+ expect(log.text).toBe('b'.repeat(BACKGROUND_TASK_LOG_MAX_LENGTH));
+ expect(log.skipped).toBe(extra);
+ expect(log.offset).toBe(output.length);
+ });
+});
diff --git a/ui/lib/ui/src/lib/components/ui/button/button.svelte b/ui/lib/ui/src/lib/components/ui/button/button.svelte
index ae5708010..0d4f6b6d8 100644
--- a/ui/lib/ui/src/lib/components/ui/button/button.svelte
+++ b/ui/lib/ui/src/lib/components/ui/button/button.svelte
@@ -17,13 +17,17 @@
'icon-lg': 'size-(--height-control-lg)',
'icon-sm': 'size-5 rounded-sm',
lg: 'h-control-lg rounded-lg px-6 has-[>svg]:px-4',
- sm: 'h-control-sm gap-1.5 rounded-md px-3 has-[>svg]:px-2.5'
+ sm: 'h-control-sm gap-1.5 rounded-md px-3 has-[>svg]:px-2.5',
+ // a compact action inside a row or a block: caption text, no fixed height
+ xs: 'gap-1.5 rounded-md px-2 py-1 text-caption [&_svg:not([class*=size-])]:size-icon-xs'
},
variant: {
default:
'matte-key-solid [--key-edge:var(--button-primary-edge)] bg-(--action-primary) text-(--fg-on-action) hover:bg-(--action-primary-hover)',
destructive:
'matte-key-solid [--key-edge:var(--button-danger-edge)] [--key-sheen-solid:var(--button-danger-sheen)] bg-(--action-danger) hover:bg-(--action-danger-hover) focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 text-(--fg-on-danger)!',
+ 'danger-secondary':
+ 'bg-(--action-danger-secondary) text-(--fg-danger) hover:bg-(--action-danger-secondary-hover) focus-visible:bg-(--action-danger-secondary-hover) focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40',
ghost:
'hover:text-(--fg-default) hover:bg-(--action-ghost-hover) hover:shadow-(--button-shadow) backdrop-blur-sm',
outline:
diff --git a/ui/lib/ui/src/lib/components/ui/chip/chip.svelte b/ui/lib/ui/src/lib/components/ui/chip/chip.svelte
new file mode 100644
index 000000000..95cce745b
--- /dev/null
+++ b/ui/lib/ui/src/lib/components/ui/chip/chip.svelte
@@ -0,0 +1,32 @@
+<script lang="ts" module>
+ import { tv } from '../utils';
+
+ // a quiet button for what a form carries along (a working directory, a system message,
+ // background tasks): muted text and a small icon, the text's colour on hover
+ export const chipVariants = tv({
+ base: 'flex w-auto min-w-0 items-center gap-1 rounded-md px-2 py-1 text-caption text-muted-foreground backdrop-blur-2xl outline-none hover:text-foreground focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 [&_svg:not([class*=size-])]:size-icon-sm [&_svg]:shrink-0'
+ });
+</script>
+
+<script lang="ts">
+ import { cn, type WithElementRef } from '../utils';
+ import type { HTMLButtonAttributes } from 'svelte/elements';
+
+ let {
+ children,
+ class: className,
+ ref = $bindable(null),
+ type = 'button',
+ ...restProps
+ }: WithElementRef<HTMLButtonAttributes> = $props();
+</script>
+
+<button
+ bind:this={ref}
+ class={cn(chipVariants(), className)}
+ data-slot="chip"
+ {type}
+ {...restProps}
+>
+ {@render children?.()}
+</button>
diff --git a/ui/lib/ui/src/lib/components/ui/chip/index.ts b/ui/lib/ui/src/lib/components/ui/chip/index.ts
new file mode 100644
index 000000000..408c0c2fc
--- /dev/null
+++ b/ui/lib/ui/src/lib/components/ui/chip/index.ts
@@ -0,0 +1,2 @@
+export { default as Chip } from './chip.svelte';
+export { chipVariants } from './chip.svelte';
diff --git a/ui/lib/ui/src/lib/styles/tokens/semantic.css b/ui/lib/ui/src/lib/styles/tokens/semantic.css
index 842e70859..b467071e6 100644
--- a/ui/lib/ui/src/lib/styles/tokens/semantic.css
+++ b/ui/lib/ui/src/lib/styles/tokens/semantic.css
@@ -75,6 +75,9 @@
/* one red for every danger state: the danger action is the status fill itself, the alerts' red */
--action-danger: var(--fill-danger);
--action-danger-hover: color-mix(in oklch, var(--action-danger) 90%, transparent);
+ /* the quiet danger action: red text on a faint wash of the same red, stronger on hover */
+ --action-danger-secondary: color-mix(in oklch, var(--fill-danger) 8%, transparent);
+ --action-danger-secondary-hover: color-mix(in oklch, var(--fill-danger) 16%, transparent);
--action-quiet: color-mix(in oklch, var(--neutral-100) 30%, transparent);
--action-quiet-hover: var(--neutral-100);
--action-ghost-hover: color-mix(in oklch, var(--neutral-500) 10%, transparent);
@@ -174,6 +177,8 @@
/* the same red as every danger state, as matte glass: the status fill, frosted and translucent over the page */
--action-danger: color-mix(in oklch, var(--fill-danger) 58%, transparent);
--action-danger-hover: color-mix(in oklch, var(--fill-danger) 68%, transparent);
+ --action-danger-secondary: color-mix(in oklch, var(--fill-danger) 12%, transparent);
+ --action-danger-secondary-hover: color-mix(in oklch, var(--fill-danger) 22%, transparent);
--action-quiet: color-mix(in oklch, var(--neutral-400) 15%, transparent);
--action-quiet-hover: color-mix(in oklch, var(--neutral-400) 25%, transparent);
--action-ghost-hover: color-mix(in oklch, var(--neutral-400) 10%, transparent);
diff --git a/ui/lib/ui/tests/stories/components/actions/Button.stories.svelte b/ui/lib/ui/tests/stories/components/actions/Button.stories.svelte
index bbabfd5a0..30d8df9a0 100644
--- a/ui/lib/ui/tests/stories/components/actions/Button.stories.svelte
+++ b/ui/lib/ui/tests/stories/components/actions/Button.stories.svelte
@@ -20,9 +20,10 @@
'tertiary',
'outline',
'ghost',
- 'destructive'
+ 'destructive',
+ 'danger-secondary'
];
- const sizes: NonNullable<ButtonSize>[] = ['sm', 'default', 'lg'];
+ const sizes: NonNullable<ButtonSize>[] = ['xs', 'sm', 'default', 'lg'];
</script>
<Story asChild name="Default">
@@ -48,6 +49,8 @@
<Button><Plus /> New chat</Button>
<Button variant="destructive"><Trash2 /> Delete</Button>
+
+ <Button variant="danger-secondary"><Trash2 /> Remove</Button>
</div>
</StateGalleryItem>
</StateGallery>
diff --git a/ui/lib/ui/tests/stories/components/actions/Chip.stories.svelte b/ui/lib/ui/tests/stories/components/actions/Chip.stories.svelte
new file mode 100644
index 000000000..4e58062fb
--- /dev/null
+++ b/ui/lib/ui/tests/stories/components/actions/Chip.stories.svelte
@@ -0,0 +1,33 @@
+<script lang="ts" module>
+ import StateGallery from '../../helpers/StateGallery.svelte';
+ import StateGalleryItem from '../../helpers/StateGalleryItem.svelte';
+ import { Chip } from '@ggml-org/llama-ui/ui/chip';
+ import { MessageSquareText, SquareTerminal } from '@lucide/svelte';
+ import { defineMeta } from '@storybook/addon-svelte-csf';
+
+ const { Story } = defineMeta({
+ component: Chip,
+ parameters: {
+ layout: 'centered'
+ },
+ title: 'Llama UI/Components/Actions/Chip'
+ });
+</script>
+
+<Story asChild name="Default">
+ <StateGallery columns={3}>
+ <StateGalleryItem label="Icon and label">
+ <Chip><SquareTerminal /><span class="truncate">1 background task</span></Chip>
+ </StateGalleryItem>
+
+ <StateGalleryItem label="Long label">
+ <Chip class="max-w-48">
+ <MessageSquareText /><span class="truncate">A custom system message that runs long</span>
+ </Chip>
+ </StateGalleryItem>
+
+ <StateGalleryItem label="Disabled">
+ <Chip disabled><MessageSquareText /><span class="truncate">Custom system message</span></Chip>
+ </StateGalleryItem>
+ </StateGallery>
+</Story>