wrapper as a newline', async () => {
+ const screen = render(ChatFormInputRichHarness, { value: SOURCE });
+
+ await tick();
+
+ const root = editableIn(screen.container);
+ const div = document.createElement('div');
+
+ div.textContent = 'second line';
+ root.appendChild(div);
+ fireInput(root);
+ await tick();
+
+ expect(screen.component.getValue()).toBe(`${SOURCE}\nsecond line`);
+ });
+
+ it('serializes a Firefox full
wrap as lines, badge included', async () => {
+ const screen = render(ChatFormInputRichHarness, { value: SOURCE });
+
+ await tick();
+
+ const root = editableIn(screen.container);
+ const first = document.createElement('div');
+
+ while (root.firstChild) first.appendChild(root.firstChild);
+ const second = document.createElement('div');
+
+ second.textContent = 'second line';
+ root.appendChild(first);
+ root.appendChild(second);
+ fireInput(root);
+ await tick();
+
+ expect(screen.component.getValue()).toBe(`${SOURCE}\nsecond line`);
+ });
+
+ it('serializes a
as a newline', async () => {
+ const screen = render(ChatFormInputRichHarness, { value: 'here' });
+
+ await tick();
+
+ const root = editableIn(screen.container);
+
+ root.appendChild(document.createElement('br'));
+ root.appendChild(document.createTextNode('second line'));
+ fireInput(root);
+ await tick();
+
+ expect(screen.component.getValue()).toBe('here\nsecond line');
+ });
+
+ it('ignores a trailing
(browser caret placeholder)', async () => {
+ const screen = render(ChatFormInputRichHarness, { value: 'abc' });
+
+ await tick();
+
+ const root = editableIn(screen.container);
+
+ root.appendChild(document.createElement('br'));
+ fireInput(root);
+ await tick();
+
+ expect(screen.component.getValue()).toBe('abc');
+ });
+
+ it('serializes one newline per empty-line
', async () => {
+ const screen = render(ChatFormInputRichHarness, { value: 'abc' });
+
+ await tick();
+
+ const root = editableIn(screen.container);
+
+ for (let i = 0; i < 2; i++) {
+ const div = document.createElement('div');
+
+ div.appendChild(document.createElement('br'));
+ root.appendChild(div);
+ }
+ fireInput(root);
+ await tick();
+
+ expect(screen.component.getValue()).toBe('abc\n\n');
+ });
+
+ it('treats a
-only buffer as empty for the placeholder', async () => {
+ const screen = render(ChatFormInputRichHarness, { value: 'abc' });
+
+ await tick();
+
+ const root = editableIn(screen.container);
+ const div = document.createElement('div');
+
+ div.appendChild(document.createElement('br'));
+ root.replaceChildren(div);
+ fireInput(root);
+ await tick();
+
+ expect(screen.component.getValue()).toBe('');
+ expect(root.dataset.empty).toBe('true');
+ });
+
+ it('maps the caret across block boundaries in both directions', async () => {
+ const screen = render(ChatFormInputRichHarness, { value: 'abc\ndef' });
+
+ await tick();
+
+ // Rebuild into the Chromium block shape; the source is unchanged,
+ // so no re-render fires.
+ const root = editableIn(screen.container);
+ const div = document.createElement('div');
+
+ div.textContent = 'def';
+ root.replaceChildren(document.createTextNode('abc'), div);
+ fireInput(root);
+ await tick();
+ expect(screen.component.getValue()).toBe('abc\ndef');
+
+ const divText = div.firstChild;
+
+ if (!divText) throw new Error('div text missing');
+
+ setCaret(divText, 2);
+ expect(screen.component.getCaretOffset()).toBe(6);
+
+ screen.component.setCaretOffset(6);
+ const selection = window.getSelection();
+
+ expect(selection?.anchorNode).toBe(divText);
+ expect(selection?.anchorOffset).toBe(2);
+
+ // The boundary newline itself: offset 3 is the end of "abc", offset
+ // 4 the start of the "def" line.
+ screen.component.setCaretOffset(4);
+ expect(window.getSelection()?.anchorNode).toBe(divText);
+ expect(window.getSelection()?.anchorOffset).toBe(0);
+
+ screen.component.setCaretOffset(3);
+ expect(window.getSelection()?.anchorNode).toBe(root.firstChild);
+ expect(window.getSelection()?.anchorOffset).toBe(3);
+ });
+});
diff --git a/tools/ui/tests/client/chat-form-input-rich-undo.svelte.test.ts b/tools/ui/tests/client/chat-form-input-rich-undo.svelte.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..00f07f48203781c5c61b93c716b55a7fe8b974dc
--- /dev/null
+++ b/tools/ui/tests/client/chat-form-input-rich-undo.svelte.test.ts
@@ -0,0 +1,161 @@
+// Guards the editing-key contract of the ChatFormInputRich:
+// undo/redo is replayed from source snapshots (the token rebuilds destroy
+// the native undo stack), and Tab is NOT intercepted (WCAG 2.1.2 no
+// keyboard trap), matching the plain textarea.
+
+import ChatFormInputRichHarness from './components/ChatFormInputRichHarness.svelte';
+import { tick } from 'svelte';
+import { describe, expect, it } from 'vitest';
+import { render } from 'vitest-browser-svelte';
+
+const SOURCE = 'see [docs](file:///a/b)';
+
+function editableIn(container: HTMLElement): HTMLElement {
+ const el = container.querySelector('[role="textbox"]');
+
+ if (!(el instanceof HTMLElement)) throw new Error('ChatFormInputRich not rendered');
+
+ return el;
+}
+
+function type(root: HTMLElement, text: string, inputType = 'insertText') {
+ root.appendChild(document.createTextNode(text));
+ root.dispatchEvent(new InputEvent('input', { bubbles: true, inputType }));
+}
+
+function keydown(root: HTMLElement, init: KeyboardEventInit) {
+ const event = new KeyboardEvent('keydown', { bubbles: true, cancelable: true, ...init });
+
+ root.dispatchEvent(event);
+
+ return event;
+}
+
+describe('ChatFormInputRich undo/redo', () => {
+ it('undoes and redoes an edit across a badge-containing buffer', async () => {
+ const screen = render(ChatFormInputRichHarness, { value: SOURCE });
+
+ await tick();
+
+ const root = editableIn(screen.container);
+
+ type(root, ' more');
+ await tick();
+ expect(screen.component.getValue()).toBe(`${SOURCE} more`);
+
+ const undoEvent = keydown(root, { ctrlKey: true, key: 'z' });
+
+ await tick();
+ expect(undoEvent.defaultPrevented).toBe(true);
+ expect(screen.component.getValue()).toBe(SOURCE);
+
+ const redoEvent = keydown(root, { ctrlKey: true, key: 'z', shiftKey: true });
+
+ await tick();
+ expect(redoEvent.defaultPrevented).toBe(true);
+ expect(screen.component.getValue()).toBe(`${SOURCE} more`);
+ });
+
+ it('redoes with Ctrl+Y as well', async () => {
+ const screen = render(ChatFormInputRichHarness, { value: SOURCE });
+
+ await tick();
+
+ const root = editableIn(screen.container);
+
+ type(root, ' more');
+ await tick();
+ keydown(root, { key: 'z', metaKey: true });
+ await tick();
+ expect(screen.component.getValue()).toBe(SOURCE);
+
+ keydown(root, { ctrlKey: true, key: 'y' });
+ await tick();
+ expect(screen.component.getValue()).toBe(`${SOURCE} more`);
+ });
+
+ it('coalesces a typing burst into one undo step', async () => {
+ const screen = render(ChatFormInputRichHarness, { value: 'abc' });
+
+ await tick();
+
+ const root = editableIn(screen.container);
+
+ type(root, 'd');
+ type(root, 'e');
+ await tick();
+ expect(screen.component.getValue()).toBe('abcde');
+
+ keydown(root, { ctrlKey: true, key: 'z' });
+ await tick();
+ expect(screen.component.getValue()).toBe('abc');
+ });
+
+ it('keeps a newline as its own undo step', async () => {
+ const screen = render(ChatFormInputRichHarness, { value: 'abc' });
+
+ await tick();
+
+ const root = editableIn(screen.container);
+
+ type(root, 'd');
+ type(root, '\n', 'insertLineBreak');
+ await tick();
+ expect(screen.component.getValue()).toBe('abcd\n');
+
+ keydown(root, { ctrlKey: true, key: 'z' });
+ await tick();
+ expect(screen.component.getValue()).toBe('abcd');
+
+ keydown(root, { ctrlKey: true, key: 'z' });
+ await tick();
+ expect(screen.component.getValue()).toBe('abc');
+ });
+
+ it('is a no-op when there is nothing to undo', async () => {
+ const screen = render(ChatFormInputRichHarness, { value: 'abc' });
+
+ await tick();
+
+ const root = editableIn(screen.container);
+ const event = keydown(root, { ctrlKey: true, key: 'z' });
+
+ await tick();
+
+ expect(event.defaultPrevented).toBe(true);
+ expect(screen.component.getValue()).toBe('abc');
+ });
+
+ it('abandons the redo branch after a fresh edit', async () => {
+ const screen = render(ChatFormInputRichHarness, { value: 'abc' });
+
+ await tick();
+
+ const root = editableIn(screen.container);
+
+ type(root, 'd');
+ await tick();
+ keydown(root, { ctrlKey: true, key: 'z' });
+ await tick();
+ expect(screen.component.getValue()).toBe('abc');
+
+ type(root, 'e');
+ await tick();
+ keydown(root, { ctrlKey: true, key: 'z', shiftKey: true });
+ await tick();
+ expect(screen.component.getValue()).toBe('abce');
+ });
+});
+
+describe('ChatFormInputRich Tab key', () => {
+ it('does not trap Tab (focus can leave the editable)', async () => {
+ const screen = render(ChatFormInputRichHarness, { value: SOURCE });
+
+ await tick();
+
+ const root = editableIn(screen.container);
+ const event = keydown(root, { key: 'Tab' });
+
+ expect(event.defaultPrevented).toBe(false);
+ });
+});
diff --git a/tools/ui/tests/client/chat-form-input-rich.svelte.test.ts b/tools/ui/tests/client/chat-form-input-rich.svelte.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..d3403030d5cd9361fba0e6b1b07d8bdf7feca30c
--- /dev/null
+++ b/tools/ui/tests/client/chat-form-input-rich.svelte.test.ts
@@ -0,0 +1,804 @@
+// Guards the clipboard contract of the ChatFormInputRich:
+// copy/cut expose the markdown SOURCE of the selection (each badge
+// contributes its full `[name](file://...)` link) and pasting such
+// markdown re-renders the badges.
+
+import ChatFormInputRich from '$lib/components/app/chat/ChatForm/ChatFormInput/ChatFormInputRich.svelte';
+import { rangeToTextOffset, serializeContent, textOffsetToRange } from '$lib/utils';
+import { tick } from 'svelte';
+import { describe, expect, it, vi } from 'vitest';
+import { userEvent } from 'vitest/browser';
+import { render } from 'vitest-browser-svelte';
+
+const SOURCE = 'hello [docs](file:///a/b) world';
+const BADGE_SELECTOR = '[data-mention-badge="true"]';
+
+function editableIn(container: HTMLElement): HTMLElement {
+ const el = container.querySelector('[role="textbox"]');
+
+ if (!(el instanceof HTMLElement)) throw new Error('ChatFormInputRich not rendered');
+
+ return el;
+}
+
+function setSelection(root: HTMLElement, place: (range: Range, root: HTMLElement) => void) {
+ const range = document.createRange();
+
+ place(range, root);
+ const selection = window.getSelection();
+
+ if (!selection) throw new Error('no selection');
+
+ selection.removeAllRanges();
+ selection.addRange(range);
+}
+
+function clipboardEvent(type: 'copy' | 'cut' | 'paste', text = '') {
+ const data = new DataTransfer();
+
+ if (text) data.setData('text/plain', text);
+
+ const event = new ClipboardEvent(type, { bubbles: true, cancelable: true, clipboardData: data });
+
+ return { data, event };
+}
+
+describe('ChatFormInputRich clipboard', () => {
+ it('copy exposes the markdown source of the selection', async () => {
+ const { container } = render(ChatFormInputRich, { value: SOURCE });
+
+ await tick();
+
+ const root = editableIn(container);
+
+ setSelection(root, (range) => range.selectNodeContents(root));
+
+ const { data, event } = clipboardEvent('copy');
+
+ root.dispatchEvent(event);
+
+ expect(event.defaultPrevented).toBe(true);
+ expect(data.getData('text/plain')).toBe(SOURCE);
+ });
+
+ it('cut exposes the markdown source and removes the slice', async () => {
+ const { container } = render(ChatFormInputRich, { value: SOURCE });
+
+ await tick();
+
+ const root = editableIn(container);
+
+ setSelection(root, (range) => {
+ const badge = root.querySelector(BADGE_SELECTOR);
+
+ if (!badge) throw new Error('badge not rendered');
+
+ range.setStartBefore(badge);
+ range.setEndAfter(badge);
+ });
+
+ const { data, event } = clipboardEvent('cut');
+
+ root.dispatchEvent(event);
+
+ expect(event.defaultPrevented).toBe(true);
+ expect(data.getData('text/plain')).toBe('[docs](file:///a/b)');
+ expect(root.querySelector(BADGE_SELECTOR)).toBeNull();
+ expect(root.textContent).toBe('hello world');
+ });
+
+ it('paste of markdown mention links re-renders badges', async () => {
+ const { container } = render(ChatFormInputRich, { value: 'hello ' });
+
+ await tick();
+
+ const root = editableIn(container);
+
+ root.focus();
+ setSelection(root, (range) => {
+ range.selectNodeContents(root);
+ range.collapse(false);
+ });
+
+ const { event } = clipboardEvent('paste', '[docs](file:///a/b) world');
+
+ root.dispatchEvent(event);
+ await tick();
+
+ expect(event.defaultPrevented).toBe(true);
+ const badge = root.querySelector(BADGE_SELECTOR);
+
+ expect(badge).not.toBeNull();
+ expect(badge!.getAttribute('data-mention-name')).toBe('docs');
+ expect(root.textContent).toContain('world');
+ });
+
+ it('paste without mention links keeps the DOM untouched', async () => {
+ const { container } = render(ChatFormInputRich, { value: 'hello ' });
+
+ await tick();
+
+ const root = editableIn(container);
+
+ root.focus();
+ setSelection(root, (range) => {
+ range.selectNodeContents(root);
+ range.collapse(false);
+ });
+ const firstChild = root.firstChild;
+ const { event } = clipboardEvent('paste', 'plain text');
+
+ root.dispatchEvent(event);
+ await tick();
+
+ expect(event.defaultPrevented).toBe(true);
+ expect(root.querySelector(BADGE_SELECTOR)).toBeNull();
+ // no rebuild: the live text node is the same instance
+ expect(root.firstChild).toBe(firstChild);
+ });
+});
+
+describe('ChatFormInputRich code spans', () => {
+ it('renders inline code from the initial value', async () => {
+ const { container } = render(ChatFormInputRich, { value: 'run `npm test` now' });
+
+ await tick();
+
+ const root = editableIn(container);
+ const code = root.querySelector('code[data-code-token="code_inline"]');
+
+ expect(code).not.toBeNull();
+ expect(code!.textContent).toBe('`npm test`');
+ });
+
+ it('renders a fenced code block with a language', async () => {
+ const source = 'before\n```js\nconst a = 1;\n```\nafter';
+ const { container } = render(ChatFormInputRich, { value: source });
+
+ await tick();
+
+ const root = editableIn(container);
+ const code = root.querySelector('code[data-code-token="code_block"]');
+
+ expect(code).not.toBeNull();
+ expect(code!.textContent).toBe('```js\nconst a = 1;\n```');
+ });
+
+ it('copy exposes the markdown source of a selection spanning code', async () => {
+ const source = 'run `npm test` now';
+ const { container } = render(ChatFormInputRich, { value: source });
+
+ await tick();
+
+ const root = editableIn(container);
+
+ setSelection(root, (range) => range.selectNodeContents(root));
+
+ const { data, event } = clipboardEvent('copy');
+
+ root.dispatchEvent(event);
+
+ expect(event.defaultPrevented).toBe(true);
+ expect(data.getData('text/plain')).toBe(source);
+ });
+
+ it('paste of a code span renders the styled element', async () => {
+ const { container } = render(ChatFormInputRich, { value: 'run ' });
+
+ await tick();
+
+ const root = editableIn(container);
+
+ root.focus();
+ setSelection(root, (range) => {
+ range.selectNodeContents(root);
+ range.collapse(false);
+ });
+
+ const { event } = clipboardEvent('paste', '`npm test` now');
+
+ root.dispatchEvent(event);
+ await tick();
+
+ expect(event.defaultPrevented).toBe(true);
+ const code = root.querySelector('code[data-code-token="code_inline"]');
+
+ expect(code).not.toBeNull();
+ expect(code!.textContent).toBe('`npm test`');
+ expect(root.textContent).toContain('now');
+ });
+
+ it('highlights a fenced block content and stays byte-exact', async () => {
+ const source = '```js\nconst a = 1;\n```';
+ const { container } = render(ChatFormInputRich, { value: source });
+
+ await tick();
+
+ const root = editableIn(container);
+ const code = root.querySelector('code[data-code-token="code_block"]');
+
+ expect(code).not.toBeNull();
+ expect(code!.querySelector('.hljs-keyword')).not.toBeNull();
+ expect(code!.textContent).toBe(source);
+ });
+
+ it('does not highlight inline code', async () => {
+ const { container } = render(ChatFormInputRich, { value: 'run `const` now' });
+
+ await tick();
+
+ const root = editableIn(container);
+
+ expect(root.querySelector('[class*="hljs-"]')).toBeNull();
+ });
+});
+
+describe('ChatFormInputRich code block escape hatches', () => {
+ const BLOCK_SOURCE = '```js\nconst a = 1;\n```';
+ const BLOCK_SELECTOR = 'code[data-code-token="code_block"]';
+
+ function blockIn(root: HTMLElement): HTMLElement {
+ const el = root.querySelector(BLOCK_SELECTOR);
+
+ if (!(el instanceof HTMLElement)) throw new Error('code block not rendered');
+
+ return el;
+ }
+
+ // Caret at the very start/end of the block's text (across highlight spans)
+ function placeCaretInBlock(root: HTMLElement, where: 'start' | 'end') {
+ const code = blockIn(root);
+ const walker = document.createTreeWalker(code, NodeFilter.SHOW_TEXT);
+
+ let target: Node | null = null;
+
+ for (let n = walker.nextNode(); n; n = walker.nextNode()) {
+ target = where === 'start' ? (target ?? n) : n;
+ }
+
+ if (!target) throw new Error('no text inside code block');
+
+ setSelection(root, (range) => {
+ range.setStart(target!, where === 'start' ? 0 : (target!.textContent ?? '').length);
+ range.collapse(true);
+ });
+ }
+
+ function caretContainer(): Node {
+ const selection = window.getSelection();
+
+ if (!selection || selection.rangeCount === 0) throw new Error('no selection');
+
+ return selection.getRangeAt(0).startContainer;
+ }
+
+ it('pads a trailing code block with a br hatch that stays invisible to copy', async () => {
+ const { container } = render(ChatFormInputRich, { value: BLOCK_SOURCE });
+
+ await tick();
+
+ const root = editableIn(container);
+
+ // no permanent empty line above a leading block
+ expect(root.firstChild).toBe(blockIn(root));
+ expect(root.lastChild?.nodeName).toBe('BR');
+
+ setSelection(root, (range) => range.selectNodeContents(root));
+ const { data, event } = clipboardEvent('copy');
+
+ root.dispatchEvent(event);
+
+ expect(data.getData('text/plain')).toBe(BLOCK_SOURCE);
+ });
+
+ it('escapes a trailing code block with ArrowDown and types after it', async () => {
+ const { container } = render(ChatFormInputRich, { value: BLOCK_SOURCE });
+
+ await tick();
+
+ const root = editableIn(container);
+
+ root.focus();
+ placeCaretInBlock(root, 'end');
+
+ await userEvent.keyboard('{ArrowDown}');
+ expect(blockIn(root).contains(caretContainer())).toBe(false);
+
+ await userEvent.keyboard('x');
+ await tick();
+
+ expect(blockIn(root).textContent).toBe(BLOCK_SOURCE);
+ // the DOM holds no separator newline (it would render as a
+ // phantom empty line); serialization synthesizes it so the
+ // markdown source keeps the text below the block
+ expect(root.textContent).toBe(BLOCK_SOURCE + 'x');
+ expect(serializeContent(root)).toBe(BLOCK_SOURCE + '\nx');
+ // the stale trailing hatch is removed once real text follows the block
+ expect(root.lastChild?.nodeName).not.toBe('BR');
+ });
+
+ it('escapes a leading code block with ArrowUp and types before it', async () => {
+ const { container } = render(ChatFormInputRich, { value: BLOCK_SOURCE });
+
+ await tick();
+
+ const root = editableIn(container);
+
+ root.focus();
+ placeCaretInBlock(root, 'start');
+
+ await userEvent.keyboard('{ArrowUp}');
+ expect(blockIn(root).contains(caretContainer())).toBe(false);
+ // the transient hatch line exists while the caret sits on it
+ expect(root.firstChild?.nodeName).toBe('BR');
+
+ await userEvent.keyboard('y');
+ await tick();
+
+ expect(blockIn(root).textContent).toBe(BLOCK_SOURCE);
+ expect(root.textContent).toBe('y' + BLOCK_SOURCE);
+ expect(serializeContent(root)).toBe('y\n' + BLOCK_SOURCE);
+ // the typed text consumed the hatch
+ expect(root.firstChild?.nodeName).not.toBe('BR');
+ });
+
+ it('escapes a leading code block with ArrowLeft from its first character', async () => {
+ const { container } = render(ChatFormInputRich, { value: BLOCK_SOURCE });
+
+ await tick();
+
+ const root = editableIn(container);
+
+ root.focus();
+ placeCaretInBlock(root, 'start');
+
+ await userEvent.keyboard('{ArrowLeft}');
+ expect(blockIn(root).contains(caretContainer())).toBe(false);
+ expect(root.firstChild?.nodeName).toBe('BR');
+ });
+
+ it('removes the transient leading hatch when the caret moves back into the block', async () => {
+ const { container } = render(ChatFormInputRich, { value: BLOCK_SOURCE });
+
+ await tick();
+
+ const root = editableIn(container);
+
+ root.focus();
+ placeCaretInBlock(root, 'start');
+
+ await userEvent.keyboard('{ArrowUp}');
+ expect(root.firstChild?.nodeName).toBe('BR');
+
+ await userEvent.keyboard('{ArrowDown}');
+ await tick();
+
+ expect(blockIn(root).contains(caretContainer())).toBe(true);
+ expect(root.firstChild).toBe(blockIn(root));
+ });
+
+ it('extends the selection out of the block with Shift+ArrowDown', async () => {
+ const { container } = render(ChatFormInputRich, { value: BLOCK_SOURCE });
+
+ await tick();
+
+ const root = editableIn(container);
+
+ root.focus();
+ placeCaretInBlock(root, 'end');
+
+ await userEvent.keyboard('{Shift>}{ArrowDown}{/Shift}');
+
+ const selection = window.getSelection();
+
+ expect(selection).not.toBeNull();
+ expect(selection!.isCollapsed).toBe(false);
+ expect(blockIn(root).contains(selection!.getRangeAt(0).endContainer)).toBe(false);
+ });
+
+ it('line-separates text typed right after the closing fence', async () => {
+ const { container } = render(ChatFormInputRich, { value: BLOCK_SOURCE });
+
+ await tick();
+
+ const root = editableIn(container);
+
+ root.focus();
+ placeCaretInBlock(root, 'end');
+
+ // no arrow keys: the caret sits at the block's end edge, where the
+ // post-rebuild restore lands it, and the typed text renders on the
+ // line below the block
+ await userEvent.keyboard('x');
+ await tick();
+
+ // the text stays on the caret's line in the DOM (no phantom empty
+ // line); the source gets the separator newline
+ expect(root.textContent).toBe(BLOCK_SOURCE + 'x');
+ expect(serializeContent(root)).toBe(BLOCK_SOURCE + '\nx');
+ });
+
+ it('does not double the newline when Shift+Enter already added one', async () => {
+ const { container } = render(ChatFormInputRich, { value: BLOCK_SOURCE });
+
+ await tick();
+
+ const root = editableIn(container);
+
+ root.focus();
+ placeCaretInBlock(root, 'end');
+
+ await userEvent.keyboard('{Shift>}{Enter}{/Shift}');
+ await userEvent.keyboard('x');
+ await tick();
+
+ expect(root.textContent).toBe(BLOCK_SOURCE + 'x');
+ expect(serializeContent(root)).toBe(BLOCK_SOURCE + '\nx');
+ });
+
+ it('moves a caret stuck before the inserted newline onto the new line', async () => {
+ const { container } = render(ChatFormInputRich, {
+ value: BLOCK_SOURCE + '\ntext after the code block'
+ });
+
+ await tick();
+
+ const root = editableIn(container);
+
+ root.focus();
+
+ // post-break DOM some browsers produce: the inserted newline plus
+ // the artificial trailing one, with the caret stuck BEFORE the
+ // inserted one (visually at the end of the old line)
+ root.appendChild(document.createTextNode('\n'));
+ root.appendChild(document.createTextNode('\n'));
+ setSelection(root, (range) => {
+ range.setStart(root.childNodes[2], 0);
+ range.collapse(true);
+ });
+
+ root.dispatchEvent(new InputEvent('input', { bubbles: true, inputType: 'insertLineBreak' }));
+ await tick();
+
+ const selection = window.getSelection();
+
+ expect(rangeToTextOffset(root, selection!.getRangeAt(0))).toBe(
+ (BLOCK_SOURCE + '\ntext after the code block\n').length
+ );
+ expect(serializeContent(root)).toBe(BLOCK_SOURCE + '\ntext after the code block\n\n');
+ });
+
+ it('appends the artificial trailing newline when the browser did not add one', async () => {
+ const { container } = render(ChatFormInputRich, {
+ value: BLOCK_SOURCE + '\ntext after the code block'
+ });
+
+ await tick();
+
+ const root = editableIn(container);
+
+ root.focus();
+
+ // post-break DOM some browsers produce: a lone trailing \n (or a
+ //
the hatch sync strips). Collapsed by the renderer, so the
+ // caret looks stuck on the old line and the next typed character
+ // would consume the newline.
+ root.appendChild(document.createTextNode('\n'));
+ setSelection(root, (range) => {
+ range.setStart(root.childNodes[2], 1);
+ range.collapse(true);
+ });
+
+ root.dispatchEvent(new InputEvent('input', { bubbles: true, inputType: 'insertLineBreak' }));
+ await tick();
+
+ const selection = window.getSelection();
+
+ expect(rangeToTextOffset(root, selection!.getRangeAt(0))).toBe(
+ (BLOCK_SOURCE + '\ntext after the code block\n').length
+ );
+ expect(serializeContent(root)).toBe(BLOCK_SOURCE + '\ntext after the code block\n\n');
+ });
+
+ it('lands the caret on the new line with a single Shift+Enter after text below a block', async () => {
+ const { container } = render(ChatFormInputRich, {
+ value: BLOCK_SOURCE + '\ntext after the code block'
+ });
+
+ await tick();
+
+ const root = editableIn(container);
+
+ root.focus();
+ setSelection(root, (range) => {
+ const text = root.childNodes[1];
+
+ range.setStart(text, (text.textContent ?? '').length);
+ range.collapse(true);
+ });
+
+ await userEvent.keyboard('{Shift>}{Enter}{/Shift}');
+ await tick();
+
+ const selection = window.getSelection();
+
+ expect(rangeToTextOffset(root, selection!.getRangeAt(0))).toBe(
+ (BLOCK_SOURCE + '\ntext after the code block\n').length
+ );
+ expect(serializeContent(root)).toBe(BLOCK_SOURCE + '\ntext after the code block\n\n');
+
+ // the next typed character lands on the new line
+ await userEvent.keyboard('x');
+ await tick();
+ expect(serializeContent(root)).toBe(BLOCK_SOURCE + '\ntext after the code block\nx');
+ });
+
+ it('lets Backspace at the text start move into the block without a source fight', async () => {
+ const { container } = render(ChatFormInputRich, { value: BLOCK_SOURCE });
+
+ await tick();
+
+ const root = editableIn(container);
+
+ root.focus();
+ placeCaretInBlock(root, 'end');
+
+ await userEvent.keyboard('{ArrowDown}');
+ await userEvent.keyboard('create');
+ await tick();
+ expect(serializeContent(root)).toBe(BLOCK_SOURCE + '\ncreate');
+
+ // Backspace at the start of the text line: the separator newline
+ // is structural (synthesized while text follows the block), so
+ // the caret just moves to the block's edge - nothing is re-added
+ await userEvent.keyboard('{Home}');
+ await userEvent.keyboard('{Backspace}');
+ await tick();
+
+ expect(serializeContent(root)).toBe(BLOCK_SOURCE + '\ncreate');
+ expect(caretContainer()).toBe(root);
+ });
+
+ it('lets forward Delete eat the text after a block normally', async () => {
+ const { container } = render(ChatFormInputRich, { value: BLOCK_SOURCE });
+
+ await tick();
+
+ const root = editableIn(container);
+
+ root.focus();
+ placeCaretInBlock(root, 'end');
+
+ await userEvent.keyboard('{ArrowDown}');
+ await userEvent.keyboard('create');
+ await tick();
+
+ await userEvent.keyboard('{Home}');
+ await userEvent.keyboard('{Delete}');
+ await tick();
+
+ expect(serializeContent(root)).toBe(BLOCK_SOURCE + '\nreate');
+ });
+
+ it('renders text after a block without a phantom empty line', async () => {
+ const { container } = render(ChatFormInputRich, {
+ value: BLOCK_SOURCE + '\nhello'
+ });
+
+ await tick();
+
+ const root = editableIn(container);
+
+ expect(root.textContent).toBe(BLOCK_SOURCE + 'hello');
+ expect(serializeContent(root)).toBe(BLOCK_SOURCE + '\nhello');
+ });
+
+ it('keeps an intentional blank line after a block out of the separator', async () => {
+ const { container } = render(ChatFormInputRich, {
+ value: BLOCK_SOURCE + '\n\nhello'
+ });
+
+ await tick();
+
+ const root = editableIn(container);
+
+ expect(root.textContent).toBe(BLOCK_SOURCE + '\nhello');
+ expect(serializeContent(root)).toBe(BLOCK_SOURCE + '\n\nhello');
+ });
+
+ it('re-highlights while typing inside a block and keeps the caret', async () => {
+ const { container } = render(ChatFormInputRich, { value: BLOCK_SOURCE });
+
+ await tick();
+
+ const root = editableIn(container);
+
+ root.focus();
+
+ // caret at the start of the block content (after the opening fence)
+ setSelection(root, (range) => {
+ const target = textOffsetToRange(root, 6);
+
+ range.setStart(target.startContainer, target.startOffset);
+ range.collapse(true);
+ });
+
+ await userEvent.keyboard('x');
+ await tick();
+
+ const code = blockIn(root);
+
+ expect(serializeContent(root)).toBe('```js\nxconst a = 1;\n```');
+ expect(code.textContent).toBe('```js\nxconst a = 1;\n```');
+ expect(code.querySelector('.hljs-number')).not.toBeNull();
+
+ const selection = window.getSelection();
+
+ expect(code.contains(selection!.getRangeAt(0).startContainer)).toBe(true);
+ expect(rangeToTextOffset(root, selection!.getRangeAt(0))).toBe(7);
+ });
+});
+
+describe('ChatFormInputRich Enter in code blocks', () => {
+ const BLOCK_SOURCE = '```js\nconst a = 1;\n```';
+
+ it('adds a line instead of submitting on plain Enter inside a block', async () => {
+ const onKeydown = vi.fn();
+ const { container } = render(ChatFormInputRich, {
+ onKeydown,
+ value: BLOCK_SOURCE
+ });
+
+ await tick();
+
+ const root = editableIn(container);
+
+ root.focus();
+
+ // caret at the start of the block content (after the opening fence)
+ setSelection(root, (range) => {
+ const target = textOffsetToRange(root, 6);
+
+ range.setStart(target.startContainer, target.startOffset);
+ range.collapse(true);
+ });
+
+ await userEvent.keyboard('{Enter}');
+ await tick();
+
+ // consumed locally: the parent's submit handler never sees it
+ expect(onKeydown).not.toHaveBeenCalled();
+ expect(serializeContent(root)).toBe('```js\n\nconst a = 1;\n```');
+
+ const code = root.querySelector('code[data-code-token="code_block"]');
+ const selection = window.getSelection();
+
+ expect(code!.contains(selection!.getRangeAt(0).startContainer)).toBe(true);
+ expect(rangeToTextOffset(root, selection!.getRangeAt(0))).toBe(7);
+ });
+
+ it('adds a line after a still-open fence (no closing ``` yet)', async () => {
+ const onKeydown = vi.fn();
+ const { container } = render(ChatFormInputRich, {
+ onKeydown,
+ value: '```js\nconst a = 1;'
+ });
+
+ await tick();
+
+ const root = editableIn(container);
+
+ root.focus();
+
+ // caret at the start of the block content (after the opening fence)
+ setSelection(root, (range) => {
+ const target = textOffsetToRange(root, 6);
+
+ range.setStart(target.startContainer, target.startOffset);
+ range.collapse(true);
+ });
+
+ await userEvent.keyboard('{Enter}');
+ await tick();
+
+ expect(onKeydown).not.toHaveBeenCalled();
+ expect(serializeContent(root)).toBe('```js\n\nconst a = 1;');
+ });
+
+ it('forwards plain Enter to the parent when the caret is outside a block', async () => {
+ const onKeydown = vi.fn();
+ const { container } = render(ChatFormInputRich, {
+ onKeydown,
+ value: BLOCK_SOURCE + '\nafter'
+ });
+
+ await tick();
+
+ const root = editableIn(container);
+
+ root.focus();
+ setSelection(root, (range) => {
+ range.selectNodeContents(root);
+ range.collapse(false);
+ });
+
+ await userEvent.keyboard('{Enter}');
+
+ expect(onKeydown).toHaveBeenCalledTimes(1);
+ expect(onKeydown.mock.calls[0][0].defaultPrevented).toBe(false);
+ });
+
+ it('forwards plain Enter on the trailing hatch line after a block', async () => {
+ const onKeydown = vi.fn();
+ const { container } = render(ChatFormInputRich, {
+ onKeydown,
+ value: BLOCK_SOURCE
+ });
+
+ await tick();
+
+ const root = editableIn(container);
+
+ root.focus();
+ // root-level caret between the block and its trailing br hatch
+ setSelection(root, (range) => {
+ range.setStart(root, 1);
+ range.collapse(true);
+ });
+
+ await userEvent.keyboard('{Enter}');
+
+ expect(onKeydown).toHaveBeenCalledTimes(1);
+ });
+
+ it('forwards Ctrl+Enter inside a block so explicit submit survives', async () => {
+ const onKeydown = vi.fn();
+ const { container } = render(ChatFormInputRich, {
+ onKeydown,
+ value: BLOCK_SOURCE
+ });
+
+ await tick();
+
+ const root = editableIn(container);
+
+ root.focus();
+ setSelection(root, (range) => {
+ const target = textOffsetToRange(root, 6);
+
+ range.setStart(target.startContainer, target.startOffset);
+ range.collapse(true);
+ });
+
+ await userEvent.keyboard('{Control>}{Enter}{/Control}');
+
+ expect(onKeydown).toHaveBeenCalledWith(
+ expect.objectContaining({ ctrlKey: true, key: 'Enter' })
+ );
+ expect(serializeContent(root)).toBe(BLOCK_SOURCE);
+ });
+
+ it('forwards Enter inside an inline code span', async () => {
+ const onKeydown = vi.fn();
+ const { container } = render(ChatFormInputRich, {
+ onKeydown,
+ value: 'run `npm test` now'
+ });
+
+ await tick();
+
+ const root = editableIn(container);
+
+ root.focus();
+ const code = root.querySelector('code[data-code-token="code_inline"]')!;
+
+ setSelection(root, (range) => {
+ range.setStart(code.firstChild!, 3);
+ range.collapse(true);
+ });
+
+ await userEvent.keyboard('{Enter}');
+
+ expect(onKeydown).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/tools/ui/tests/client/chat-form-mention-picker-gate.svelte.test.ts b/tools/ui/tests/client/chat-form-mention-picker-gate.svelte.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..cbf3747cccc1968248bae0bf5a9cab50f1562dd9
--- /dev/null
+++ b/tools/ui/tests/client/chat-form-mention-picker-gate.svelte.test.ts
@@ -0,0 +1,63 @@
+// Guards the @-mention picker's file_glob_search gate: when the server
+// does not expose the tool (started without --tools) or the user disabled
+// it, the picker still opens but explains why instead of firing searches
+// that would only fail with "Search failed".
+
+import ChatFormPickerMention from '$lib/components/app/chat/ChatForm/ChatFormPickers/ChatFormPickerMention.svelte';
+import { DISABLED_TOOL_KEYS_LOCALSTORAGE_KEY } from '$lib/constants';
+import { BuiltInTool } from '$lib/enums';
+import { toolsStore } from '$lib/stores/tools.svelte';
+import type { OpenAIToolDefinition } from '$lib/types';
+import { tick } from 'svelte';
+import { afterEach, describe, expect, it } from 'vitest';
+import { render } from 'vitest-browser-svelte';
+
+const FILE_SEARCH_DEF: OpenAIToolDefinition = {
+ function: { description: '', name: BuiltInTool.SERVER_FILE_GLOB_SEARCH, parameters: {} },
+ type: 'function'
+};
+const FILE_SEARCH_KEY = `server:${BuiltInTool.SERVER_FILE_GLOB_SEARCH}`;
+
+// The store keeps its server tool list private; tests inject it through
+// the reactive field so the derived gates recompute.
+function setServerTools(defs: OpenAIToolDefinition[]) {
+ (toolsStore as unknown as { _serverTools: OpenAIToolDefinition[] })._serverTools = defs;
+}
+
+function renderPicker() {
+ return render(ChatFormPickerMention, {
+ isOpen: true,
+ onClose: () => {},
+ onSelect: () => {},
+ query: 'main'
+ });
+}
+
+afterEach(() => {
+ setServerTools([]);
+ toolsStore.setToolEnabled(FILE_SEARCH_KEY, true);
+ localStorage.removeItem(DISABLED_TOOL_KEYS_LOCALSTORAGE_KEY);
+});
+
+describe('ChatFormPickerMention file_glob_search gate', () => {
+ it('explains that file search is unavailable when the server has no tools', async () => {
+ setServerTools([]);
+ renderPicker();
+ await tick();
+
+ expect(document.body.textContent).toContain(
+ 'File search is unavailable on this server (started without --tools)'
+ );
+ });
+
+ it('explains that file search must be enabled when the user disabled it', async () => {
+ setServerTools([FILE_SEARCH_DEF]);
+ toolsStore.setToolEnabled(FILE_SEARCH_KEY, false);
+ renderPicker();
+ await tick();
+
+ expect(document.body.textContent).toContain(
+ 'File search is disabled - enable "Search files" in Settings > Tools to use @-mentions'
+ );
+ });
+});
diff --git a/tools/ui/tests/client/chat-form-slash-commands.svelte.test.ts b/tools/ui/tests/client/chat-form-slash-commands.svelte.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..d053f7f60cff3c0254ed2c338308c383cc838802
--- /dev/null
+++ b/tools/ui/tests/client/chat-form-slash-commands.svelte.test.ts
@@ -0,0 +1,139 @@
+// Guards the slash-command dispatch contract: commands dispatch only on
+// explicit selection (Enter/click in the picker), never mid-typing.
+// Typing `/model is broken` is prose until the command is picked - the
+// buffer must survive; only an actual selection consumes the token.
+
+import ChatFormPickersHarness from './components/ChatFormPickersHarness.svelte';
+import { tick } from 'svelte';
+import { describe, expect, it } from 'vitest';
+import { render } from 'vitest-browser-svelte';
+
+describe('slash command dispatch', () => {
+ it('does not dispatch or clear the buffer when a space follows the name', async () => {
+ const screen = render(ChatFormPickersHarness);
+
+ await tick();
+
+ screen.component.type('/model is broken');
+ await tick();
+
+ const pickers = screen.component.getPickers();
+
+ expect(screen.component.getValue()).toBe('/model is broken');
+ expect(screen.component.getCalls()).not.toContain('openModelSelector');
+ expect(screen.component.getCalls().some((c) => c.startsWith('setValue:'))).toBe(false);
+ expect(pickers.isCommandPickerOpen).toBe(true);
+ expect(pickers.commandQuery).toBe('model');
+ });
+
+ it('dispatches /model on explicit selection and consumes the token', async () => {
+ const screen = render(ChatFormPickersHarness);
+
+ await tick();
+
+ screen.component.type('/model is broken');
+ await tick();
+
+ const pickers = screen.component.getPickers();
+ const model = pickers.availableCommands.find((c) => c.name === 'model');
+
+ if (!model) throw new Error('model command missing');
+
+ pickers.handleCommandSelect(model);
+ await tick();
+
+ expect(screen.component.getValue()).toBe('');
+ expect(screen.component.getCalls()).toContain('openModelSelector');
+ expect(pickers.isCommandPickerOpen).toBe(false);
+ });
+
+ it('seeds the prompt picker search from the token args on selection', async () => {
+ const screen = render(ChatFormPickersHarness);
+
+ await tick();
+
+ screen.component.type('/prompt weather');
+ await tick();
+
+ const pickers = screen.component.getPickers();
+
+ expect(pickers.isPromptPickerOpen).toBe(false);
+
+ const prompt = pickers.availableCommands.find((c) => c.name === 'prompt');
+
+ if (!prompt) throw new Error('prompt command missing');
+
+ pickers.handleCommandSelect(prompt);
+ await tick();
+
+ expect(screen.component.getValue()).toBe('');
+ expect(pickers.isPromptPickerOpen).toBe(true);
+ expect(pickers.promptSearchQuery).toBe('weather');
+ });
+
+ it('normalizes a partial /cwd token on selection and keeps it in the buffer', async () => {
+ const screen = render(ChatFormPickersHarness);
+
+ await tick();
+
+ screen.component.type('/cw docs');
+ await tick();
+
+ const pickers = screen.component.getPickers();
+
+ expect(pickers.isWorkingDirectoryPickerOpen).toBe(false);
+
+ const cwd = pickers.availableCommands.find((c) => c.name === 'cwd');
+
+ if (!cwd) throw new Error('cwd command missing');
+
+ pickers.handleCommandSelect(cwd);
+ await tick();
+
+ expect(pickers.isWorkingDirectoryPickerOpen).toBe(true);
+ expect(pickers.workingDirectoryQuery).toBe('docs');
+ expect(screen.component.getValue()).toBe('/cwd docs');
+ });
+
+ it('syncs the /cwd token into the picker search while the picker is open', async () => {
+ const screen = render(ChatFormPickersHarness);
+
+ await tick();
+
+ const pickers = screen.component.getPickers();
+ const cwd = pickers.availableCommands.find((c) => c.name === 'cwd');
+
+ if (!cwd) throw new Error('cwd command missing');
+
+ screen.component.type('/cwd docs');
+ pickers.handleCommandSelect(cwd);
+ await tick();
+
+ screen.component.type('/cwd docs/sub');
+ await tick();
+
+ expect(pickers.isWorkingDirectoryPickerOpen).toBe(true);
+ expect(pickers.workingDirectoryQuery).toBe('docs/sub');
+ expect(pickers.isCommandPickerOpen).toBe(false);
+ });
+
+ it('abandons the /cwd picker when the token is edited away from /cwd', async () => {
+ const screen = render(ChatFormPickersHarness);
+
+ await tick();
+
+ const pickers = screen.component.getPickers();
+ const cwd = pickers.availableCommands.find((c) => c.name === 'cwd');
+
+ if (!cwd) throw new Error('cwd command missing');
+
+ screen.component.type('/cwd docs');
+ pickers.handleCommandSelect(cwd);
+ await tick();
+
+ screen.component.type('/cwdd docs');
+ await tick();
+
+ expect(pickers.isWorkingDirectoryPickerOpen).toBe(false);
+ });
+});
diff --git a/tools/ui/tests/client/collapsible-lazy-body.svelte.test.ts b/tools/ui/tests/client/collapsible-lazy-body.svelte.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..c82210176a1d22e03ea2e1cb4d4de581c35f58fc
--- /dev/null
+++ b/tools/ui/tests/client/collapsible-lazy-body.svelte.test.ts
@@ -0,0 +1,38 @@
+// Guards the lazy-body behaviour of the shared collapsible wrappers.
+//
+// bits-ui's Collapsible.Content renders its children unconditionally and only
+// sets `hidden`, so before this was gated a collapsed tool result kept its whole
+// body in the DOM and re-rendered it on every streamed token (measured at
+// ~41ms/section/token for a 200KB result). These tests pin the fix: closed means
+// not rendered, and opening still mounts the body.
+
+import CollapsibleLazyBodyHarness from './components/CollapsibleLazyBodyHarness.svelte';
+import { tick } from 'svelte';
+import { describe, expect, it } from 'vitest';
+import { render } from 'vitest-browser-svelte';
+
+const MARKER = 'collapsible-body-marker';
+
+describe('collapsible wrappers render their body lazily', () => {
+ for (const variant of ['content', 'terminal'] as const) {
+ it(`${variant}: body is absent while closed and present once open`, async () => {
+ const screen = render(CollapsibleLazyBodyHarness, { open: false, variant });
+
+ await tick();
+
+ expect(document.body.textContent).not.toContain(MARKER);
+
+ await screen.rerender({ open: true, variant });
+ await tick();
+
+ expect(document.body.textContent).toContain(MARKER);
+
+ // And it unmounts again on close, so a collapsed block stops costing
+ // anything during streaming.
+ await screen.rerender({ open: false, variant });
+ await tick();
+
+ expect(document.body.textContent).not.toContain(MARKER);
+ });
+ }
+});
diff --git a/tools/ui/tests/client/components/AgenticPerfWrapper.svelte b/tools/ui/tests/client/components/AgenticPerfWrapper.svelte
new file mode 100644
index 0000000000000000000000000000000000000000..822fd17ce094e0e614163e827962227265a54dee
--- /dev/null
+++ b/tools/ui/tests/client/components/AgenticPerfWrapper.svelte
@@ -0,0 +1,16 @@
+
+
+
+ {#if perfState.message}
+
+ {/if}
+
diff --git a/tools/ui/tests/client/components/ChatFormInputRichHarness.svelte b/tools/ui/tests/client/components/ChatFormInputRichHarness.svelte
new file mode 100644
index 0000000000000000000000000000000000000000..58768a1e88a32cda18048b3d5c060efb6cabd496
--- /dev/null
+++ b/tools/ui/tests/client/components/ChatFormInputRichHarness.svelte
@@ -0,0 +1,27 @@
+
+
+
diff --git a/tools/ui/tests/client/components/ChatFormPickersHarness.svelte b/tools/ui/tests/client/components/ChatFormPickersHarness.svelte
new file mode 100644
index 0000000000000000000000000000000000000000..e8ef6465b9db0b3b4ada84de91d9d59accc3378b
--- /dev/null
+++ b/tools/ui/tests/client/components/ChatFormPickersHarness.svelte
@@ -0,0 +1,51 @@
+
diff --git a/tools/ui/tests/client/components/ChatFormTestWrapper.svelte b/tools/ui/tests/client/components/ChatFormTestWrapper.svelte
new file mode 100644
index 0000000000000000000000000000000000000000..7ec8bf7f8b6e5e4fca3f057c485816b1e0218393
--- /dev/null
+++ b/tools/ui/tests/client/components/ChatFormTestWrapper.svelte
@@ -0,0 +1,12 @@
+
+
+
+
+
diff --git a/tools/ui/tests/client/components/ChatMessagesPerfWrapper.svelte b/tools/ui/tests/client/components/ChatMessagesPerfWrapper.svelte
new file mode 100644
index 0000000000000000000000000000000000000000..ab5cc38bc96cb574d7698879e2382a6bf820d6f3
--- /dev/null
+++ b/tools/ui/tests/client/components/ChatMessagesPerfWrapper.svelte
@@ -0,0 +1,12 @@
+
+
+
+
+
diff --git a/tools/ui/tests/client/components/CollapsibleLazyBodyHarness.svelte b/tools/ui/tests/client/components/CollapsibleLazyBodyHarness.svelte
new file mode 100644
index 0000000000000000000000000000000000000000..b11ea0f100f071b2e921a6ac3dad6e049f6c862d
--- /dev/null
+++ b/tools/ui/tests/client/components/CollapsibleLazyBodyHarness.svelte
@@ -0,0 +1,21 @@
+
+
+{#if variant === 'content'}
+
+ collapsible-body-marker
+
+{:else}
+
+ collapsible-body-marker
+
+{/if}
diff --git a/tools/ui/tests/client/components/McpServerFormWrapper.svelte b/tools/ui/tests/client/components/McpServerFormWrapper.svelte
new file mode 100644
index 0000000000000000000000000000000000000000..07479534be34cba0c85423dbacc3e797721db1c1
--- /dev/null
+++ b/tools/ui/tests/client/components/McpServerFormWrapper.svelte
@@ -0,0 +1,37 @@
+
+
+
+
{
+ headersState = value;
+ }}
+ onUrlChange={() => {}}
+ url="https://example.test/mcp"
+/>
+
+
diff --git a/tools/ui/tests/client/components/PickerListScrollHarness.svelte b/tools/ui/tests/client/components/PickerListScrollHarness.svelte
new file mode 100644
index 0000000000000000000000000000000000000000..16a8f00b4f0d7d9fbe0d8f9070f734ec12f35856
--- /dev/null
+++ b/tools/ui/tests/client/components/PickerListScrollHarness.svelte
@@ -0,0 +1,43 @@
+
+
+conversation
+
+{#if open}
+
+ it.id}
+ {items}
+ {scrollTrigger}
+ searchQuery=""
+ {selectedIndex}
+ showSearchInput={false}
+ >
+ {#snippet item(it, index, isSelected)}
+ {}}>
+ {it.label}
+
+ {/snippet}
+
+
+{/if}
diff --git a/tools/ui/tests/client/components/TestWrapper.svelte b/tools/ui/tests/client/components/TestWrapper.svelte
new file mode 100644
index 0000000000000000000000000000000000000000..3c874276adfedca4ffddf33b38ab86e755701d3e
--- /dev/null
+++ b/tools/ui/tests/client/components/TestWrapper.svelte
@@ -0,0 +1,12 @@
+
+
+
+
+
+
diff --git a/tools/ui/tests/client/components/agentic-perf-state.svelte.ts b/tools/ui/tests/client/components/agentic-perf-state.svelte.ts
new file mode 100644
index 0000000000000000000000000000000000000000..abf989da27420462b1840ace6eb877c00cf45f0c
--- /dev/null
+++ b/tools/ui/tests/client/components/agentic-perf-state.svelte.ts
@@ -0,0 +1,17 @@
+// Shared reactive fixture state for the Tier 1 perf harness.
+//
+// The wrapper component reads this module directly rather than taking props,
+// so the driver can mutate it without depending on how the test renderer
+// forwards props.
+
+import type { DatabaseMessage } from '$lib/types';
+
+export const perfState = $state<{
+ message: DatabaseMessage | null;
+ toolMessages: DatabaseMessage[];
+ isStreaming: boolean;
+}>({
+ isStreaming: true,
+ message: null,
+ toolMessages: []
+});
diff --git a/tools/ui/tests/client/conversation-import-db.svelte.test.ts b/tools/ui/tests/client/conversation-import-db.svelte.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..de331f1314f780db013d83c7d0ca363b0d3a7d38
--- /dev/null
+++ b/tools/ui/tests/client/conversation-import-db.svelte.test.ts
@@ -0,0 +1,69 @@
+import { MessageRole, MessageType } from '$lib/enums';
+import { DatabaseService } from '$lib/services/database.service';
+import type { ExportedConversation } from '$lib/types/database';
+import { afterEach, describe, expect, it } from 'vitest';
+
+function makeSession(id: string): ExportedConversation {
+ return {
+ conv: { currNode: `${id}-msg`, id, lastModified: 0, name: `Chat ${id}` },
+ messages: [
+ {
+ children: [],
+ content: `hello from ${id}`,
+ convId: id,
+ id: `${id}-msg`,
+ parent: null,
+ role: MessageRole.USER,
+ timestamp: 0,
+ type: MessageType.TEXT
+ }
+ ]
+ } as unknown as ExportedConversation;
+}
+
+afterEach(async () => {
+ const conversations = await DatabaseService.getAllConversations();
+
+ await DatabaseService.bulkDeleteConversations(conversations.map((conv) => conv.id));
+});
+
+/**
+ * An import leaves a conversation already in the database untouched, so the
+ * caller needs to know what was written to report it instead of echoing the
+ * selection back at the user.
+ */
+describe('DatabaseService.importConversations', () => {
+ it('reports the conversations it wrote', async () => {
+ const { imported, skipped } = await DatabaseService.importConversations([
+ makeSession('a'),
+ makeSession('b')
+ ]);
+
+ expect(imported.map((conv) => conv.id)).toEqual(['a', 'b']);
+ expect(skipped).toEqual([]);
+ expect(await DatabaseService.getConversationMessages('a')).toHaveLength(1);
+ });
+
+ it('reports an existing conversation as skipped and leaves it untouched', async () => {
+ await DatabaseService.importConversations([makeSession('a')]);
+ await DatabaseService.updateConversation('a', { name: 'Renamed locally' });
+
+ const { imported, skipped } = await DatabaseService.importConversations([makeSession('a')]);
+
+ expect(imported).toEqual([]);
+ expect(skipped.map((conv) => conv.id)).toEqual(['a']);
+ expect((await DatabaseService.getConversation('a'))?.name).toBe('Renamed locally');
+ });
+
+ it('imports the new conversations of a partially known selection', async () => {
+ await DatabaseService.importConversations([makeSession('a')]);
+
+ const { imported, skipped } = await DatabaseService.importConversations([
+ makeSession('a'),
+ makeSession('b')
+ ]);
+
+ expect(imported.map((conv) => conv.id)).toEqual(['b']);
+ expect(skipped.map((conv) => conv.id)).toEqual(['a']);
+ });
+});
diff --git a/tools/ui/tests/client/mcp-display-name.svelte.test.ts b/tools/ui/tests/client/mcp-display-name.svelte.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..7db0ffd42e5ae60a73bd2e7786e66bb71263724c
--- /dev/null
+++ b/tools/ui/tests/client/mcp-display-name.svelte.test.ts
@@ -0,0 +1,78 @@
+import { McpServerForm } from '$lib/components/app/mcp';
+import { mcpStore } from '$lib/stores/mcp/index.svelte';
+import { settingsStore } from '$lib/stores/settings/index.svelte';
+import { beforeEach, describe, expect, it } from 'vitest';
+import { render } from 'vitest-browser-svelte';
+
+describe('mcp server display name', () => {
+ beforeEach(() => {
+ settingsStore.updateConfig('mcpServers', '[]');
+ });
+
+ it('custom display name wins over the url fallback', () => {
+ const server = mcpStore.addServer({
+ displayName: 'My Tools',
+ enabled: false,
+ url: 'https://mcp.example.com/a'
+ });
+
+ expect(mcpStore.getServerLabel(server)).toBe('My Tools');
+ });
+
+ it('without a custom name the url is the label', () => {
+ const server = mcpStore.addServer({ enabled: false, url: 'https://mcp.example.com/a' });
+
+ expect(mcpStore.getServerLabel(server)).toBe('https://mcp.example.com/a');
+ });
+
+ it('identical labels get positional suffixes', () => {
+ const a = mcpStore.addServer({
+ displayName: 'GitHub',
+ enabled: false,
+ url: 'https://mcp.example.com/a'
+ });
+ const b = mcpStore.addServer({
+ displayName: 'GitHub',
+ enabled: false,
+ url: 'https://mcp.example.com/b'
+ });
+
+ expect(mcpStore.getServerLabel(a)).toBe('GitHub (1)');
+ expect(mcpStore.getServerLabel(b)).toBe('GitHub (2)');
+ });
+
+ it('renaming one twin dissolves the suffixes', () => {
+ const a = mcpStore.addServer({
+ displayName: 'GitHub',
+ enabled: false,
+ url: 'https://mcp.example.com/a'
+ });
+ const b = mcpStore.addServer({
+ displayName: 'GitHub',
+ enabled: false,
+ url: 'https://mcp.example.com/b'
+ });
+
+ mcpStore.updateServer(b.id, { displayName: 'GitHub Work' });
+ expect(mcpStore.getServerLabel(a)).toBe('GitHub');
+ expect(mcpStore.getServerLabel(mcpStore.getServerById(b.id)!)).toBe('GitHub Work');
+ });
+
+ it('the form exposes an editable display name field', async () => {
+ let captured = '';
+
+ const screen = await render(McpServerForm, {
+ headers: '',
+ name: '',
+ onHeadersChange: () => {},
+ onNameChange: (v: string) => (captured = v),
+ onUrlChange: () => {},
+ url: 'https://mcp.example.com/a'
+ });
+ const input = screen.getByLabelText('Display name');
+
+ await expect.element(input).toBeVisible();
+ await input.fill('My Custom Server');
+ expect(captured).toBe('My Custom Server');
+ });
+});
diff --git a/tools/ui/tests/client/mcp-server-form.svelte.test.ts b/tools/ui/tests/client/mcp-server-form.svelte.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..99b7a1354a90d3b3ceac0ec5bf9517084bbb691e
--- /dev/null
+++ b/tools/ui/tests/client/mcp-server-form.svelte.test.ts
@@ -0,0 +1,134 @@
+import McpServerFormWrapper from './components/McpServerFormWrapper.svelte';
+import { describe, expect, it } from 'vitest';
+import { render } from 'vitest-browser-svelte';
+
+const AUTHORIZATION_HEADER = 'Authorization';
+const BEARER_PREFIX = 'Bearer ';
+const BEARER_PLACEHOLDER = 'Paste token here';
+
+/**
+ * Client-side tests for the McpServerForm bearer UI.
+ *
+ * The dedicated UI only "owns" Authorization headers that already carry a
+ * Bearer scheme (heuristic check on the value). Other Authorization values
+ * stay in the KV section so the user can still edit them verbatim. Storage
+ * always goes through the same custom-headers slot, so a round-trip via this
+ * UI produces exactly one `Authorization: Bearer ` entry.
+ *
+ * Equivalent parser coverage lives in `tests/unit/headers.test.ts`.
+ */
+describe('McpServerForm - Authorization / bearer UI', () => {
+ function bearerInput(screen: Awaited>) {
+ return screen.locator.getByPlaceholder(BEARER_PLACEHOLDER);
+ }
+
+ function capturedHeaders(screen: Awaited>) {
+ return screen.getByTestId('captured-headers');
+ }
+
+ it('mounts with the bearer input hidden when no auth header is present', async () => {
+ const screen = await render(McpServerFormWrapper, { headers: '' });
+
+ await expect.element(screen.getByRole('textbox', { name: /server url/i })).toBeVisible();
+
+ await expect.element(bearerInput(screen)).not.toBeInTheDocument();
+ });
+
+ it('toggling Authorization shows the bearer input', async () => {
+ const screen = await render(McpServerFormWrapper, { headers: '' });
+
+ await screen.getByRole('switch', { name: /authorization/i }).click();
+
+ await expect.element(bearerInput(screen)).toBeVisible();
+ });
+
+ it('typing a token writes the Authorization row with the Bearer prefix prepended', async () => {
+ const screen = await render(McpServerFormWrapper, { headers: '' });
+
+ await screen.getByRole('switch', { name: /authorization/i }).click();
+
+ const token = 'super-secret';
+
+ await bearerInput(screen).fill(token);
+
+ const expected = JSON.stringify({ [AUTHORIZATION_HEADER]: `${BEARER_PREFIX}${token}` });
+
+ await expect
+ .element(capturedHeaders(screen))
+ .toHaveAttribute('data-captured-headers', expected);
+ });
+
+ it('pre-existing Bearer header pre-fills the bearer input with the token stripped', async () => {
+ const existing = JSON.stringify({
+ [AUTHORIZATION_HEADER]: `${BEARER_PREFIX}preexisting`,
+ 'X-Trace-Id': 'abc'
+ });
+ const screen = await render(McpServerFormWrapper, { headers: existing });
+
+ await expect.element(bearerInput(screen)).toBeVisible();
+ await expect.element(bearerInput(screen)).toHaveValue('preexisting');
+ });
+
+ it('non-Bearer Authorization is ignored by the dedicated UI and stays in the KV section', async () => {
+ const existing = JSON.stringify({ [AUTHORIZATION_HEADER]: 'Basic czNjcjpwYXNz' });
+ const screen = await render(McpServerFormWrapper, { headers: existing });
+
+ await expect.element(bearerInput(screen)).not.toBeInTheDocument();
+
+ const headerKeyInput = screen.getByPlaceholder('Header name');
+
+ await expect.element(headerKeyInput).toBeVisible();
+ });
+
+ it('engaging the token UI replaces a non-Bearer Authorization with the Bearer scheme', async () => {
+ const existing = JSON.stringify({ [AUTHORIZATION_HEADER]: 'Basic old' });
+ const screen = await render(McpServerFormWrapper, { headers: existing });
+
+ await screen.getByRole('switch', { name: /authorization/i }).click();
+ await bearerInput(screen).fill('new');
+
+ const expected = JSON.stringify({ [AUTHORIZATION_HEADER]: `${BEARER_PREFIX}new` });
+
+ await expect
+ .element(capturedHeaders(screen))
+ .toHaveAttribute('data-captured-headers', expected);
+ });
+
+ it('toggling Authorization off with no token drops the Bearer row but keeps non-Bearer schemes', async () => {
+ const existing = JSON.stringify({ [AUTHORIZATION_HEADER]: `${BEARER_PREFIX}xyz` });
+ const screen = await render(McpServerFormWrapper, { headers: existing });
+
+ await screen.getByRole('switch', { name: /authorization/i }).click();
+
+ await expect.element(capturedHeaders(screen)).toHaveAttribute('data-captured-headers', '');
+ });
+
+ it('toggling Authorization off when no Bearer row is present leaves headers untouched', async () => {
+ const existing = JSON.stringify({ [AUTHORIZATION_HEADER]: 'Basic czNjcjpwYXNz' });
+ const screen = await render(McpServerFormWrapper, { headers: existing });
+
+ await screen.getByRole('switch', { name: /authorization/i }).click();
+ await screen.getByRole('switch', { name: /authorization/i }).click();
+
+ await expect
+ .element(capturedHeaders(screen))
+ .toHaveAttribute('data-captured-headers', existing);
+ });
+
+ it('clearing the bearer input drops the Authorization row', async () => {
+ const existing = JSON.stringify({ [AUTHORIZATION_HEADER]: `${BEARER_PREFIX}xyz` });
+ const screen = await render(McpServerFormWrapper, { headers: existing });
+
+ await bearerInput(screen).fill('');
+
+ await expect.element(capturedHeaders(screen)).toHaveAttribute('data-captured-headers', '');
+ });
+
+ it('does not surface Bearer Authorization in the KV section even when pre-existing', async () => {
+ const existing = JSON.stringify({ [AUTHORIZATION_HEADER]: `${BEARER_PREFIX}xyz` });
+ const screen = await render(McpServerFormWrapper, { headers: existing });
+ const headerKeyInput = screen.getByPlaceholder('Header name');
+
+ await expect.element(headerKeyInput).not.toBeInTheDocument();
+ });
+});
diff --git a/tools/ui/tests/client/page.svelte.test.ts b/tools/ui/tests/client/page.svelte.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..37d7e08c4983ce65b52e909aa28ba382221eadb8
--- /dev/null
+++ b/tools/ui/tests/client/page.svelte.test.ts
@@ -0,0 +1,12 @@
+import TestWrapper from './components/TestWrapper.svelte';
+import { describe, expect, it } from 'vitest';
+import { render } from 'vitest-browser-svelte';
+
+describe('/+page.svelte', () => {
+ it('should render page without throwing', async () => {
+ // Basic smoke test - page should render without throwing errors.
+ // API calls are mocked in vitest-setup-client.ts.
+ await render(TestWrapper);
+ expect(true).toBe(true);
+ });
+});
diff --git a/tools/ui/tests/client/picker-list-scroll.svelte.test.ts b/tools/ui/tests/client/picker-list-scroll.svelte.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..469b626e60c3f2eba1baaabeaa9dd416f151275e
--- /dev/null
+++ b/tools/ui/tests/client/picker-list-scroll.svelte.test.ts
@@ -0,0 +1,32 @@
+// Regression test: opening a chat-form picker must not scroll the
+// conversation to the top. Root cause: the list's scroll effect fired
+// scrollIntoView on the initial mount, before the popover was positioned,
+// so the browser scrolled every scrollable ancestor to reveal the row.
+
+import PickerListScrollHarness from './components/PickerListScrollHarness.svelte';
+import { tick } from 'svelte';
+import { describe, expect, it } from 'vitest';
+import { render } from 'vitest-browser-svelte';
+
+describe('ChatFormPickerList mount scroll', () => {
+ it('does not scroll documentElement when the picker mounts', async () => {
+ const screen = render(PickerListScrollHarness);
+
+ await tick();
+
+ document.documentElement.scrollTop = document.documentElement.scrollHeight;
+ await tick();
+ const before = document.documentElement.scrollTop;
+
+ expect(before).toBeGreaterThan(0);
+
+ screen.component.openPicker();
+ await tick();
+ await new Promise((r) => setTimeout(r, 100));
+ await tick();
+
+ const after = document.documentElement.scrollTop;
+
+ expect(after).toBe(before);
+ });
+});
diff --git a/tools/ui/tests/client/sandbox.service.svelte.test.ts b/tools/ui/tests/client/sandbox.service.svelte.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..547e3ac1f291d749888e8ce6c38cfd8ee1ba5b40
--- /dev/null
+++ b/tools/ui/tests/client/sandbox.service.svelte.test.ts
@@ -0,0 +1,66 @@
+import { SANDBOX_TOOL_NAME } from '$lib/constants';
+import { SandboxService } from '$lib/services/sandbox.service';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+const run = (code: string, timeoutMs?: number) =>
+ SandboxService.executeTool(SANDBOX_TOOL_NAME, {
+ code,
+ ...(timeoutMs !== undefined ? { timeout_ms: timeoutMs } : {})
+ });
+
+describe('sandbox service', () => {
+ beforeEach(async () => {
+ const { settingsStore } = await import('$lib/stores/settings/index.svelte');
+
+ settingsStore.config = {
+ ...settingsStore.config,
+ symbolicMathEnabled: true
+ };
+ });
+
+ it('executes plain JavaScript', async () => {
+ const reply = await run('return 1 + 1;');
+
+ expect(reply.isError).toBe(false);
+ expect(reply.content).toContain('=> 2');
+ });
+
+ it('exposes nerdamer for symbolic computation', async () => {
+ const reply = await run("return nerdamer.diff('sin(x)/x', 'x').toString();");
+
+ expect(reply.isError).toBe(false);
+ expect(reply.content).toContain('cos(x)');
+ });
+
+ it('computes exact rational arithmetic', async () => {
+ const reply = await run("return nerdamer('1/3 + 1/6').toString();");
+
+ expect(reply.isError).toBe(false);
+ expect(reply.content).toContain('=> 1/2');
+ });
+
+ it('proves a polynomial identity symbolically', async () => {
+ const reply = await run(
+ "return nerdamer('expand((1+x*y)^3 - (1 + 3*x*y + 3*x^2*y^2 + x^3*y^3))').toString();"
+ );
+
+ expect(reply.isError).toBe(false);
+ expect(reply.content).toContain('=> 0');
+ });
+
+ it('blocks network egress in the worker via CSP', async () => {
+ const reply = await run(
+ "try { await fetch('https://example.com/'); return 'leaked'; } catch { return 'blocked'; }"
+ );
+
+ expect(reply.isError).toBe(false);
+ expect(reply.content).toContain('=> blocked');
+ });
+
+ it('enforces the timeout on runaway code', async () => {
+ const reply = await run('while (true) {}', 500);
+
+ expect(reply.isError).toBe(true);
+ expect(reply.content).toContain('timed out');
+ });
+});
diff --git a/tools/ui/tests/client/settings-registry-invariants.svelte.test.ts b/tools/ui/tests/client/settings-registry-invariants.svelte.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..0ed6996b5304e6dbac88b6e57e44b93590d54ad4
--- /dev/null
+++ b/tools/ui/tests/client/settings-registry-invariants.svelte.test.ts
@@ -0,0 +1,114 @@
+import { CONFIG_LOCALSTORAGE_KEY, SETTING_CONFIG_DEFAULT } from '$lib/constants';
+import { ParameterSyncService } from '$lib/services/parameter-sync.service';
+import { serverStore } from '$lib/stores/server.svelte';
+import { settingsStore } from '$lib/stores/settings/index.svelte';
+import type { SettingsConfigType } from '$lib/types';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+type Primitive = string | number | boolean;
+
+const KEYS = Object.keys(SETTING_CONFIG_DEFAULT).filter(
+ (k) => ['string', 'number', 'boolean'].includes(typeof SETTING_CONFIG_DEFAULT[k]) && k !== 'theme'
+);
+
+function divergent(key: string, base: Primitive): Primitive {
+ if (typeof base === 'boolean') return !base;
+
+ if (typeof base === 'number') return base + 7;
+
+ return `user-${key}`;
+}
+
+function baselineFor(key: string, base: Primitive): Primitive {
+ if (typeof base === 'boolean') return !base;
+
+ if (typeof base === 'number') return base + 42;
+
+ return `admin-${key}`;
+}
+
+function mockProps(uiSettings: Record) {
+ Object.defineProperty(serverStore, 'props', {
+ configurable: true,
+ get: () =>
+ ({
+ default_generation_settings: { params: { temperature: 0.8 } },
+ ui_settings: uiSettings
+ }) as unknown as typeof serverStore.props
+ });
+}
+
+const setUser = (key: string, value: Primitive) =>
+ settingsStore.updateConfig(key as keyof SettingsConfigType, value as never);
+const current = (key: string) => (settingsStore.config as Record)[key];
+
+describe('registry-wide invariants', () => {
+ beforeEach(() => {
+ localStorage.removeItem(CONFIG_LOCALSTORAGE_KEY);
+ });
+
+ it('I1: no load ever modifies a stored user value, for any key of any type', () => {
+ settingsStore.initialize();
+ const userValues: Record = {};
+
+ for (const key of KEYS) {
+ userValues[key] = divergent(key, SETTING_CONFIG_DEFAULT[key] as Primitive);
+ setUser(key, userValues[key]);
+ }
+
+ // simulated F5 + adverse admin baseline on every key, synced twice
+ settingsStore.initialize();
+ const adverse: Record = {};
+
+ for (const key of KEYS)
+ adverse[key] = baselineFor(key, SETTING_CONFIG_DEFAULT[key] as Primitive);
+ mockProps(adverse);
+ settingsStore.syncWithServerDefaults();
+ settingsStore.syncWithServerDefaults();
+
+ for (const key of KEYS) {
+ expect(current(key), key).toBe(userValues[key]);
+ }
+ });
+
+ it('first visit: the baseline applies for every key, false and 0 included', () => {
+ settingsStore.initialize();
+ const baseline: Record = {};
+
+ for (const key of KEYS)
+ baseline[key] = baselineFor(key, SETTING_CONFIG_DEFAULT[key] as Primitive);
+ mockProps(baseline);
+
+ settingsStore.syncWithServerDefaults();
+
+ for (const key of KEYS) {
+ if (ParameterSyncService.canSyncParameter(key)) continue;
+
+ expect(current(key), key).toBe(baseline[key]);
+ }
+ });
+
+ it('I3: Reset returns every key to baseline when defined, factory default otherwise', () => {
+ settingsStore.initialize();
+ for (const key of KEYS) setUser(key, divergent(key, SETTING_CONFIG_DEFAULT[key] as Primitive));
+
+ const baseline: Record = {};
+
+ KEYS.filter((_, i) => i % 2 === 0).forEach((key) => {
+ baseline[key] = baselineFor(key, SETTING_CONFIG_DEFAULT[key] as Primitive);
+ });
+ mockProps(baseline);
+
+ settingsStore.forceSyncWithServerDefaults();
+
+ for (const key of KEYS) {
+ if (key in baseline) {
+ expect(current(key), key).toBe(baseline[key]);
+ } else if (ParameterSyncService.canSyncParameter(key)) {
+ expect(current(key), key).toBe('');
+ } else {
+ expect(current(key), key).toBe(SETTING_CONFIG_DEFAULT[key]);
+ }
+ }
+ });
+});
diff --git a/tools/ui/tests/client/settings-render-keys-migration.svelte.test.ts b/tools/ui/tests/client/settings-render-keys-migration.svelte.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..ce65aeb700018bca1b6f739a9f62d79bbc1c222f
--- /dev/null
+++ b/tools/ui/tests/client/settings-render-keys-migration.svelte.test.ts
@@ -0,0 +1,64 @@
+// Guards the unfolding of `renderContentAsRawText` back onto the two
+// per-surface render keys. The single toggle carried user content and
+// thinking at once, so only the user key is restored from it and thinking
+// returns to its own default. The toggle is removed from the persisted
+// config so it does not stay orphaned in localStorage.
+
+import { CONFIG_LOCALSTORAGE_KEY } from '$lib/constants';
+import { MigrationService } from '$lib/services/migration.service';
+import { settingsStore } from '$lib/stores/settings/index.svelte';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+const RENDER_KEYS_MIGRATION_ID = 'render-keys-unfold-v1';
+
+async function seedConfig(stored: Record) {
+ localStorage.setItem(CONFIG_LOCALSTORAGE_KEY, JSON.stringify(stored));
+
+ const migration = MigrationService.getMigrations().find((m) => m.id === RENDER_KEYS_MIGRATION_ID);
+
+ await migration?.run();
+ settingsStore.initialize();
+}
+
+function persisted(): Record {
+ return JSON.parse(localStorage.getItem(CONFIG_LOCALSTORAGE_KEY) ?? '{}');
+}
+
+describe('renderContentAsRawText unfolding', () => {
+ beforeEach(() => {
+ localStorage.removeItem(CONFIG_LOCALSTORAGE_KEY);
+ MigrationService.resetState();
+ settingsStore.initialize();
+ });
+
+ it('maps raw text to user content as plain text', async () => {
+ await seedConfig({ renderContentAsRawText: true });
+ expect(settingsStore.config.renderUserContentAsMarkdown).toBe(false);
+ });
+
+ it('maps markdown to user content as markdown', async () => {
+ await seedConfig({ renderContentAsRawText: false });
+ expect(settingsStore.config.renderUserContentAsMarkdown).toBe(true);
+ });
+
+ it('leaves thinking on its own default', async () => {
+ await seedConfig({ renderContentAsRawText: true });
+ expect(settingsStore.config.renderThinkingAsMarkdown).toBe(true);
+ });
+
+ it('keeps an explicit user preference over the toggle', async () => {
+ await seedConfig({ renderContentAsRawText: true, renderUserContentAsMarkdown: true });
+ expect(settingsStore.config.renderUserContentAsMarkdown).toBe(true);
+ });
+
+ it('drops the toggle from the persisted config', async () => {
+ await seedConfig({ renderContentAsRawText: true });
+ expect(persisted().renderContentAsRawText).toBeUndefined();
+ });
+
+ it('leaves both surfaces on markdown when nothing is stored', async () => {
+ await seedConfig({});
+ expect(settingsStore.config.renderUserContentAsMarkdown).toBe(true);
+ expect(settingsStore.config.renderThinkingAsMarkdown).toBe(true);
+ });
+});
diff --git a/tools/ui/tests/client/ui-settings-sync.svelte.test.ts b/tools/ui/tests/client/ui-settings-sync.svelte.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..ca9268e2e067292e1c8a2f8ee271212dde946b97
--- /dev/null
+++ b/tools/ui/tests/client/ui-settings-sync.svelte.test.ts
@@ -0,0 +1,87 @@
+import { CONFIG_LOCALSTORAGE_KEY } from '$lib/constants';
+import { serverStore } from '$lib/stores/server.svelte';
+import { settingsStore } from '$lib/stores/settings/index.svelte';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+function mockProps(uiSettings: Record) {
+ Object.defineProperty(serverStore, 'props', {
+ configurable: true,
+ get: () =>
+ ({
+ default_generation_settings: { params: { temperature: 0.8 } },
+ ui_settings: uiSettings
+ }) as unknown as typeof serverStore.props
+ });
+}
+
+describe('server ui_settings application semantics', () => {
+ beforeEach(() => {
+ localStorage.removeItem(CONFIG_LOCALSTORAGE_KEY);
+ });
+
+ it('applies the admin defaults once for a new user', () => {
+ settingsStore.initialize();
+ mockProps({ apiKey: '', theme: 'dark' });
+
+ settingsStore.syncWithServerDefaults();
+
+ expect(settingsStore.config.theme).toBe('dark');
+ });
+
+ it('never reapplies on later loads: the user config diverges freely', () => {
+ settingsStore.initialize();
+ settingsStore.updateConfig('theme', 'light');
+ settingsStore.updateConfig('apiKey', 'sk-user-key');
+
+ // simulated F5: config now exists in localStorage
+ settingsStore.initialize();
+ mockProps({ apiKey: '', theme: 'dark' });
+
+ settingsStore.syncWithServerDefaults();
+ settingsStore.syncWithServerDefaults();
+
+ expect(settingsStore.config.theme).toBe('light');
+ expect(settingsStore.config.apiKey).toBe('sk-user-key');
+ const stored = JSON.parse(localStorage.getItem(CONFIG_LOCALSTORAGE_KEY) ?? '{}');
+
+ expect(stored.apiKey).toBe('sk-user-key');
+ });
+
+ it('keeps a value the user sets before the baseline is reachable', () => {
+ settingsStore.initialize();
+ // the splash is the only way in when the server runs with --api-key,
+ // so the first user write lands before the first successful /props
+ settingsStore.updateConfig('apiKey', 'sk-user-key');
+ mockProps({ apiKey: 'admin-placeholder', theme: 'dark' });
+
+ settingsStore.syncWithServerDefaults();
+
+ expect(settingsStore.config.apiKey).toBe('sk-user-key');
+ expect(settingsStore.config.theme).toBe('dark');
+ });
+
+ it('Reset to Default reapplies the full baseline, api key included', () => {
+ settingsStore.initialize();
+ settingsStore.updateConfig('theme', 'light');
+ settingsStore.updateConfig('apiKey', 'sk-user-key');
+ mockProps({ apiKey: '', theme: 'dark' });
+
+ settingsStore.forceSyncWithServerDefaults();
+
+ expect(settingsStore.config.theme).toBe('dark');
+ expect(settingsStore.config.apiKey).toBe('');
+ });
+});
+
+describe('syncable scope (spec section 4)', () => {
+ it('sampling params keep their live server twin, ui settings carry none', async () => {
+ const { ParameterSyncService } = await import('$lib/services/parameter-sync.service');
+
+ expect(ParameterSyncService.canSyncParameter('temperature')).toBe(true);
+ expect(ParameterSyncService.canSyncParameter('samplers')).toBe(true);
+ expect(ParameterSyncService.canSyncParameter('theme')).toBe(false);
+ expect(ParameterSyncService.canSyncParameter('systemMessage')).toBe(false);
+ expect(ParameterSyncService.canSyncParameter('apiKey')).toBe(false);
+ expect(ParameterSyncService.canSyncParameter('customCss')).toBe(false);
+ });
+});
diff --git a/tools/ui/tests/client/update-message-in-place.svelte.test.ts b/tools/ui/tests/client/update-message-in-place.svelte.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..ea3b65d0cc26e0edae84ea4c2357ec0159e9c816
--- /dev/null
+++ b/tools/ui/tests/client/update-message-in-place.svelte.test.ts
@@ -0,0 +1,64 @@
+// Pins the contract that makes streaming cheap: updateMessageAtIndex mutates the
+// existing message object instead of replacing it.
+//
+// Replacing it (`{ ...old, ...updates }`) changes the array slot, which
+// invalidates every consumer that merely walks the list - ChatMessages'
+// `displayMessages` rebuilds entries for EVERY message in the conversation. That
+// made per-token cost scale with conversation length (1.26ms at 1 prior message
+// -> 3.07ms at 40). Mutating in place keeps it flat.
+
+import { MessageRole } from '$lib/enums';
+import { conversationsStore } from '$lib/stores/conversations/index.svelte';
+import type { DatabaseMessage } from '$lib/types';
+import { describe, expect, it } from 'vitest';
+
+function makeMessage(id: string): DatabaseMessage {
+ return {
+ children: [],
+ content: '',
+ convId: 'c1',
+ id,
+ parent: null,
+ role: MessageRole.ASSISTANT,
+ timestamp: 0,
+ type: 'text'
+ } as DatabaseMessage;
+}
+
+describe('conversationsStore.updateMessageAtIndex', () => {
+ it('mutates in place, preserving object identity', () => {
+ conversationsStore.activeMessages = [makeMessage('a'), makeMessage('b')];
+ const before = conversationsStore.activeMessages[1];
+
+ conversationsStore.updateMessageAtIndex(1, { content: 'hello' });
+
+ expect(conversationsStore.activeMessages[1].content).toBe('hello');
+ expect(conversationsStore.activeMessages[1]).toBe(before);
+
+ conversationsStore.activeMessages = [];
+ });
+
+ it('leaves other messages and unrelated fields untouched', () => {
+ conversationsStore.activeMessages = [makeMessage('a'), makeMessage('b')];
+ const untouched = conversationsStore.activeMessages[0];
+
+ conversationsStore.updateMessageAtIndex(1, { content: 'x', model: 'm1' });
+
+ expect(conversationsStore.activeMessages[0]).toBe(untouched);
+ expect(conversationsStore.activeMessages[0].content).toBe('');
+ expect(conversationsStore.activeMessages[1].model).toBe('m1');
+ expect(conversationsStore.activeMessages[1].id).toBe('b');
+
+ conversationsStore.activeMessages = [];
+ });
+
+ it('is a no-op for an index of -1 or out of range', () => {
+ conversationsStore.activeMessages = [makeMessage('a')];
+
+ expect(() => conversationsStore.updateMessageAtIndex(-1, { content: 'x' })).not.toThrow();
+ expect(() => conversationsStore.updateMessageAtIndex(9, { content: 'x' })).not.toThrow();
+ expect(conversationsStore.activeMessages[0].content).toBe('');
+
+ conversationsStore.activeMessages = [];
+ });
+});
diff --git a/tools/ui/tests/e2e/pwa.e2e.ts b/tools/ui/tests/e2e/pwa.e2e.ts
new file mode 100644
index 0000000000000000000000000000000000000000..09442f42927fc097afbe82fc712750bc79a6a421
--- /dev/null
+++ b/tools/ui/tests/e2e/pwa.e2e.ts
@@ -0,0 +1,117 @@
+import { expect, test } from '@playwright/test';
+
+test.describe('PWA Service Worker', () => {
+ test('service worker is registered', async ({ page }) => {
+ await page.goto('/');
+
+ const swURL = await page.evaluate(async () => {
+ const registration = await Promise.race([
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
+ // @ts-ignore - type inference differs from browser runtime
+ navigator.serviceWorker.ready,
+ new Promise((_, reject) =>
+ setTimeout(() => reject(new Error('Service worker registration failed: timeout')), 15000)
+ )
+ ]);
+
+ // @ts-expect-error registration is of type unknown
+ return registration.active?.scriptURL;
+ });
+
+ expect(swURL).toBeTruthy();
+ expect(swURL).toContain('/sw.js');
+ });
+
+ test('service worker has precache configured', async ({ page }) => {
+ await page.goto('/');
+
+ await page.evaluate(async () => {
+ await navigator.serviceWorker.ready;
+ });
+
+ const swActive = await page.evaluate(async () => {
+ const reg = await navigator.serviceWorker.ready;
+
+ return reg.active?.scriptURL ?? null;
+ });
+
+ expect(swActive).toBeTruthy();
+
+ const swResponse = await page.request.get(swActive!);
+ const swContent = await swResponse.text();
+
+ // Precache contains SvelteKit content-hashed bundle paths
+ expect(swContent).toMatch(/"_app\/immutable\/bundle\.[a-zA-Z0-9_-]+\.js"/);
+ expect(swContent).toMatch(/"_app\/immutable\/assets\/bundle\.[a-zA-Z0-9_-]+\.css"/);
+ expect(swContent).toMatch(/"manifest\.webmanifest"/);
+ expect(swContent).toMatch(/"_app\/version\.json"/);
+ // NavigationRoute is intentionally absent — server API endpoints
+ // (e.g. /slots, /models) must not be intercepted by the PWA and
+ // should return JSON directly from the server.
+ expect(swContent).not.toMatch(/NavigationRoute/);
+ expect(swContent).toMatch(/api-cache/);
+ });
+
+ test('offline mode - page loads when offline after caching', async ({ browser }) => {
+ const context = await browser.newContext();
+ const offlinePage = await context.newPage();
+
+ await offlinePage.goto('/');
+ await offlinePage.waitForLoadState('networkidle');
+
+ await offlinePage.evaluate(async () => {
+ await navigator.serviceWorker.ready;
+ });
+
+ await offlinePage.waitForTimeout(2000);
+
+ await context.setOffline(true);
+ await offlinePage.goto('/');
+
+ const bodyText = await offlinePage.locator('body').textContent();
+
+ expect(bodyText).toBeTruthy();
+
+ await context.close();
+ });
+
+ test('version.json is accessible and contains version', async ({ page }) => {
+ const versionResponse = await page.request.get('/_app/version.json');
+
+ expect(versionResponse.ok()).toBeTruthy();
+
+ const versionData = await versionResponse.json();
+
+ expect(versionData).toHaveProperty('version');
+ expect(typeof versionData.version).toBe('string');
+ expect(versionData.version.length).toBeGreaterThan(0);
+ });
+
+ test('manifest.webmanifest is accessible and valid', async ({ page }) => {
+ const response = await page.request.get('/manifest.webmanifest');
+
+ expect(response.ok()).toBeTruthy();
+
+ const manifest = await response.json();
+
+ expect(manifest).toHaveProperty('name', 'llama-ui');
+ expect(manifest).toHaveProperty('short_name', 'llama-ui');
+ expect(manifest).toHaveProperty('start_url', './');
+ expect(manifest).toHaveProperty('display', 'standalone');
+ expect(manifest.icons).toBeTruthy();
+ expect(manifest.icons.length).toBeGreaterThan(0);
+ });
+
+ test('index.html contains content-hashed bundle references', async ({ page }) => {
+ const response = await page.request.get('/');
+
+ expect(response.ok()).toBeTruthy();
+
+ const html = await response.text();
+
+ // SvelteKit outputs content-hashed bundle names in _app/immutable/
+ expect(html).toMatch(/href="(\.\/|\/)_app\/immutable\/bundle\.[a-zA-Z0-9_-]+\.js"/);
+ expect(html).toMatch(/href="(\.\/|\/)_app\/immutable\/assets\/bundle\.[a-zA-Z0-9_-]+\.css"/);
+ expect(html).toMatch(/import\("(\.\/|\/)_app\/immutable\/bundle\.[a-zA-Z0-9_-]+\.js"\)/);
+ });
+});
diff --git a/tools/ui/tests/stories/ChatMessage.stories.svelte b/tools/ui/tests/stories/ChatMessage.stories.svelte
new file mode 100644
index 0000000000000000000000000000000000000000..270813eb38695dc96bb4ceb65020007dc8310156
--- /dev/null
+++ b/tools/ui/tests/stories/ChatMessage.stories.svelte
@@ -0,0 +1,229 @@
+
+
+ {
+ const { settingsStore } = await import('$lib/stores/settings/index.svelte');
+
+ settingsStore.updateConfig('showRawOutputSwitch', false);
+ }}
+/>
+
+ {
+ const { settingsStore } = await import('$lib/stores/settings/index.svelte');
+
+ settingsStore.updateConfig('showRawOutputSwitch', false);
+ }}
+/>
+
+ {
+ const { settingsStore } = await import('$lib/stores/settings/index.svelte');
+
+ settingsStore.updateConfig('showRawOutputSwitch', false);
+ }}
+/>
+
+ {
+ const { settingsStore } = await import('$lib/stores/settings/index.svelte');
+
+ settingsStore.updateConfig('showRawOutputSwitch', true);
+ }}
+/>
+
+ {
+ const { settingsStore } = await import('$lib/stores/settings/index.svelte');
+
+ settingsStore.updateConfig('showRawOutputSwitch', false);
+ // Phase 1: Stream reasoning content in chunks
+ let reasoningText =
+ 'I need to think about this carefully. Let me break down the problem:\n\n1. The user is asking for help with something complex\n2. I should provide a thorough and helpful response\n3. I need to consider multiple approaches\n4. The best solution would be to explain step by step\n\nThis approach will ensure clarity and understanding.';
+ let reasoningChunk = 'I';
+ let i = 0;
+
+ while (i < reasoningText.length) {
+ const chunkSize = Math.floor(Math.random() * 5) + 3; // Random 3-7 characters
+ const chunk = reasoningText.slice(i, i + chunkSize);
+
+ reasoningChunk += chunk;
+
+ // Update the reactive state directly
+ streamingMessage.thinking = reasoningChunk;
+
+ i += chunkSize;
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+
+ const regularText =
+ "Based on my analysis, here's the solution:\n\n**Step 1:** First, we need to understand the requirements clearly.\n\n**Step 2:** Then we can implement the solution systematically.\n\n**Step 3:** Finally, we test and validate the results.\n\nThis approach ensures we cover all aspects of the problem effectively.";
+
+ let contentChunk = '';
+
+ i = 0;
+
+ while (i < regularText.length) {
+ const chunkSize = Math.floor(Math.random() * 5) + 3; // Random 3-7 characters
+ const chunk = regularText.slice(i, i + chunkSize);
+
+ contentChunk += chunk;
+
+ // Update the reactive state directly
+ streamingMessage.content = contentChunk;
+
+ i += chunkSize;
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+
+ streamingMessage.timestamp = Date.now();
+ }}
+>
+
+
+
+
+
+ {
+ const { settingsStore } = await import('$lib/stores/settings/index.svelte');
+
+ settingsStore.updateConfig('showRawOutputSwitch', false);
+ // Import the chat store to simulate loading state
+ const { chatStore } = await import('$lib/stores/chat/index.svelte');
+
+ // Set loading state to true to trigger the processing UI
+ chatStore.isLoading = true;
+
+ // Simulate the processing state hook behavior
+ // This will show the "Generating..." text and parameter details
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ }}
+/>
diff --git a/tools/ui/tests/stories/ChatScreenForm.stories.svelte b/tools/ui/tests/stories/ChatScreenForm.stories.svelte
new file mode 100644
index 0000000000000000000000000000000000000000..b41ccf0a19869346ed2472b4cca17b72b7bdc6b2
--- /dev/null
+++ b/tools/ui/tests/stories/ChatScreenForm.stories.svelte
@@ -0,0 +1,95 @@
+
+
+ {
+ const textarea = await canvas.findByRole('textbox');
+ const submitButton = await canvas.findByRole('button', { name: 'Send' });
+
+ // Expect the input to be focused after the component is mounted
+ await expect(textarea).toHaveFocus();
+
+ // Expect the submit button to be disabled
+ await expect(submitButton).toBeDisabled();
+
+ const text = 'What is the meaning of life?';
+
+ await userEvent.clear(textarea);
+ await userEvent.type(textarea, text);
+
+ await expect(textarea).toHaveValue(text);
+
+ const fileInput = document.querySelector('input[type="file"]');
+
+ await expect(fileInput).not.toHaveAttribute('accept');
+ }}
+/>
+
+
+
+ {
+ const jpgAttachment = canvas.getByAltText('1.jpg');
+ const svgAttachment = canvas.getByAltText('hf-logo.svg');
+ const pdfFileExtension = canvas.getByText('PDF');
+ const pdfAttachment = canvas.getByText('example.pdf');
+ const pdfSize = canvas.getByText('342.82 KB');
+
+ await expect(jpgAttachment).toBeInTheDocument();
+ await expect(jpgAttachment).toHaveAttribute('src', jpgAsset);
+
+ await expect(svgAttachment).toBeInTheDocument();
+ await expect(svgAttachment).toHaveAttribute('src', svgAsset);
+
+ await expect(pdfFileExtension).toBeInTheDocument();
+ await expect(pdfAttachment).toBeInTheDocument();
+ await expect(pdfSize).toBeInTheDocument();
+ }}
+/>
diff --git a/tools/ui/tests/stories/Introduction.mdx b/tools/ui/tests/stories/Introduction.mdx
new file mode 100644
index 0000000000000000000000000000000000000000..d4c0c792164c5f5b2bd27c03e0306c0b2c9d647d
--- /dev/null
+++ b/tools/ui/tests/stories/Introduction.mdx
@@ -0,0 +1,44 @@
+import { Meta } from '@storybook/addon-docs/blocks';
+
+
+
+# llama.cpp Web UI
+
+Welcome to the **llama-ui** component library! This Storybook showcases the components used in the modern web interface for the llama-server.
+
+## 🚀 About This Project
+
+Llama UI is a modern web interface for the llama-server, built with SvelteKit and ShadCN UI. Features include:
+
+- **Real-time chat conversations** with AI assistants
+- **Multi-conversation management** with persistent storage
+- **Advanced parameter tuning** for model behavior
+- **File upload support** for multimodal interactions
+- **Responsive design** that works on desktop and mobile
+
+## 🎨 Design System
+
+The UI is built using:
+
+- **SvelteKit** - Modern web framework with excellent performance
+- **Tailwind CSS** - Utility-first CSS framework for rapid styling
+- **ShadCN/UI** - High-quality, accessible component library
+- **Lucide Icons** - Beautiful, consistent icon set
+
+## 🔧 Development
+
+This Storybook serves as both documentation and a development environment for the UI components. Each story demonstrates:
+
+- **Component variations** - Different states and configurations
+- **Interactive examples** - Live components you can interact with
+- **Usage patterns** - How components work together
+- **Styling consistency** - Unified design language
+
+## 🚀 Getting Started
+
+To explore the components:
+
+1. **Browse the sidebar** to see all available components
+2. **Click on stories** to see different component states
+3. **Use the controls panel** to interact with component props
+4. **Check the docs tab** for detailed component information
diff --git a/tools/ui/tests/stories/MarkdownContent.stories.svelte b/tools/ui/tests/stories/MarkdownContent.stories.svelte
new file mode 100644
index 0000000000000000000000000000000000000000..b3203e335969deeabdb740567a9e7777c5b627ab
--- /dev/null
+++ b/tools/ui/tests/stories/MarkdownContent.stories.svelte
@@ -0,0 +1,139 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {
+ const { canvasElement } = context;
+
+ // Wait for component to render
+ await new Promise((resolve) => setTimeout(resolve, 100));
+
+ // Find all links in the rendered content
+ const links = (canvasElement as HTMLElement).querySelectorAll(
+ 'a[href]'
+ ) as NodeListOf;
+ const linkList = Array.from(links) as HTMLAnchorElement[];
+
+ // Test that we have the expected number of links
+ expect(links.length).toBeGreaterThan(0);
+
+ // Test each link for proper attributes
+ links.forEach((link: HTMLAnchorElement) => {
+ const href = link.getAttribute('href');
+
+ // Test that external links have proper security attributes
+ if (href && (href.startsWith('http://') || href.startsWith('https://'))) {
+ expect(link.getAttribute('target')).toBe('_blank');
+ expect(link.getAttribute('rel')).toBe('noopener noreferrer');
+ }
+ });
+
+ // Test specific links exist
+ const hugginFaceLink = linkList.find(
+ (link) => link.getAttribute('href') === 'https://huggingface.co'
+ );
+
+ expect(hugginFaceLink).toBeTruthy();
+ expect(hugginFaceLink?.textContent).toBe('Hugging Face Homepage');
+
+ const githubLink = linkList.find(
+ (link) => link.getAttribute('href') === 'https://github.com/ggml-org/llama.cpp'
+ );
+
+ expect(githubLink).toBeTruthy();
+ expect(githubLink?.textContent).toBe('GitHub Repository');
+
+ const openaiLink = linkList.find((link) => link.getAttribute('href') === 'https://openai.com');
+
+ expect(openaiLink).toBeTruthy();
+ expect(openaiLink?.textContent).toBe('OpenAI Website');
+
+ const googleLink = linkList.find(
+ (link) => link.getAttribute('href') === 'https://www.google.com'
+ );
+
+ expect(googleLink).toBeTruthy();
+ expect(googleLink?.textContent).toBe('Google Search');
+
+ // Test inline links (auto-linked URLs)
+ const exampleLink = linkList.find(
+ (link) => link.getAttribute('href') === 'https://example.com'
+ );
+
+ expect(exampleLink).toBeTruthy();
+
+ const pythonDocsLink = linkList.find(
+ (link) => link.getAttribute('href') === 'https://docs.python.org'
+ );
+
+ expect(pythonDocsLink).toBeTruthy();
+
+ console.log(`✅ URL Links test passed - Found ${links.length} links with proper attributes`);
+ }}
+/>
diff --git a/tools/ui/tests/stories/ModelsSelector.stories.svelte b/tools/ui/tests/stories/ModelsSelector.stories.svelte
new file mode 100644
index 0000000000000000000000000000000000000000..e577226f29967864f3e910c99d818da4f9102e98
--- /dev/null
+++ b/tools/ui/tests/stories/ModelsSelector.stories.svelte
@@ -0,0 +1,279 @@
+
+
+
+
+
+
+ console.log('Info clicked:', modelName)}
+ onSelect={handleSelect}
+ />
+
+
+
+
+
+ console.log('Info clicked:', modelName)}
+ onSelect={handleSelect}
+ />
+
+
+
+
+
+ console.log('Info clicked:', modelName)}
+ onSelect={handleSelect}
+ />
+
+
+
+
+
+
+ Server model states
+
+
+
{}}
+ onMouseEnter={() => {}}
+ onSelect={() => {}}
+ option={mockModel('model-idle', 'Model (idle)', 'meta')}
+ />
+
+ {}}
+ onMouseEnter={() => {}}
+ onSelect={() => {}}
+ option={mockModel('model-loading', 'Model (loading)', 'meta')}
+ />
+
+ {}}
+ onMouseEnter={() => {}}
+ onSelect={() => {}}
+ option={mockModel('model-loaded', 'Model (loaded)', 'meta')}
+ />
+
+ {}}
+ onMouseEnter={() => {}}
+ onSelect={() => {}}
+ option={mockModel('model-sleeping', 'Model (sleeping)', 'meta')}
+ />
+
+ {}}
+ onMouseEnter={() => {}}
+ onSelect={() => {}}
+ option={mockModel('model-failed', 'Model (failed)', 'meta')}
+ />
+
+
+
+
+
+
+ Selection states
+
+
+
{}}
+ onMouseEnter={() => {}}
+ onSelect={() => {}}
+ option={mockModel('normal-model', 'Normal Model', 'meta')}
+ />
+
+ {}}
+ onMouseEnter={() => {}}
+ onSelect={() => {}}
+ option={mockModel('selected-model', 'Selected Model', 'meta')}
+ />
+
+ {}}
+ onMouseEnter={() => {}}
+ onSelect={() => {}}
+ option={mockModel('highlighted-model', 'Highlighted Model', 'meta')}
+ />
+
+ {}}
+ onMouseEnter={() => {}}
+ onSelect={() => {}}
+ option={mockModel('fav-model', 'Favorite Model', 'Qwen')}
+ />
+
+
diff --git a/tools/ui/tests/stories/PwaRefreshAlert.stories.svelte b/tools/ui/tests/stories/PwaRefreshAlert.stories.svelte
new file mode 100644
index 0000000000000000000000000000000000000000..2a0a0b4bbf6a9e59c8e89c75be0b48931fe627ad
--- /dev/null
+++ b/tools/ui/tests/stories/PwaRefreshAlert.stories.svelte
@@ -0,0 +1,64 @@
+
+
+ console.log('reload') }}
+ name="Default"
+ play={async ({ canvas }) => {
+ const title = canvas.getByText('Update available');
+
+ await expect(title).toBeInTheDocument();
+
+ const description = canvas.getByText(/A new version is available/);
+
+ await expect(description).toBeInTheDocument();
+
+ const button = canvas.getByRole('button', { name: 'Reload' });
+
+ await expect(button).toBeInTheDocument();
+ }}
+/>
+
+ console.log('reload') }}
+ name="Hidden"
+ play={async ({ canvas }) => {
+ const title = canvas.queryByText('Update available');
+
+ await expect(title).not.toBeInTheDocument();
+ }}
+/>
+
+ console.log('reload')
+ }}
+ name="ClickReload"
+ play={async ({ canvas, userEvent }) => {
+ const button = canvas.getByRole('button', { name: 'Reload' });
+
+ await expect(button).toBeInTheDocument();
+
+ await userEvent.click(button);
+
+ const title = canvas.queryByText('Update available');
+
+ await expect(title).not.toBeInTheDocument();
+
+ const reloadBtn = canvas.queryByRole('button', { name: 'Reload' });
+
+ await expect(reloadBtn).not.toBeInTheDocument();
+ }}
+/>
diff --git a/tools/ui/tests/stories/SidebarNavigation.stories.svelte b/tools/ui/tests/stories/SidebarNavigation.stories.svelte
new file mode 100644
index 0000000000000000000000000000000000000000..ab05b1e9a7d408f7f917f059aa6abc6cc6b97c05
--- /dev/null
+++ b/tools/ui/tests/stories/SidebarNavigation.stories.svelte
@@ -0,0 +1,109 @@
+
+
+
+
+ {
+ const { conversationsStore } = await import('$lib/stores/conversations/index.svelte');
+
+ waitFor(() =>
+ setTimeout(() => {
+ conversationsStore.conversations = mockConversations;
+ }, 0)
+ );
+ }}
+>
+
+
+
+
+
+ {
+ const { conversationsStore } = await import('$lib/stores/conversations/index.svelte');
+
+ waitFor(() =>
+ setTimeout(() => {
+ conversationsStore.conversations = mockConversations;
+ }, 0)
+ );
+
+ // Expand sidebar first, then click Search in the expanded button list
+ const logoTrigger = screen.getByRole('button', { name: /expand navigation/i });
+
+ await userEvent.click(logoTrigger);
+ const searchTrigger = screen.getByText('Search');
+
+ userEvent.click(searchTrigger);
+ }}
+>
+
+
+
+
+
+ {
+ // Mock empty conversations store
+ const { conversationsStore } = await import('$lib/stores/conversations/index.svelte');
+
+ conversationsStore.conversations = [];
+ }}
+>
+
+
+
+
diff --git a/tools/ui/tests/stories/a11y/ActionIcon.a11y.stories.svelte b/tools/ui/tests/stories/a11y/ActionIcon.a11y.stories.svelte
new file mode 100644
index 0000000000000000000000000000000000000000..f94e7a792beaefbae945ce732cdc45d1a0a4e2de
--- /dev/null
+++ b/tools/ui/tests/stories/a11y/ActionIcon.a11y.stories.svelte
@@ -0,0 +1,35 @@
+
+
+ {
+ const before = await canvas.findByRole('button', { name: 'before' });
+ const target = await canvas.findByRole('button', { name: 'Copy' });
+
+ before.focus();
+ await userEvent.tab();
+
+ await expect(target).toHaveFocus();
+ }}
+>
+
+
before
+
+
{}} tooltip="Copy" />
+
+
diff --git a/tools/ui/tests/stories/a11y/ChatMessageStatistics.a11y.stories.svelte b/tools/ui/tests/stories/a11y/ChatMessageStatistics.a11y.stories.svelte
new file mode 100644
index 0000000000000000000000000000000000000000..ec3c269df2b6a8ad052e3569bef3e420d176cb32
--- /dev/null
+++ b/tools/ui/tests/stories/a11y/ChatMessageStatistics.a11y.stories.svelte
@@ -0,0 +1,50 @@
+
+
+ {
+ const reading = await canvas.findByRole('button', { name: 'Reading' });
+ const generation = await canvas.findByRole('button', { name: 'Generation' });
+ const tools = await canvas.findByRole('button', { name: 'Tools' });
+ const summary = await canvas.findByRole('button', { name: 'Summary' });
+
+ reading.focus();
+ await expect(reading).toHaveFocus();
+
+ await userEvent.tab();
+ await expect(generation).toHaveFocus();
+
+ await userEvent.tab();
+ await expect(tools).toHaveFocus();
+
+ await userEvent.tab();
+ await expect(summary).toHaveFocus();
+ }}
+/>
diff --git a/tools/ui/tests/stories/a11y/ChatScreenForm.a11y.stories.svelte b/tools/ui/tests/stories/a11y/ChatScreenForm.a11y.stories.svelte
new file mode 100644
index 0000000000000000000000000000000000000000..6fa5924e0812800b407de84e5dd158a775ffb086
--- /dev/null
+++ b/tools/ui/tests/stories/a11y/ChatScreenForm.a11y.stories.svelte
@@ -0,0 +1,51 @@
+
+
+ {
+ const textarea = await canvas.findByRole('textbox');
+
+ await userEvent.clear(textarea);
+ await userEvent.type(textarea, 'What is the meaning of life?');
+
+ const trigger = await canvas.findByRole('button', { name: ATTACHMENT_TOOLTIP_TEXT });
+
+ trigger.focus();
+ await expect(trigger).toHaveFocus();
+
+ await userEvent.tab();
+
+ await expect(trigger).not.toHaveFocus();
+ }}
+/>
+
+ {
+ const trigger = await canvas.findByRole('button', { name: ATTACHMENT_TOOLTIP_TEXT });
+
+ trigger.focus();
+ await userEvent.keyboard('{Enter}');
+ await screen.findByRole('menu');
+
+ await waitFor(() => {
+ expect(document.activeElement).toHaveTextContent('Reasoning');
+ });
+ }}
+/>
diff --git a/tools/ui/tests/stories/a11y/ScrollCarousel.a11y.stories.svelte b/tools/ui/tests/stories/a11y/ScrollCarousel.a11y.stories.svelte
new file mode 100644
index 0000000000000000000000000000000000000000..f1a04a9acefccc6eb20d38f554026054a043bf37
--- /dev/null
+++ b/tools/ui/tests/stories/a11y/ScrollCarousel.a11y.stories.svelte
@@ -0,0 +1,74 @@
+
+
+ {
+ const before = await canvas.findByRole('button', { name: 'before' });
+ const after = await canvas.findByRole('button', { name: 'after' });
+ const leftArrow = await canvas.findByRole('button', { name: 'Scroll left' });
+
+ await waitFor(() => {
+ expect(leftArrow).toBeDisabled();
+ });
+
+ before.focus();
+ await userEvent.tab();
+
+ await expect(after).toHaveFocus();
+ }}
+>
+
+
before
+
+
+
+
+
+
+
+
after
+
+
+
+ {
+ const before = await canvas.findByRole('button', { name: 'before' });
+ const rightArrow = await canvas.findByRole('button', { name: 'Scroll right' });
+
+ await waitFor(() => {
+ expect(rightArrow).not.toBeDisabled();
+ });
+
+ before.focus();
+ await userEvent.tab();
+
+ await expect(rightArrow).toHaveFocus();
+ }}
+>
+
+
before
+
+
+ {#each [...Array(20).keys()] as i (i)}
+ {i}
+ {/each}
+
+
+
diff --git a/tools/ui/tests/stories/a11y/SidebarNavigationConversationItem.a11y.stories.svelte b/tools/ui/tests/stories/a11y/SidebarNavigationConversationItem.a11y.stories.svelte
new file mode 100644
index 0000000000000000000000000000000000000000..170352bcebb89d6dc30d1c83c5ceb20e1afd3fe0
--- /dev/null
+++ b/tools/ui/tests/stories/a11y/SidebarNavigationConversationItem.a11y.stories.svelte
@@ -0,0 +1,36 @@
+
+
+ {
+ const row = await canvas.findByRole('button', { name: /Forked Conversation/ });
+ const forkIcon = await canvas.findByRole('link');
+
+ row.focus();
+ await userEvent.tab();
+
+ await expect(forkIcon).toHaveFocus();
+ }}
+/>
diff --git a/tools/ui/tests/stories/fixtures/ai-tutorial.ts b/tools/ui/tests/stories/fixtures/ai-tutorial.ts
new file mode 100644
index 0000000000000000000000000000000000000000..b3b1c24835921d0a579149905366e8e579da0c73
--- /dev/null
+++ b/tools/ui/tests/stories/fixtures/ai-tutorial.ts
@@ -0,0 +1,164 @@
+// AI Assistant Tutorial Response
+export const AI_TUTORIAL_MD = String.raw`
+# Building a Modern Chat Application with SvelteKit
+
+I'll help you create a **production-ready chat application** using SvelteKit, TypeScript, and WebSockets. This implementation includes real-time messaging, user authentication, and message persistence.
+
+## 🚀 Quick Start
+
+First, let's set up the project:
+
+${'```'}bash
+npm create svelte@latest chat-app
+cd chat-app
+npm install
+npm install socket.io socket.io-client
+npm install @prisma/client prisma
+npm run dev
+${'```'}
+
+## 📁 Project Structure
+
+${'```'}
+chat-app/
+├── src/
+│ ├── routes/
+│ │ ├── +layout.svelte
+│ │ ├── +page.svelte
+│ │ └── api/
+│ │ └── socket/+server.ts
+│ ├── lib/
+│ │ ├── components/
+│ │ │ ├── ChatMessage.svelte
+│ │ │ └── ChatInput.svelte
+│ │ └── stores/
+│ │ └── chat.ts
+│ └── app.html
+├── prisma/
+│ └── schema.prisma
+└── package.json
+${'```'}
+
+## 💻 Implementation
+
+### WebSocket Server
+
+${'```'}typescript
+// src/lib/server/socket.ts
+import { Server } from 'socket.io';
+import type { ViteDevServer } from 'vite';
+
+export function initializeSocketIO(server: ViteDevServer) {
+ const io = new Server(server.httpServer || server, {
+ cors: {
+ origin: process.env.ORIGIN || 'http://localhost:5173',
+ credentials: true
+ }
+ });
+
+ io.on('connection', (socket) => {
+ console.log('User connected:', socket.id);
+
+ socket.on('message', async (data) => {
+ // Broadcast to all clients
+ io.emit('new-message', {
+ id: crypto.randomUUID(),
+ userId: socket.id,
+ content: data.content,
+ timestamp: new Date().toISOString()
+ });
+ });
+
+ socket.on('disconnect', () => {
+ console.log('User disconnected:', socket.id);
+ });
+ });
+
+ return io;
+}
+${'```'}
+
+### Client Store
+
+${'```'}typescript
+// src/lib/stores/chat.ts
+import { writable } from 'svelte/store';
+import io from 'socket.io-client';
+
+export interface Message {
+ id: string;
+ userId: string;
+ content: string;
+ timestamp: string;
+}
+
+function createChatStore() {
+ const { subscribe, update } = writable([]);
+ let socket: ReturnType;
+
+ return {
+ subscribe,
+ connect: () => {
+ socket = io('http://localhost:5173');
+
+ socket.on('new-message', (message: Message) => {
+ update(messages => [...messages, message]);
+ });
+ },
+ sendMessage: (content: string) => {
+ if (socket && content.trim()) {
+ socket.emit('message', { content });
+ }
+ }
+ };
+}
+
+export const chatStore = createChatStore();
+${'```'}
+
+## 🎯 Key Features
+
+✅ **Real-time messaging** with WebSockets
+✅ **Message persistence** using Prisma + PostgreSQL
+✅ **Type-safe** with TypeScript
+✅ **Responsive UI** for all devices
+✅ **Auto-reconnection** on connection loss
+
+## 📊 Performance Metrics
+
+| Metric | Value |
+|--------|-------|
+| **Message Latency** | < 50ms |
+| **Concurrent Users** | 10,000+ |
+| **Messages/Second** | 5,000+ |
+| **Uptime** | 99.9% |
+
+## 🔧 Configuration
+
+### Environment Variables
+
+${'```'}env
+DATABASE_URL="postgresql://user:password@localhost:5432/chat"
+JWT_SECRET="your-secret-key"
+REDIS_URL="redis://localhost:6379"
+${'```'}
+
+## 🚢 Deployment
+
+Deploy to production using Docker:
+
+${'```'}dockerfile
+FROM node:20-alpine
+WORKDIR /app
+COPY package*.json ./
+RUN npm ci --only=production
+COPY . .
+RUN npm run build
+EXPOSE 3000
+CMD ["node", "build"]
+${'```'}
+
+---
+
+*Need help? Check the [documentation](https://kit.svelte.dev) or [open an issue](https://github.com/sveltejs/kit/issues)*
+`;
diff --git a/tools/ui/tests/stories/fixtures/api-docs.ts b/tools/ui/tests/stories/fixtures/api-docs.ts
new file mode 100644
index 0000000000000000000000000000000000000000..7b499956f8bc3106be6f2bedd728fe70c511aad2
--- /dev/null
+++ b/tools/ui/tests/stories/fixtures/api-docs.ts
@@ -0,0 +1,160 @@
+// API Documentation
+export const API_DOCS_MD = String.raw`
+# REST API Documentation
+
+## 🔐 Authentication
+
+All API requests require authentication using **Bearer tokens**. Include your API key in the Authorization header:
+
+${'```'}http
+GET /api/v1/users
+Host: api.example.com
+Authorization: Bearer YOUR_API_KEY
+Content-Type: application/json
+${'```'}
+
+## 📍 Endpoints
+
+### Users API
+
+#### **GET** /api/v1/users
+
+Retrieve a paginated list of users.
+
+**Query Parameters:**
+
+| Parameter | Type | Default | Description |
+|-----------|------|---------|-------------|
+| page | integer | 1 | Page number |
+| limit | integer | 20 | Items per page |
+| sort | string | "created_at" | Sort field |
+| order | string | "desc" | Sort order |
+
+**Response:** 200 OK
+
+${'```'}json
+{
+ "data": [
+ {
+ "id": "usr_1234567890",
+ "email": "user@example.com",
+ "name": "John Doe",
+ "role": "admin",
+ "created_at": "2024-01-15T10:30:00Z"
+ }
+ ],
+ "pagination": {
+ "page": 1,
+ "limit": 20,
+ "total": 156,
+ "pages": 8
+ }
+}
+${'```'}
+
+#### **POST** /api/v1/users
+
+Create a new user account.
+
+**Request Body:**
+
+${'```'}json
+{
+ "email": "newuser@example.com",
+ "password": "SecurePassword123!",
+ "name": "Jane Smith",
+ "role": "user"
+}
+${'```'}
+
+**Response:** 201 Created
+
+${'```'}json
+{
+ "id": "usr_9876543210",
+ "email": "newuser@example.com",
+ "name": "Jane Smith",
+ "role": "user",
+ "created_at": "2024-01-21T09:15:00Z"
+}
+${'```'}
+
+### Error Responses
+
+The API returns errors in a consistent format:
+
+${'```'}json
+{
+ "error": {
+ "code": "VALIDATION_ERROR",
+ "message": "Invalid request parameters",
+ "details": [
+ {
+ "field": "email",
+ "message": "Email format is invalid"
+ }
+ ]
+ }
+}
+${'```'}
+
+### Rate Limiting
+
+| Tier | Requests/Hour | Burst |
+|------|--------------|-------|
+| **Free** | 1,000 | 100 |
+| **Pro** | 10,000 | 500 |
+| **Enterprise** | Unlimited | - |
+
+**Headers:**
+- X-RateLimit-Limit
+- X-RateLimit-Remaining
+- X-RateLimit-Reset
+
+### Webhooks
+
+Configure webhooks to receive real-time events:
+
+${'```'}javascript
+// Webhook payload
+{
+ "event": "user.created",
+ "timestamp": "2024-01-21T09:15:00Z",
+ "data": {
+ "id": "usr_9876543210",
+ "email": "newuser@example.com"
+ },
+ "signature": "sha256=abcd1234..."
+}
+${'```'}
+
+### SDK Examples
+
+**JavaScript/TypeScript:**
+
+${'```'}typescript
+import { ApiClient } from '@example/api-sdk';
+
+const client = new ApiClient({
+ apiKey: process.env.API_KEY
+});
+
+const users = await client.users.list({
+ page: 1,
+ limit: 20
+});
+${'```'}
+
+**Python:**
+
+${'```'}python
+from example_api import Client
+
+client = Client(api_key=os.environ['API_KEY'])
+users = client.users.list(page=1, limit=20)
+${'```'}
+
+---
+
+📚 [Full API Reference](https://api.example.com/docs) | 💬 [Support](https://support.example.com)
+`;
diff --git a/tools/ui/tests/stories/fixtures/assets/1.jpg b/tools/ui/tests/stories/fixtures/assets/1.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..8348e38780de3332ba2e1d39fdb81fd8bba92389
Binary files /dev/null and b/tools/ui/tests/stories/fixtures/assets/1.jpg differ
diff --git a/tools/ui/tests/stories/fixtures/assets/beautiful-flowers-lotus.webp b/tools/ui/tests/stories/fixtures/assets/beautiful-flowers-lotus.webp
new file mode 100644
index 0000000000000000000000000000000000000000..a381cf364ba82158c315f1c9f94b7b6684551136
--- /dev/null
+++ b/tools/ui/tests/stories/fixtures/assets/beautiful-flowers-lotus.webp
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:a5f728fbce7c5b2ed8ef32303942f97a00e4cadb791ec65eadcfbe59ebe9625f
+size 817630
diff --git a/tools/ui/tests/stories/fixtures/assets/example.pdf b/tools/ui/tests/stories/fixtures/assets/example.pdf
new file mode 100644
index 0000000000000000000000000000000000000000..0d27da1dcdc565be93d5d5c8a2548162f12ff8db
--- /dev/null
+++ b/tools/ui/tests/stories/fixtures/assets/example.pdf
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:83a68983203e51467b9ffaf42c1a6728bd7a9c5a2425eb8e26acc2742020bdab
+size 351048
diff --git a/tools/ui/tests/stories/fixtures/assets/hf-logo.svg b/tools/ui/tests/stories/fixtures/assets/hf-logo.svg
new file mode 100644
index 0000000000000000000000000000000000000000..d55ea22a24f4fb8fc8ae911aff86f6689bb0ad1d
--- /dev/null
+++ b/tools/ui/tests/stories/fixtures/assets/hf-logo.svg
@@ -0,0 +1,8 @@
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/tools/ui/tests/stories/fixtures/blog-post.ts b/tools/ui/tests/stories/fixtures/blog-post.ts
new file mode 100644
index 0000000000000000000000000000000000000000..3eb2ed7585f869b3b2045318ce6b2179ecef6105
--- /dev/null
+++ b/tools/ui/tests/stories/fixtures/blog-post.ts
@@ -0,0 +1,125 @@
+// Blog Post Content
+export const BLOG_POST_MD = String.raw`
+# Understanding Rust's Ownership System
+
+*Published on March 15, 2024 • 8 min read*
+
+Rust's ownership system is one of its most distinctive features, enabling memory safety without garbage collection. In this post, we'll explore how ownership works and why it's revolutionary for systems programming.
+
+## What is Ownership?
+
+Ownership is a set of rules that governs how Rust manages memory. These rules are checked at compile time, ensuring memory safety without runtime overhead.
+
+### The Three Rules of Ownership
+
+1. **Each value has a single owner**
+2. **There can only be one owner at a time**
+3. **When the owner goes out of scope, the value is dropped**
+
+## Memory Management Without GC
+
+Traditional approaches to memory management:
+
+- **Manual management** (C/C++): Error-prone, leads to bugs
+- **Garbage collection** (Java, Python): Runtime overhead
+- **Ownership** (Rust): Compile-time safety, zero runtime cost
+
+## Basic Examples
+
+### Variable Scope
+
+${'```'}rust
+fn main() {
+ let s = String::from("hello"); // s comes into scope
+
+ // s is valid here
+ println!("{}", s);
+
+} // s goes out of scope and is dropped
+${'```'}
+
+### Move Semantics
+
+${'```'}rust
+fn main() {
+ let s1 = String::from("hello");
+ let s2 = s1; // s1 is moved to s2
+
+ // println!("{}", s1); // ❌ ERROR: s1 is no longer valid
+ println!("{}", s2); // ✅ OK: s2 owns the string
+}
+${'```'}
+
+## Borrowing and References
+
+Instead of transferring ownership, you can **borrow** values:
+
+### Immutable References
+
+${'```'}rust
+fn calculate_length(s: &String) -> usize {
+ s.len() // s is a reference, doesn't own the String
+}
+
+fn main() {
+ let s1 = String::from("hello");
+ let len = calculate_length(&s1); // Borrow s1
+ println!("Length of '{}' is {}", s1, len); // s1 still valid
+}
+${'```'}
+
+### Mutable References
+
+${'```'}rust
+fn main() {
+ let mut s = String::from("hello");
+
+ let r1 = &mut s;
+ r1.push_str(", world");
+ println!("{}", r1);
+
+ // let r2 = &mut s; // ❌ ERROR: cannot borrow twice
+}
+${'```'}
+
+## Common Pitfalls
+
+### Dangling References
+
+${'```'}rust
+fn dangle() -> &String { // ❌ ERROR: missing lifetime specifier
+ let s = String::from("hello");
+ &s // s will be dropped, leaving a dangling reference
+}
+${'```'}
+
+### ✅ Solution
+
+${'```'}rust
+fn no_dangle() -> String {
+ let s = String::from("hello");
+ s // Ownership is moved out
+}
+${'```'}
+
+## Benefits
+
+- ✅ **No null pointer dereferences**
+- ✅ **No data races**
+- ✅ **No use-after-free**
+- ✅ **No memory leaks**
+
+## Conclusion
+
+Rust's ownership system eliminates entire classes of bugs at compile time. While it has a learning curve, the benefits in safety and performance are worth it.
+
+## Further Reading
+
+- [The Rust Book - Ownership](https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html)
+- [Rust by Example - Ownership](https://doc.rust-lang.org/rust-by-example/scope/move.html)
+- [Rustlings Exercises](https://github.com/rust-lang/rustlings)
+
+---
+
+*Questions? Reach out on [Twitter](https://twitter.com/rustlang) or join the [Rust Discord](https://discord.gg/rust-lang)*
+`;
diff --git a/tools/ui/tests/stories/fixtures/data-analysis.ts b/tools/ui/tests/stories/fixtures/data-analysis.ts
new file mode 100644
index 0000000000000000000000000000000000000000..6fec32dad637ce5f835cc513ef04ec9e779d4dab
--- /dev/null
+++ b/tools/ui/tests/stories/fixtures/data-analysis.ts
@@ -0,0 +1,124 @@
+// Data Analysis Report
+export const DATA_ANALYSIS_MD = String.raw`
+# Q4 2024 Business Analytics Report
+
+*Executive Summary • Generated on January 15, 2025*
+
+## 📊 Key Performance Indicators
+
+${'```'}
+Daily Active Users (DAU): 1.2M (+65% YoY)
+Monthly Active Users (MAU): 4.5M (+48% YoY)
+User Retention (Day 30): 68% (+12pp YoY)
+Average Session Duration: 24min (+35% YoY)
+${'```'}
+
+## 🎯 Product Performance
+
+### Feature Adoption Rates
+
+1. **AI Assistant**: 78% of users (↑ from 45%)
+2. **Collaboration Tools**: 62% of users (↑ from 38%)
+3. **Analytics Dashboard**: 54% of users (↑ from 31%)
+4. **Mobile App**: 41% of users (↑ from 22%)
+
+### Customer Satisfaction
+
+| Metric | Q4 2024 | Q3 2024 | Change |
+|--------|---------|---------|--------|
+| **NPS Score** | 72 | 68 | +4 |
+| **CSAT** | 4.6/5 | 4.4/5 | +0.2 |
+| **Support Tickets** | 2,340 | 2,890 | -19% |
+| **Resolution Time** | 4.2h | 5.1h | -18% |
+
+## 💰 Revenue Metrics
+
+### Monthly Recurring Revenue (MRR)
+
+- **Current MRR**: $2.8M (+42% YoY)
+- **New MRR**: $340K
+- **Expansion MRR**: $180K
+- **Churned MRR**: $95K
+- **Net New MRR**: $425K
+
+### Customer Acquisition
+
+${'```'}
+Cost per Acquisition (CAC): $127 (-23% YoY)
+Customer Lifetime Value: $1,840 (+31% YoY)
+LTV:CAC Ratio: 14.5:1
+Payback Period: 3.2 months
+${'```'}
+
+## 🌍 Geographic Performance
+
+### Revenue by Region
+
+1. **North America**: 45% ($1.26M)
+2. **Europe**: 32% ($896K)
+3. **Asia-Pacific**: 18% ($504K)
+4. **Other**: 5% ($140K)
+
+### Growth Opportunities
+
+- **APAC**: 89% YoY growth potential
+- **Latin America**: Emerging market entry
+- **Middle East**: Enterprise expansion
+
+## 📱 Channel Performance
+
+### Traffic Sources
+
+| Channel | Sessions | Conversion | Revenue |
+|---------|----------|------------|---------|
+| **Organic Search** | 45% | 3.2% | $1.1M |
+| **Direct** | 28% | 4.1% | $850K |
+| **Social Media** | 15% | 2.8% | $420K |
+| **Paid Ads** | 12% | 5.5% | $430K |
+
+### Marketing ROI
+
+- **Content Marketing**: 340% ROI
+- **Email Campaigns**: 280% ROI
+- **Social Media**: 190% ROI
+- **Paid Search**: 220% ROI
+
+## 🔍 User Behavior Analysis
+
+### Session Patterns
+
+- **Peak Hours**: 9-11 AM, 2-4 PM EST
+- **Mobile Usage**: 67% of sessions
+- **Average Pages/Session**: 4.8
+- **Bounce Rate**: 23% (↓ from 31%)
+
+### Feature Usage Heatmap
+
+Most used features in order:
+1. Dashboard (89% of users)
+2. Search (76% of users)
+3. Reports (64% of users)
+4. Settings (45% of users)
+5. Integrations (32% of users)
+
+## 💡 Recommendations
+
+1. **Invest** in AI capabilities (+$2M budget)
+2. **Expand** sales team in APAC region
+3. **Improve** onboarding to reduce churn
+4. **Launch** enterprise security features
+
+## Appendix
+
+### Methodology
+
+Data collected from:
+- Internal analytics (Amplitude)
+- Customer surveys (n=2,450)
+- Financial systems (NetSuite)
+- Market research (Gartner)
+
+---
+
+*Report prepared by Data Analytics Team • [View Interactive Dashboard](https://analytics.example.com)*
+`;
diff --git a/tools/ui/tests/stories/fixtures/empty.ts b/tools/ui/tests/stories/fixtures/empty.ts
new file mode 100644
index 0000000000000000000000000000000000000000..05286e7a783c6c28920e7a683f164a20da98730e
--- /dev/null
+++ b/tools/ui/tests/stories/fixtures/empty.ts
@@ -0,0 +1,2 @@
+// Empty state
+export const EMPTY_MD = '';
diff --git a/tools/ui/tests/stories/fixtures/math-formulas.ts b/tools/ui/tests/stories/fixtures/math-formulas.ts
new file mode 100644
index 0000000000000000000000000000000000000000..1355256b20ceb7f51aaa7fb6f69c3449dd28d126
--- /dev/null
+++ b/tools/ui/tests/stories/fixtures/math-formulas.ts
@@ -0,0 +1,221 @@
+/* eslint-disable no-irregular-whitespace */
+// Math Formulas Content
+export const MATH_FORMULAS_MD = String.raw`
+# Mathematical Formulas and Expressions
+
+This document demonstrates various mathematical notation and formulas that can be rendered using LaTeX syntax in markdown.
+
+## Basic Arithmetic
+
+### Addition and Summation
+$$\sum_{i=1}^{n} i = \frac{n(n+1)}{2}$$
+
+## Algebra
+
+### Quadratic Formula
+The solutions to $ax^2 + bx + c = 0$ are:
+$$x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$
+
+### Binomial Theorem
+$$(x + y)^n = \sum_{k=0}^{n} \binom{n}{k} x^{n-k} y^k$$
+
+## Calculus
+
+### Derivatives
+The derivative of $f(x) = x^n$ is:
+$$f'(x) = nx^{n-1}$$
+
+### Integration
+$$\int_a^b f(x) \, dx = F(b) - F(a)$$
+
+### Fundamental Theorem of Calculus
+$$\frac{d}{dx} \int_a^x f(t) \, dt = f(x)$$
+
+## Linear Algebra
+
+### Matrix Multiplication
+If $A$ is an $m \times n$ matrix and $B$ is an $n \times p$ matrix, then:
+$$C_{ij} = \sum_{k=1}^{n} A_{ik} B_{kj}$$
+
+### Eigenvalues and Eigenvectors
+For a square matrix $A$, if $Av = \lambda v$ for some non-zero vector $v$, then:
+- $\lambda$ is an eigenvalue
+- $v$ is an eigenvector
+
+## Statistics and Probability
+
+### Normal Distribution
+The probability density function is:
+$$f(x) = \frac{1}{\sigma\sqrt{2\pi}} e^{-\frac{1}{2}\left(\frac{x-\mu}{\sigma}\right)^2}$$
+
+### Bayes' Theorem
+$$P(A|B) = \frac{P(B|A) \cdot P(A)}{P(B)}$$
+
+### Central Limit Theorem
+For large $n$, the sample mean $\bar{X}$ is approximately:
+$$\bar{X} \sim N\left(\mu, \frac{\sigma^2}{n}\right)$$
+
+## Trigonometry
+
+### Pythagorean Identity
+$$\sin^2\theta + \cos^2\theta = 1$$
+
+### Euler's Formula
+$$e^{i\theta} = \cos\theta + i\sin\theta$$
+
+### Taylor Series for Sine
+$$\sin x = \sum_{n=0}^{\infty} \frac{(-1)^n}{(2n+1)!} x^{2n+1} = x - \frac{x^3}{3!} + \frac{x^5}{5!} - \frac{x^7}{7!} + \cdots$$
+
+## Complex Analysis
+
+### Complex Numbers
+A complex number can be written as:
+$$z = a + bi = r e^{i\theta}$$
+
+where $r = |z| = \sqrt{a^2 + b^2}$ and $\theta = \arg(z)$
+
+### Cauchy-Riemann Equations
+For a function $f(z) = u(x,y) + iv(x,y)$ to be analytic:
+$$\frac{\partial u}{\partial x} = \frac{\partial v}{\partial y}, \quad \frac{\partial u}{\partial y} = -\frac{\partial v}{\partial x}$$
+
+## Differential Equations
+
+### First-order Linear ODE
+$$\frac{dy}{dx} + P(x)y = Q(x)$$
+
+Solution: $y = e^{-\int P(x)dx}\left[\int Q(x)e^{\int P(x)dx}dx + C\right]$
+
+### Heat Equation
+$$\frac{\partial u}{\partial t} = \alpha \frac{\partial^2 u}{\partial x^2}$$
+
+## Number Theory
+
+### Prime Number Theorem
+$$\pi(x) \sim \frac{x}{\ln x}$$
+
+where $\pi(x)$ is the number of primes less than or equal to $x$.
+
+### Fermat's Last Theorem
+For $n > 2$, there are no positive integers $a$, $b$, and $c$ such that:
+$$a^n + b^n = c^n$$
+
+## Set Theory
+
+### De Morgan's Laws
+$$\overline{A \cup B} = \overline{A} \cap \overline{B}$$
+$$\overline{A \cap B} = \overline{A} \cup \overline{B}$$
+
+## Advanced Topics
+
+### Riemann Zeta Function
+$$\zeta(s) = \sum_{n=1}^{\infty} \frac{1}{n^s} = \prod_{p \text{ prime}} \frac{1}{1-p^{-s}}$$
+
+### Maxwell's Equations
+$$\nabla \cdot \mathbf{E} = \frac{\rho}{\epsilon_0}$$
+$$\nabla \cdot \mathbf{B} = 0$$
+$$\nabla \times \mathbf{E} = -\frac{\partial \mathbf{B}}{\partial t}$$
+$$\nabla \times \mathbf{B} = \mu_0\mathbf{J} + \mu_0\epsilon_0\frac{\partial \mathbf{E}}{\partial t}$$
+
+### Schrödinger Equation
+$$i\hbar\frac{\partial}{\partial t}\Psi(\mathbf{r},t) = \hat{H}\Psi(\mathbf{r},t)$$
+
+## Inline Math Examples
+
+Here are some inline mathematical expressions:
+
+- The golden ratio: $\phi = \frac{1 + \sqrt{5}}{2} \approx 1.618$
+- Euler's number: $e = \lim_{n \to \infty} \left(1 + \frac{1}{n}\right)^n$
+- Pi: $\pi = 4 \sum_{n=0}^{\infty} \frac{(-1)^n}{2n+1}$
+- Square root of 2: $\sqrt{2} = 1.41421356...$
+
+## Fractions and Radicals
+
+Complex fraction: $\frac{\frac{a}{b} + \frac{c}{d}}{\frac{e}{f} - \frac{g}{h}}$
+
+Nested radicals: $\sqrt{2 + \sqrt{3 + \sqrt{4 + \sqrt{5}}}}$
+
+## Summations and Products
+
+### Geometric Series
+$$\sum_{n=0}^{\infty} ar^n = \frac{a}{1-r} \quad \text{for } |r| < 1$$
+
+### Product Notation
+$$n! = \prod_{k=1}^{n} k$$
+
+### Double Summation
+$$\sum_{i=1}^{m} \sum_{j=1}^{n} a_{ij}$$
+
+## Limits
+
+$$\lim_{x \to 0} \frac{\sin x}{x} = 1$$
+
+$$\lim_{n \to \infty} \left(1 + \frac{x}{n}\right)^n = e^x$$
+
+## Further Bracket Styles and Amounts
+
+- \( \mathrm{GL}_2(\mathbb{F}_7) \): Group of invertible matrices with entries in \(\mathbb{F}_7\).
+- Some kernel of \(\mathrm{SL}_2(\mathbb{F}_7)\):
+ \[
+ \left\{ \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix}, \begin{pmatrix} -1 & 0 \\ 0 & -1 \end{pmatrix} \right\} = \{\pm I\}
+ \]
+- Algebra:
+\[
+x = \frac{-b \pm \sqrt{\,b^{2}-4ac\,}}{2a}
+\]
+- $100 and $12.99 are amounts, not LaTeX.
+- I have $10, $3.99 and $x + y$ and $100x$. The amount is $2,000.
+- Emma buys 2 cupcakes for $3 each and 1 cookie for $1.50. How much money does she spend in total?
+- Maria has $20. She buys a notebook for $4.75 and a pack of pencils for $3.25. How much change does she receive?
+- 1 kg の質量は
+ \[
+ E = (1\ \text{kg}) \times (3.0 \times 10^8\ \text{m/s})^2 \approx 9.0 \times 10^{16}\ \text{J}
+ \]
+ というエネルギーに相当します。これは約 21 百万トンの TNT が爆発したときのエネルギーに匹敵します。
+- Algebra: \[
+x = \frac{-b \pm \sqrt{\,b^{2}-4ac\,}}{2a}
+\]
+- Algebraic topology, Homotopy Groups of $\mathbb{S}^3$:
+$$\pi_n(\mathbb{S}^3) = \begin{cases}
+\mathbb{Z} & n = 3 \\
+0 & n > 3, n \neq 4 \\
+\mathbb{Z}_2 & n = 4 \\
+\end{cases}$$
+- Spacer preceded by backslash:
+\[
+\boxed{
+\begin{aligned}
+N_{\text{att}}^{\text{(MHA)}} &=
+h \bigl[\, d_{\text{model}}\;d_{k} + d_{\text{model}}\;d_{v}\, \bigr] && (\text{Q,K,V の重み})\\
+&\quad+ h(d_{k}+d_{k}+d_{v}) && (\text{バイアス Q,K,V)}\\[4pt]
+&\quad+ (h d_{v})\, d_{\text{model}} && (\text{出力射影 }W^{O})\\
+&\quad+ d_{\text{model}} && (\text{バイアス }b^{O})
+\end{aligned}}
+\]
+
+## Formulas in a Table
+
+| Area | Expression | Comment |
+|------|------------|---------|
+| **Algebra** | \[
+x = \frac{-b \pm \sqrt{\,b^{2}-4ac\,}}{2a}
+\] | Quadratic formula |
+| | \[
+(a+b)^{n} = \sum_{k=0}^{n}\binom{n}{k}\,a^{\,n-k}\,b^{\,k}
+\] | Binomial theorem |
+| | \(\displaystyle \prod_{k=1}^{n}k = n! \) | Factorial definition |
+| **Geometry** | \( \mathbf{a}\cdot \mathbf{b} = \|\mathbf{a}\|\,\|\mathbf{b}\|\,\cos\theta \) | Dot product & angle |
+
+## No math (but chemical)
+
+Balanced chemical reaction with states:
+
+\[
+\ce{2H2(g) + O2(g) -> 2H2O(l)}
+\]
+
+The standard enthalpy change for the reaction is: $\Delta H^\circ = \pu{-572 kJ mol^{-1}}$.
+
+---
+
+*This document showcases various mathematical notation and formulas that can be rendered in markdown using LaTeX syntax.*
+`;
diff --git a/tools/ui/tests/stories/fixtures/readme.ts b/tools/ui/tests/stories/fixtures/readme.ts
new file mode 100644
index 0000000000000000000000000000000000000000..e8b573d6c4e3f9ecfb94e44d644adac08eeeed51
--- /dev/null
+++ b/tools/ui/tests/stories/fixtures/readme.ts
@@ -0,0 +1,136 @@
+// README Content
+export const README_MD = String.raw`
+# 🚀 Awesome Web Framework
+
+[](https://www.npmjs.com/package/awesome-framework)
+[](https://github.com/awesome/framework/actions)
+[](https://codecov.io/gh/awesome/framework)
+[](https://opensource.org/licenses/MIT)
+
+> A modern, fast, and flexible web framework for building scalable applications
+
+## ✨ Features
+
+- 🎯 **Type-Safe** - Full TypeScript support out of the box
+- ⚡ **Lightning Fast** - Built on Vite for instant HMR
+- 📦 **Zero Config** - Works out of the box for most use cases
+- 🎨 **Flexible** - Unopinionated with sensible defaults
+- 🔧 **Extensible** - Plugin system for custom functionality
+- 📱 **Responsive** - Mobile-first approach
+- 🌍 **i18n Ready** - Built-in internationalization
+- 🔒 **Secure** - Security best practices by default
+
+## 📦 Installation
+
+${'```'}bash
+npm install awesome-framework
+# or
+yarn add awesome-framework
+# or
+pnpm add awesome-framework
+${'```'}
+
+## 🚀 Quick Start
+
+### Create a new project
+
+${'```'}bash
+npx create-awesome-app my-app
+cd my-app
+npm run dev
+${'```'}
+
+### Basic Example
+
+${'```'}javascript
+import { createApp } from 'awesome-framework';
+
+const app = createApp({
+ port: 3000,
+ middleware: ['cors', 'helmet', 'compression']
+});
+
+app.get('/', (req, res) => {
+ res.json({ message: 'Hello World!' });
+});
+
+app.listen(() => {
+ console.log('Server running on http://localhost:3000');
+});
+${'```'}
+
+## 📖 Documentation
+
+### Core Concepts
+
+- [Getting Started](https://docs.awesome.dev/getting-started)
+- [Configuration](https://docs.awesome.dev/configuration)
+- [Routing](https://docs.awesome.dev/routing)
+- [Middleware](https://docs.awesome.dev/middleware)
+- [Database](https://docs.awesome.dev/database)
+- [Authentication](https://docs.awesome.dev/authentication)
+
+### Advanced Topics
+
+- [Performance Optimization](https://docs.awesome.dev/performance)
+- [Deployment](https://docs.awesome.dev/deployment)
+- [Testing](https://docs.awesome.dev/testing)
+- [Security](https://docs.awesome.dev/security)
+
+## 🛠️ Development
+
+### Prerequisites
+
+- Node.js >= 18
+- pnpm >= 8
+
+### Setup
+
+${'```'}bash
+git clone https://github.com/awesome/framework.git
+cd framework
+pnpm install
+pnpm dev
+${'```'}
+
+### Testing
+
+${'```'}bash
+pnpm test # Run unit tests
+pnpm test:e2e # Run end-to-end tests
+pnpm test:watch # Run tests in watch mode
+${'```'}
+
+## 🤝 Contributing
+
+We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.
+
+### Contributors
+
+
+
+
+
+## 📊 Benchmarks
+
+| Framework | Requests/sec | Latency (ms) | Memory (MB) |
+|-----------|-------------|--------------|-------------|
+| **Awesome** | **45,230** | **2.1** | **42** |
+| Express | 28,450 | 3.5 | 68 |
+| Fastify | 41,200 | 2.3 | 48 |
+| Koa | 32,100 | 3.1 | 52 |
+
+*Benchmarks performed on MacBook Pro M2, Node.js 20.x*
+
+## 📝 License
+
+MIT © [Awesome Team](https://github.com/awesome)
+
+## 🙏 Acknowledgments
+
+Special thanks to all our sponsors and contributors who make this project possible.
+
+---
+
+**[Website](https://awesome.dev)** • **[Documentation](https://docs.awesome.dev)** • **[Discord](https://discord.gg/awesome)** • **[Twitter](https://twitter.com/awesomeframework)**
+`;
diff --git a/tools/ui/tests/stories/fixtures/storybook-mocks.ts b/tools/ui/tests/stories/fixtures/storybook-mocks.ts
new file mode 100644
index 0000000000000000000000000000000000000000..ac9fb63cd0770548e5703789889008aa5c4adb1a
--- /dev/null
+++ b/tools/ui/tests/stories/fixtures/storybook-mocks.ts
@@ -0,0 +1,87 @@
+import { modelsStore } from '$lib/stores/models/index.svelte';
+import { serverStore } from '$lib/stores/server.svelte';
+
+/**
+ * Mock server properties for Storybook testing
+ * This utility allows setting mock server configurations without polluting production code
+ */
+export function mockServerProps(props: Partial): void {
+ // Reset any pointer-events from previous tests (dropdown cleanup)
+ const body = document.querySelector('body');
+
+ if (body) body.style.pointerEvents = '';
+
+ // Directly set the props for testing purposes
+ (serverStore as unknown as { props: ApiLlamaCppServerProps }).props = {
+ modalities: {
+ audio: props.modalities?.audio ?? false,
+ video: props.modalities?.video ?? false,
+ vision: props.modalities?.vision ?? false
+ },
+ model_path: props.model_path || 'test-model',
+ ...props
+ } as ApiLlamaCppServerProps;
+
+ // Set router mode role so activeModelId can be set
+ (serverStore as unknown as { props: ApiLlamaCppServerProps }).props.role = 'ROUTER';
+
+ // Also mock modelsStore methods for modality checking
+ const vision = props.modalities?.vision ?? false;
+ const audio = props.modalities?.audio ?? false;
+ const video = props.modalities?.video ?? false;
+
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (modelsStore as any).modelSupportsVision = () => vision;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (modelsStore as any).modelSupportsAudio = () => audio;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (modelsStore as any).modelSupportsVideo = () => video;
+
+ // Mock models list with a test model so activeModelId can be resolved
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (modelsStore as any).models = [
+ {
+ id: 'test-model',
+ model: 'test-model',
+ name: 'Test Model'
+ }
+ ];
+
+ // Mock selectedModelId
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (modelsStore as any).selectedModelId = 'test-model';
+}
+
+/**
+ * Reset server store to clean state for testing
+ */
+export function resetServerStore(): void {
+ (serverStore as unknown as { props: ApiLlamaCppServerProps }).props = {
+ modalities: {
+ audio: false,
+ video: false,
+ vision: false
+ },
+ model_path: ''
+ } as ApiLlamaCppServerProps;
+ (serverStore as unknown as { error: string }).error = '';
+ (serverStore as unknown as { loading: boolean }).loading = false;
+}
+
+/**
+ * Common mock configurations for Storybook stories
+ */
+export const mockConfigs = {
+ audioOnly: {
+ modalities: { audio: true, vision: false }
+ },
+ bothModalities: {
+ modalities: { audio: true, vision: true }
+ },
+ noModalities: {
+ modalities: { audio: false, video: false, vision: false }
+ },
+ visionOnly: {
+ modalities: { audio: false, vision: true }
+ }
+} as const;
diff --git a/tools/ui/tests/unit/abort.test.ts b/tools/ui/tests/unit/abort.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..b8b41667d2c8c8a06af1dfae94b1e8abaf514009
--- /dev/null
+++ b/tools/ui/tests/unit/abort.test.ts
@@ -0,0 +1,58 @@
+import { isAbortError } from '$lib/utils/abort';
+import { describe, expect, it } from 'vitest';
+
+describe('isAbortError', () => {
+ it('returns false for null, undefined and non-error values', () => {
+ expect(isAbortError(null)).toBe(false);
+ expect(isAbortError(undefined)).toBe(false);
+ expect(isAbortError('string error')).toBe(false);
+ expect(isAbortError({ name: 'AbortError' })).toBe(false);
+ expect(isAbortError(42)).toBe(false);
+ });
+
+ it('returns true for DOMException with AbortError name', () => {
+ const err = new DOMException('Operation was aborted', 'AbortError');
+
+ expect(isAbortError(err)).toBe(true);
+ });
+
+ it('returns true for plain Error with AbortError name', () => {
+ const err = new Error('aborted');
+
+ err.name = 'AbortError';
+ expect(isAbortError(err)).toBe(true);
+ });
+
+ it('returns false for unrelated Error instances', () => {
+ expect(isAbortError(new Error('something failed'))).toBe(false);
+ expect(isAbortError(new TypeError('not related'))).toBe(false);
+ expect(isAbortError(new RangeError('out of range'))).toBe(false);
+ });
+
+ it('recognizes Firefox TypeError "Error in input stream" emitted at page unload', () => {
+ expect(isAbortError(new TypeError('Error in input stream'))).toBe(true);
+ expect(isAbortError(new TypeError('TypeError: Error in input stream'))).toBe(true);
+ });
+
+ it('recognizes Safari "The network connection was lost" during transient drop', () => {
+ expect(isAbortError(new TypeError('The network connection was lost.'))).toBe(true);
+ });
+
+ it('recognizes Safari "Load failed" during page navigation', () => {
+ expect(isAbortError(new TypeError('Load failed'))).toBe(true);
+ });
+
+ it('does NOT recognize generic TypeError messages as aborts', () => {
+ // matching too broadly would hide real bugs, the predicate must stay conservative
+ expect(isAbortError(new TypeError('Failed to fetch'))).toBe(false);
+ expect(isAbortError(new TypeError('Cannot read property of undefined'))).toBe(false);
+ expect(isAbortError(new TypeError('NetworkError when attempting to fetch resource'))).toBe(
+ false
+ );
+ });
+
+ it('is case insensitive on the matched substrings', () => {
+ expect(isAbortError(new TypeError('error in INPUT STREAM'))).toBe(true);
+ expect(isAbortError(new TypeError('the network connection WAS LOST'))).toBe(true);
+ });
+});
diff --git a/tools/ui/tests/unit/agentic-hotpath.bench.ts b/tools/ui/tests/unit/agentic-hotpath.bench.ts
new file mode 100644
index 0000000000000000000000000000000000000000..24dcb48911f86eed660cebed324cdaaa739712a7
--- /dev/null
+++ b/tools/ui/tests/unit/agentic-hotpath.bench.ts
@@ -0,0 +1,243 @@
+// Microbenchmarks for the functions on the agentic-thread streaming hot path.
+//
+// Every function here is invoked from a `$derived` that is invalidated on each
+// streamed token, for every tool-call section in the message. These numbers give
+// the per-call cost; multiply by (tokens x sections) for the real damage.
+//
+// Run: npx vitest bench --project=unit tests/unit/agentic-hotpath.bench.ts
+
+import { classifyToolResult, parseToolResultWithMedia } from '$lib/utils/agentic';
+import { detectIncompleteCodeBlock, highlightCode } from '$lib/utils/code';
+import { computeLineDiff } from '$lib/utils/compute-line-diff';
+import { preprocessLaTeX } from '$lib/utils/latex-protection';
+import { parsePartialJsonArgs } from '$lib/utils/parse-partial-json-args';
+import { extractSearchQuery, extractSearchResults } from '$lib/utils/search-results';
+import { all as lowlightAll } from 'lowlight';
+import rehypeHighlight from 'rehype-highlight';
+import rehypeKatex from 'rehype-katex';
+import rehypeStringify from 'rehype-stringify';
+import { remark } from 'remark';
+import remarkBreaks from 'remark-breaks';
+import remarkGfm from 'remark-gfm';
+import remarkMath from 'remark-math';
+import remarkRehype from 'remark-rehype';
+import { bench, describe } from 'vitest';
+
+// --- fixtures -------------------------------------------------------------
+
+function lines(n: number, seed: string): string {
+ const out: string[] = [];
+
+ for (let i = 0; i < n; i++) out.push(`${seed} line ${i} const value_${i} = compute(${i});`);
+
+ return out.join('\n');
+}
+
+const SHELL_OUTPUT_1KB = lines(12, 'out');
+const SHELL_OUTPUT_200KB = lines(2600, 'out');
+const SHELL_OUTPUT_2MB = lines(26000, 'out');
+// Realistic exec_shell_command result: the exit-code marker is the final line,
+// which is what the un-anchored EXIT_CODE regex has to scan the whole blob for.
+const SHELL_2MB_WITH_EXIT = `${SHELL_OUTPUT_2MB}\n[exit code: 0]`;
+const EDIT_OLD_400 = lines(400, 'old');
+const EDIT_NEW_400 = lines(400, 'new');
+const EDIT_OLD_50 = lines(50, 'old');
+const EDIT_NEW_50 = lines(50, 'new');
+const WRITE_FILE_ARGS = JSON.stringify({
+ content: lines(1500, 'src'),
+ path: '/src/lib/thing.ts'
+});
+const MARKDOWN_50KB = Array.from(
+ { length: 400 },
+ (_, i) =>
+ `## Section ${i}\n\nSome **bold** prose with a [link](https://example.com) and \`inline\` code.\n\n- bullet one\n- bullet two\n\n\`\`\`ts\nconst x${i} = ${i};\n\`\`\`\n`
+).join('\n');
+const CODE_BLOCK_5KB = lines(60, 'code');
+
+// --- A: computeLineDiff (O(m*n) LCS, allocates a full matrix) --------------
+
+describe('computeLineDiff', () => {
+ bench('50 x 50 lines', () => {
+ computeLineDiff(EDIT_OLD_50, EDIT_NEW_50);
+ });
+
+ bench('400 x 400 lines', () => {
+ computeLineDiff(EDIT_OLD_400, EDIT_NEW_400);
+ });
+});
+
+// --- B: the unified processor, rebuilt per call ---------------------------
+// Mirrors MarkdownContent.svelte:144-176. The local rehype/remark plugins are
+// omitted (they pull in browser-only modules); rehypeHighlight + lowlightAll is
+// the dominant term, so this is a lower bound on the real cost.
+
+function buildProcessor() {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ let proc: any = remark().use(remarkGfm);
+
+ proc = proc.use(remarkMath).use(remarkBreaks).use(remarkRehype).use(rehypeKatex);
+
+ return proc.use(rehypeHighlight, { languages: lowlightAll }).use(rehypeStringify, {
+ allowDangerousHtml: true
+ });
+}
+
+describe('markdown processor', () => {
+ bench('build processor (per processMarkdown call, x2)', () => {
+ buildProcessor();
+ });
+
+ const prebuilt = buildProcessor();
+
+ bench('parse 50KB markdown with a prebuilt processor', () => {
+ prebuilt.parse(MARKDOWN_50KB);
+ });
+});
+
+// Isolates the O(n^2) term measured in Tier 1: processMarkdown re-parses the
+// WHOLE accumulated string every frame, while only the last block can have
+// changed. If parse() dominates at these sizes, incremental parsing (re-parsing
+// only the tail after the last stable block) is the fix; if not, the cost is
+// downstream in transform/stringify/DOM.
+describe('markdown parse scaling (whole-string reparse per frame)', () => {
+ const proc = buildProcessor();
+ const prose = (kb: number) =>
+ Array.from(
+ { length: Math.ceil((kb * 1024) / 64) },
+ (_, i) => `The quick brown fox jumps over the lazy dog. Sentence ${i}.`
+ ).join(' ');
+ const MD_3KB = prose(3);
+ const MD_11KB = prose(11);
+ const MD_26KB = prose(26);
+
+ bench('parse 3KB', () => {
+ proc.parse(MD_3KB);
+ });
+
+ bench('parse 11KB', () => {
+ proc.parse(MD_11KB);
+ });
+
+ bench('parse 26KB', () => {
+ proc.parse(MD_26KB);
+ });
+
+ bench('parse only a 200-char tail (proposed incremental)', () => {
+ proc.parse(MD_26KB.slice(-200));
+ });
+});
+
+// processMarkdown runs these over the WHOLE accumulated string every frame too,
+// before parse() even starts. Measure them before assuming parse is the target.
+describe('other whole-string passes per frame', () => {
+ const prose = (kb: number) =>
+ Array.from(
+ { length: Math.ceil((kb * 1024) / 64) },
+ (_, i) => `The quick brown fox jumps over the lazy dog. Sentence ${i}.`
+ ).join(' ');
+ const MD_3KB = prose(3);
+ const MD_11KB = prose(11);
+ const MD_26KB = prose(26);
+ const MD_26KB_LATEX = `${MD_26KB} and some math $x^2 + y^2 = z^2$ inline.`;
+
+ bench('preprocessLaTeX 3KB (no latex present)', () => {
+ preprocessLaTeX(MD_3KB);
+ });
+
+ bench('preprocessLaTeX 11KB (no latex present)', () => {
+ preprocessLaTeX(MD_11KB);
+ });
+
+ bench('preprocessLaTeX 26KB (no latex present)', () => {
+ preprocessLaTeX(MD_26KB);
+ });
+
+ bench('preprocessLaTeX 26KB (latex present)', () => {
+ preprocessLaTeX(MD_26KB_LATEX);
+ });
+
+ bench('detectIncompleteCodeBlock 26KB', () => {
+ detectIncompleteCodeBlock(MD_26KB);
+ });
+});
+
+// --- C: extractSearchResults, run for EVERY tool of every type ------------
+
+describe('extractSearchResults (only .length > 0 is consumed)', () => {
+ bench('1KB non-search tool result', () => {
+ extractSearchResults(SHELL_OUTPUT_1KB);
+ });
+
+ bench('200KB non-search tool result', () => {
+ extractSearchResults(SHELL_OUTPUT_200KB);
+ });
+
+ bench('2MB non-search tool result', () => {
+ extractSearchResults(SHELL_OUTPUT_2MB);
+ });
+});
+
+describe('extractSearchQuery', () => {
+ bench('write_file args (throws on the JSON.parse path)', () => {
+ extractSearchQuery(WRITE_FILE_ARGS);
+ });
+});
+
+// --- E: the un-anchored exit-code regex -----------------------------------
+// Reproduced inline so the bench is independent of the current call site.
+
+const EXIT_CODE_TAIL = /\[exit code: (-?\d+)\]\s*$/;
+
+describe('exit-code regex', () => {
+ bench('whole 2MB blob (current behaviour)', () => {
+ SHELL_2MB_WITH_EXIT.match(EXIT_CODE_TAIL);
+ });
+
+ bench('last 64 chars only (proposed)', () => {
+ SHELL_2MB_WITH_EXIT.slice(-64).match(EXIT_CODE_TAIL);
+ });
+});
+
+// --- per-line result parsers ----------------------------------------------
+
+describe('parseToolResultWithMedia', () => {
+ bench('1KB', () => {
+ parseToolResultWithMedia(SHELL_OUTPUT_1KB, []);
+ });
+
+ bench('200KB', () => {
+ parseToolResultWithMedia(SHELL_OUTPUT_200KB, []);
+ });
+
+ bench('2MB', () => {
+ parseToolResultWithMedia(SHELL_OUTPUT_2MB, []);
+ });
+});
+
+describe('classifyToolResult', () => {
+ bench('200KB plain text (falls through to looksLikeMarkdown)', () => {
+ classifyToolResult(SHELL_OUTPUT_200KB);
+ });
+});
+
+describe('parsePartialJsonArgs', () => {
+ bench('write_file args, ~60KB (char-by-char scan)', () => {
+ parsePartialJsonArgs(WRITE_FILE_ARGS);
+ });
+});
+
+// --- F / I: highlight.js ---------------------------------------------------
+
+describe('highlightCode', () => {
+ bench('short bash command (title row, per token)', () => {
+ highlightCode('grep -rn "foo" src/ | head -50', 'bash');
+ });
+
+ bench('5KB known language', () => {
+ highlightCode(CODE_BLOCK_5KB, 'typescript');
+ });
+
+ bench('5KB unknown language -> highlightAuto', () => {
+ highlightCode(CODE_BLOCK_5KB, 'not-a-language');
+ });
+});
diff --git a/tools/ui/tests/unit/agentic-sections.test.ts b/tools/ui/tests/unit/agentic-sections.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..fdb3b221780cee1d50f222e825314b11d101cb32
--- /dev/null
+++ b/tools/ui/tests/unit/agentic-sections.test.ts
@@ -0,0 +1,403 @@
+import { AgenticSectionType, MessageRole } from '$lib/enums';
+import type { ApiChatCompletionToolCall } from '$lib/types/api';
+import type { DatabaseMessage } from '$lib/types/database';
+import { deriveAgenticSections, hasAgenticContent } from '$lib/utils/agentic';
+import { describe, expect, it } from 'vitest';
+
+function makeAssistant(overrides: Partial = {}): DatabaseMessage {
+ return {
+ children: [],
+ content: overrides.content ?? '',
+ convId: 'conv-1',
+ id: overrides.id ?? 'ast-1',
+ parent: null,
+ role: MessageRole.ASSISTANT,
+ timestamp: Date.now(),
+ type: 'text',
+ ...overrides
+ } as DatabaseMessage;
+}
+
+function makeToolMsg(overrides: Partial = {}): DatabaseMessage {
+ return {
+ children: [],
+ content: overrides.content ?? 'tool result',
+ convId: 'conv-1',
+ id: overrides.id ?? 'tool-1',
+ parent: null,
+ role: MessageRole.TOOL,
+ timestamp: Date.now(),
+ toolCallId: overrides.toolCallId ?? 'call_1',
+ type: 'text',
+ ...overrides
+ } as DatabaseMessage;
+}
+
+describe('deriveAgenticSections', () => {
+ it('returns empty array for assistant with no content', () => {
+ const msg = makeAssistant({ content: '' });
+ const sections = deriveAgenticSections(msg);
+
+ expect(sections).toEqual([]);
+ });
+
+ it('returns text section for simple assistant message', () => {
+ const msg = makeAssistant({ content: 'Hello world' });
+ const sections = deriveAgenticSections(msg);
+
+ expect(sections).toHaveLength(1);
+ expect(sections[0].type).toBe(AgenticSectionType.TEXT);
+ expect(sections[0].content).toBe('Hello world');
+ });
+
+ it('returns reasoning + text for message with reasoning', () => {
+ const msg = makeAssistant({
+ content: 'Answer is 4.',
+ reasoningContent: 'Let me think...'
+ });
+ const sections = deriveAgenticSections(msg);
+
+ expect(sections).toHaveLength(2);
+ expect(sections[0].type).toBe(AgenticSectionType.REASONING);
+ expect(sections[0].content).toBe('Let me think...');
+ expect(sections[1].type).toBe(AgenticSectionType.TEXT);
+ });
+
+ it('single turn: assistant with tool calls and results', () => {
+ const msg = makeAssistant({
+ content: 'Let me check.',
+ toolCalls: JSON.stringify([
+ {
+ function: { arguments: '{"q":"test"}', name: 'search' },
+ id: 'call_1',
+ type: 'function'
+ }
+ ])
+ });
+ const toolResult = makeToolMsg({
+ content: 'Found 3 results',
+ toolCallId: 'call_1'
+ });
+ const sections = deriveAgenticSections(msg, [toolResult]);
+
+ expect(sections).toHaveLength(2);
+ expect(sections[0].type).toBe(AgenticSectionType.TEXT);
+ expect(sections[1].type).toBe(AgenticSectionType.TOOL_CALL);
+ expect(sections[1].toolName).toBe('search');
+ expect(sections[1].toolResult).toBe('Found 3 results');
+ });
+
+ it('single turn: pending tool call without result', () => {
+ const msg = makeAssistant({
+ toolCalls: JSON.stringify([
+ { function: { arguments: '{}', name: 'bash' }, id: 'call_1', type: 'function' }
+ ])
+ });
+ const sections = deriveAgenticSections(msg, [], [], true);
+
+ expect(sections).toHaveLength(1);
+ expect(sections[0].type).toBe(AgenticSectionType.TOOL_CALL_PENDING);
+ expect(sections[0].toolName).toBe('bash');
+ });
+
+ it('chat-streaming write_file surfaces as TOOL_CALL_PENDING with partial toolArgs (not TOOL_CALL_STREAMING)', () => {
+ // Regression: while the LLM is emitting a write_file tool call's
+ // args, `chat.svelte.ts` JSON-encodes the partial tool-call array on
+ // every chunk, so `parseToolCalls` succeeds and the section is
+ // classified TOOL_CALL_PENDING - not TOOL_CALL_STREAMING (which is
+ // only produced from the `streamingToolCalls` parameter, never set
+ // by current UI callers). Streaming-only UI like auto-scroll in the
+ // code block must still trigger, driven by `isStreaming && (isPending
+ // || isStreamingCall)`, not `isStreamingCall` alone.
+ const partialArgs = '{"path":"/Users/fifa2026.html","content":" {
+ const assistant1 = makeAssistant({
+ content: 'Turn 1 text',
+ id: 'ast-1',
+ toolCalls: JSON.stringify([
+ {
+ function: { arguments: '{"q":"foo"}', name: 'search' },
+ id: 'call_1',
+ type: 'function'
+ }
+ ])
+ });
+ const tool1 = makeToolMsg({ content: 'result 1', id: 'tool-1', toolCallId: 'call_1' });
+ const assistant2 = makeAssistant({
+ content: 'Final answer based on results.',
+ id: 'ast-2'
+ });
+ // toolMessages contains both tool result and continuation assistant
+ const sections = deriveAgenticSections(assistant1, [tool1, assistant2]);
+
+ expect(sections).toHaveLength(3);
+ // Turn 1
+ expect(sections[0].type).toBe(AgenticSectionType.TEXT);
+ expect(sections[0].content).toBe('Turn 1 text');
+ expect(sections[1].type).toBe(AgenticSectionType.TOOL_CALL);
+ expect(sections[1].toolName).toBe('search');
+ expect(sections[1].toolResult).toBe('result 1');
+ // Turn 2 (final)
+ expect(sections[2].type).toBe(AgenticSectionType.TEXT);
+ expect(sections[2].content).toBe('Final answer based on results.');
+ });
+
+ it('multi-turn: three turns with tool calls', () => {
+ const assistant1 = makeAssistant({
+ content: '',
+ id: 'ast-1',
+ toolCalls: JSON.stringify([
+ {
+ function: { arguments: '{}', name: 'list_files' },
+ id: 'call_1',
+ type: 'function'
+ }
+ ])
+ });
+ const tool1 = makeToolMsg({ content: 'file1 file2', id: 'tool-1', toolCallId: 'call_1' });
+ const assistant2 = makeAssistant({
+ content: 'Reading file1...',
+ id: 'ast-2',
+ toolCalls: JSON.stringify([
+ {
+ function: { arguments: '{"path":"file1"}', name: 'read_file' },
+ id: 'call_2',
+ type: 'function'
+ }
+ ])
+ });
+ const tool2 = makeToolMsg({
+ content: 'contents of file1',
+ id: 'tool-2',
+ toolCallId: 'call_2'
+ });
+ const assistant3 = makeAssistant({
+ content: 'Here is the analysis.',
+ id: 'ast-3',
+ reasoningContent: 'The file contains...'
+ });
+ const sections = deriveAgenticSections(assistant1, [tool1, assistant2, tool2, assistant3]);
+
+ // Turn 1: tool_call (no text since content is empty)
+ // Turn 2: text + tool_call
+ // Turn 3: reasoning + text
+ expect(sections).toHaveLength(5);
+ expect(sections[0].type).toBe(AgenticSectionType.TOOL_CALL);
+ expect(sections[0].toolName).toBe('list_files');
+ expect(sections[1].type).toBe(AgenticSectionType.TEXT);
+ expect(sections[1].content).toBe('Reading file1...');
+ expect(sections[2].type).toBe(AgenticSectionType.TOOL_CALL);
+ expect(sections[2].toolName).toBe('read_file');
+ expect(sections[3].type).toBe(AgenticSectionType.REASONING);
+ expect(sections[4].type).toBe(AgenticSectionType.TEXT);
+ expect(sections[4].content).toBe('Here is the analysis.');
+ });
+
+ it('returns REASONING_PENDING when streaming with only reasoning content', () => {
+ const msg = makeAssistant({
+ reasoningContent: 'Let me think about this...'
+ });
+ const sections = deriveAgenticSections(msg, [], [], true);
+
+ expect(sections).toHaveLength(1);
+ expect(sections[0].type).toBe(AgenticSectionType.REASONING_PENDING);
+ expect(sections[0].content).toBe('Let me think about this...');
+ });
+
+ it('returns REASONING (not pending) when streaming but text content has appeared', () => {
+ const msg = makeAssistant({
+ content: 'The answer is',
+ reasoningContent: 'Let me think...'
+ });
+ const sections = deriveAgenticSections(msg, [], [], true);
+
+ expect(sections).toHaveLength(2);
+ expect(sections[0].type).toBe(AgenticSectionType.REASONING);
+ expect(sections[1].type).toBe(AgenticSectionType.TEXT);
+ });
+
+ it('returns REASONING (not pending) when not streaming', () => {
+ const msg = makeAssistant({
+ reasoningContent: 'Let me think...'
+ });
+ const sections = deriveAgenticSections(msg, [], [], false);
+
+ expect(sections).toHaveLength(1);
+ expect(sections[0].type).toBe(AgenticSectionType.REASONING);
+ });
+
+ it('multi-turn: streaming tool calls on last turn', () => {
+ const assistant1 = makeAssistant({
+ toolCalls: JSON.stringify([
+ { function: { arguments: '{}', name: 'search' }, id: 'call_1', type: 'function' }
+ ])
+ });
+ const tool1 = makeToolMsg({ content: 'result', toolCallId: 'call_1' });
+ const assistant2 = makeAssistant({ content: '', id: 'ast-2' });
+ const streamingToolCalls: ApiChatCompletionToolCall[] = [
+ { function: { arguments: '{"pa', name: 'write_file' }, id: 'call_2', type: 'function' }
+ ];
+ const sections = deriveAgenticSections(assistant1, [tool1, assistant2], streamingToolCalls);
+
+ // Turn 1: tool_call
+ // Turn 2 (streaming): streaming tool call
+ expect(sections.some((s) => s.type === AgenticSectionType.TOOL_CALL)).toBe(true);
+ expect(sections.some((s) => s.type === AgenticSectionType.TOOL_CALL_STREAMING)).toBe(true);
+ });
+});
+
+describe('hasAgenticContent', () => {
+ it('returns false for plain assistant', () => {
+ const msg = makeAssistant({ content: 'Just text' });
+
+ expect(hasAgenticContent(msg)).toBe(false);
+ });
+
+ it('returns true when message has toolCalls', () => {
+ const msg = makeAssistant({
+ toolCalls: JSON.stringify([
+ { function: { arguments: '{}', name: 'test' }, id: 'call_1', type: 'function' }
+ ])
+ });
+
+ expect(hasAgenticContent(msg)).toBe(true);
+ });
+
+ it('returns true when toolMessages are provided', () => {
+ const msg = makeAssistant();
+ const tool = makeToolMsg();
+
+ expect(hasAgenticContent(msg, [tool])).toBe(true);
+ });
+
+ it('returns false for empty toolCalls JSON', () => {
+ const msg = makeAssistant({ toolCalls: '[]' });
+
+ expect(hasAgenticContent(msg)).toBe(false);
+ });
+});
+
+// The turn-section cache: completed turns are immutable, so repeated
+// derivations return the same section objects - which is what keeps tool
+// block props stable while another turn streams. Every field the cache
+// compares must invalidate it; a miss here renders stale content.
+
+describe('completed turn section reuse', () => {
+ const toolCallsJson = JSON.stringify([
+ { function: { arguments: '{"path":"/a"}', name: 'test' }, id: 'call_1', type: 'function' }
+ ]);
+
+ function makeSession() {
+ return {
+ anchor: makeAssistant({
+ content: 'answer',
+ reasoningContent: 'thinking',
+ toolCalls: toolCallsJson
+ }),
+ tools: [makeToolMsg({ content: 'tool result', extra: [{ type: 'file' } as never] })]
+ };
+ }
+
+ it('returns the same section objects for unchanged inputs', () => {
+ const { anchor, tools } = makeSession();
+ const first = deriveAgenticSections(anchor, tools, [], false);
+ const second = deriveAgenticSections(anchor, tools, [], false);
+
+ expect(second[0]).toBe(first[0]);
+ expect(second[1]).toBe(first[1]);
+ });
+
+ it('recomputes when the assistant content changes', () => {
+ const { anchor, tools } = makeSession();
+ const first = deriveAgenticSections(anchor, tools, [], false);
+
+ anchor.content = 'edited';
+ const second = deriveAgenticSections(anchor, tools, [], false);
+
+ expect(second).not.toBe(first);
+ expect(second.some((s) => s.type === AgenticSectionType.TEXT && s.content === 'edited')).toBe(
+ true
+ );
+ });
+
+ it('recomputes when reasoning content changes', () => {
+ const { anchor, tools } = makeSession();
+ const first = deriveAgenticSections(anchor, tools, [], false);
+
+ anchor.reasoningContent = 'new thinking';
+ const second = deriveAgenticSections(anchor, tools, [], false);
+
+ expect(second).not.toBe(first);
+ });
+
+ it('recomputes when toolCalls change', () => {
+ const { anchor, tools } = makeSession();
+ const first = deriveAgenticSections(anchor, tools, [], false);
+
+ anchor.toolCalls = '[]';
+ const second = deriveAgenticSections(anchor, tools, [], false);
+
+ expect(second).not.toBe(first);
+ });
+
+ it('recomputes when a tool result or its extras change', () => {
+ const { anchor, tools } = makeSession();
+ const first = deriveAgenticSections(anchor, tools, [], false);
+
+ tools[0].content = 'new tool result';
+ expect(deriveAgenticSections(anchor, tools, [], false)).not.toBe(first);
+
+ const firstAfterContent = deriveAgenticSections(anchor, tools, [], false);
+
+ tools[0].extra = [{ type: 'image' } as never];
+ expect(deriveAgenticSections(anchor, tools, [], false)).not.toBe(firstAfterContent);
+ });
+
+ it('never reuses the streaming turn', () => {
+ const { anchor, tools } = makeSession();
+ const first = deriveAgenticSections(anchor, tools, [], true);
+ const second = deriveAgenticSections(anchor, tools, [], true);
+
+ expect(second).not.toBe(first);
+ });
+
+ it('keeps completed turns stable while the last turn streams', () => {
+ const anchor = makeAssistant({
+ content: 'turn one',
+ id: 'ast-1',
+ toolCalls: JSON.stringify([
+ { function: { arguments: '{}', name: 'test' }, id: 'call_1', type: 'function' }
+ ])
+ });
+ const continuation = makeAssistant({ content: 'turn two', id: 'ast-2' });
+ const tools = [
+ makeToolMsg({ content: 'r1', id: 'tool-1', toolCallId: 'call_1' }),
+ continuation,
+ makeToolMsg({ content: 'r2', id: 'tool-2', toolCallId: 'call_2' })
+ ];
+ const first = deriveAgenticSections(anchor, tools, [], true);
+ const second = deriveAgenticSections(anchor, tools, [], true);
+
+ // turn one is complete: identical section objects across derivations
+ expect(second.slice(0, 2)).toEqual(first.slice(0, 2));
+ expect(second[0]).toBe(first[0]);
+ expect(second[1]).toBe(first[1]);
+
+ // the streaming last turn recomputed: fresh section objects
+ expect(second[second.length - 1]).not.toBe(first[first.length - 1]);
+ });
+});
diff --git a/tools/ui/tests/unit/agentic-strip.test.ts b/tools/ui/tests/unit/agentic-strip.test.ts
new file mode 100644
index 0000000000000000000000000000000000000000..ec4fc213c3a3f85178a08d68b4293a4038894779
--- /dev/null
+++ b/tools/ui/tests/unit/agentic-strip.test.ts
@@ -0,0 +1,100 @@
+import { LEGACY_AGENTIC_REGEX } from '$lib/constants';
+import { describe, expect, it } from 'vitest';
+
+/**
+ * Tests for legacy marker stripping (used in migration).
+ * The new system does not embed markers in content - these tests verify
+ * the legacy regex patterns still work for the migration code.
+ */
+
+// Mirror the legacy stripping logic used during migration
+function stripLegacyContextMarkers(content: string): string {
+ return content
+ .replace(new RegExp(LEGACY_AGENTIC_REGEX.REASONING_BLOCK.source, 'g'), '')
+ .replace(LEGACY_AGENTIC_REGEX.REASONING_OPEN, '')
+ .replace(new RegExp(LEGACY_AGENTIC_REGEX.AGENTIC_TOOL_CALL_BLOCK.source, 'g'), '')
+ .replace(LEGACY_AGENTIC_REGEX.AGENTIC_TOOL_CALL_OPEN, '');
+}
+
+// A realistic complete tool call block as stored in old message.content
+const COMPLETE_BLOCK =
+ '\n\n<<>>\n' +
+ '<<>>\n' +
+ '<<>>\n' +
+ '{"command":"ls /tmp","description":"list tmp"}\n' +
+ '<<>>\n' +
+ 'file1.txt\nfile2.txt\n' +
+ '<<>>\n';
+// Partial block: streaming was cut before END arrived.
+const OPEN_BLOCK =
+ '\n\n<<>>\n' +
+ '<<>>\n' +
+ '<<>>\n' +
+ '{"command":"ls /tmp","description":"list tmp"}\n' +
+ '<<>>\n' +
+ 'partial output...';
+
+describe('legacy agentic marker stripping (for migration)', () => {
+ it('strips a complete tool call block, leaving surrounding text', () => {
+ const input = 'Before.' + COMPLETE_BLOCK + 'After.';
+ const result = stripLegacyContextMarkers(input);
+
+ expect(result).not.toContain('<<<');
+ expect(result).toContain('Before.');
+ expect(result).toContain('After.');
+ });
+
+ it('strips multiple complete tool call blocks', () => {
+ const input = 'A' + COMPLETE_BLOCK + 'B' + COMPLETE_BLOCK + 'C';
+ const result = stripLegacyContextMarkers(input);
+
+ expect(result).not.toContain('<<<');
+ expect(result).toContain('A');
+ expect(result).toContain('B');
+ expect(result).toContain('C');
+ });
+
+ it('strips an open/partial tool call block (no END marker)', () => {
+ const input = 'Lead text.' + OPEN_BLOCK;
+ const result = stripLegacyContextMarkers(input);
+
+ expect(result).toBe('Lead text.');
+ expect(result).not.toContain('<<<');
+ });
+
+ it('does not alter content with no markers', () => {
+ const input = 'Just a normal assistant response.';
+
+ expect(stripLegacyContextMarkers(input)).toBe(input);
+ });
+
+ it('strips reasoning block independently', () => {
+ const input = '<<