Commit 2d4848412 for llama.cpp

commit 2d48484127dcd5f2b3a48694cb84a123d37982fa
Author: Aleksander Grygier <aleksander.grygier@gmail.com>
Date:   Mon Nov 30 16:34:38 2026 +0100

    ui: close a code block as its opening fence is typed (#33364)

    Typing ``` on a line of its own in the editor now writes the closing fence
    below right away and puts the cursor on the line between them, so what comes
    next is code and the block needs no last keystroke. It takes the text the
    browser reports rather than the key, so soft keyboards get it too, and one
    backspace brings the cursor back to the opening fence to name a language. A
    fence typed where a code block is still open stays the text it is, and an
    undone block goes away in one step.

    Assisted by: Llama Chat (ggml-org/Qwen3.8-Flash-Next-GGUF:Q8_0 + DFLASH:Q8_0)

diff --git a/ui/apps/chat/AGENTS.md b/ui/apps/chat/AGENTS.md
index 31a21755a..762b1f325 100644
--- a/ui/apps/chat/AGENTS.md
+++ b/ui/apps/chat/AGENTS.md
@@ -6,7 +6,7 @@ These add to the repository's [AGENTS.md](../../../AGENTS.md) for work in `ui/ap
 - **Demos, checks and docs media:** [skills/ui-demo](../../../skills/ui-demo/SKILL.md) records a PR's demo video, turns its flow into an e2e check and captures docs videos and screenshots, for Llama Chat and Llama UI alike.
 - **Stories:** a story lives with the code it shows. Llama UI's (its foundations, base components, app components and Model UI) are in `ui/lib/ui/tests/stories`, titled `Llama UI/...`, and run as the library's tests; this app's Storybook shows them too. Llama Chat's are in `tests/stories/<area>`, one folder per `src/lib/components/app/<area>` (`chat/` has one per Chat folder), titled `Llama Chat/<Area>/<Component>`. How the app works on a phone (the sidebar's keys, the sheets and the pages each pushes) is written up in `tests/stories/mobile`, titled `Llama Chat/Mobile/Flows`: update it when a sheet gains or loses a page. An accessibility story sits next to its component's, as `<Component>.a11y.stories.svelte`, titled `.../<Component>/Accessibility`. The story helpers both Storybooks use (the Editorial the prose pages are set in, `StateGallery`) live with the library's stories and are imported here as `$llama-ui-stories/...`; reuse them rather than copying them here.
 - **Releases:** `@ggml-org/llama-chat` and `@ggml-org/llama-ui` are versioned by hand and published by CI when a new version reaches `master` (see [Releases](../../README.md#releases)). Bump a version only when asked to release, never as a side effect of a change; Chat's version and its alias's (`alias/package.json`) always move together.
-- **Components:** the `SKILL.md` next to a component folder (such as [src/lib/components/app/SKILL.md](src/lib/components/app/SKILL.md)) holds that folder's conventions.
+- **Components:** the `SKILL.md` next to a component folder (such as [src/lib/components/app/SKILL.md](src/lib/components/app/SKILL.md)) holds that folder's conventions. A component whose machinery is hard to read keeps its own `AGENTS.md` beside it, such as [the Markdown editor's](src/lib/components/app/content/MarkdownEditor/AGENTS.md).

 ## Content is Markdown, custom pieces are Svelte: .svx

diff --git a/ui/apps/chat/src/lib/components/app/content/MarkdownEditor/AGENTS.md b/ui/apps/chat/src/lib/components/app/content/MarkdownEditor/AGENTS.md
new file mode 100644
index 000000000..2bc7f3aea
--- /dev/null
+++ b/ui/apps/chat/src/lib/components/app/content/MarkdownEditor/AGENTS.md
@@ -0,0 +1,11 @@
+# Instructions for ui/apps/chat/src/lib/components/app/content/MarkdownEditor
+
+These add to the repository's [AGENTS.md](../../../../../../../../../AGENTS.md) for Chat's rich content editor: a CodeMirror 6 editor whose document is always the markdown source itself. `../../chat/ChatForm/ChatFormInput/ChatFormInput.svelte` writes a message with it, and `../MarkdownContent` renders that same source in a chat message, reusing its pipeline and stylesheet, so the two must keep agreeing on what a block is.
+
+- **The document is the prompt.** The live preview only decorates: `markdown-live-preview.ts` replaces every top-level block the cursor is not in with the HTML `MarkdownContent` renders for it and shows the block being edited as raw text, and none of it touches the text. What reaches `onChange` is what gets sent, byte for byte. An extension that inserts text (fence auto-close) enlarges the user's keystroke rather than correcting them: one transaction with `userEvent: 'input.type'`, which reports like typing and undoes in one step.
+- **Edits come in two directions.** Editor edits reach `onChange` and so back into `value`; the edits that bring the editor in line with `value` (streamed tokens, a cleared form) go through `syncValue` as the single differing middle of the two texts, annotated `valueSync` to keep them out of `onChange` and out of the undo history.
+- **Extension order decides who sees a key.** The `extensions` prop sits ahead of the editor's own keymaps, so the chat form's handlers keep their keys first (submit, pickers); the editor's own behaviour is added after `markdownSupport`. A `keymap` `run` handler returns `false` when it does not handle the event, otherwise the handlers below it never run.
+- **Typed text arrives through `EditorView.inputHandler`, not a keymap.** The editor takes text through contenteditable on every browser (`ContentEditableView`, because Chrome on Android opens no virtual keyboard for EditContext), where soft keyboards and input methods give no reliable key events but do report the text they inserted. `markdown-code-fence.ts` is that for ``` fences: the last backtick of an opening fence writes the closing one and moves the cursor between them.
+- **What is code is asked of the syntax tree, never of a regex.** `markdown-syntax.ts` (`codeRanges`) and `markdown-blocks.ts` (`collectBlocks`, `CODE_BLOCK_NAMES`) answer the way the preview renders. A code block that is still open runs to the end of the document while a closed one stops before its newline, so resolving the start of a line with side `-1` and walking up tells you whether a block is open there.
+- **Block gaps are computed, not measured.** CodeMirror cannot read the margins of a block widget, so `BLOCK_MARGINS_REM` holds them per block kind, and `markdown-editor-margins.svelte.test.ts` checks them against `../MarkdownContent/markdown-content.css`.
+- **Its tests** are `markdown-editor.svelte.test.ts` and `markdown-editor-margins.svelte.test.ts` in `ui/apps/chat/tests/client` (vitest project `client`, real Chromium). Typing that must reach an input handler is driven with `userEvent.keyboard`; `editor.dispatch` writes the document without going through the DOM input path at all.
diff --git a/ui/apps/chat/src/lib/components/app/content/MarkdownEditor/MarkdownEditor.svelte b/ui/apps/chat/src/lib/components/app/content/MarkdownEditor/MarkdownEditor.svelte
index 3d5e0103e..39d6d2fe8 100644
--- a/ui/apps/chat/src/lib/components/app/content/MarkdownEditor/MarkdownEditor.svelte
+++ b/ui/apps/chat/src/lib/components/app/content/MarkdownEditor/MarkdownEditor.svelte
@@ -13,6 +13,7 @@
 <script lang="ts">
 	import '#lib/styles/katex-custom.scss';
 	import MarkdownSurface from '../MarkdownContent/MarkdownSurface.svelte';
+	import { autoCloseCodeFence } from './markdown-code-fence';
 	import {
 		markdownLivePreview,
 		type MarkdownLivePreviewOptions,
@@ -166,6 +167,8 @@
 					),
 					keymap.of([...markdownKeymap, ...defaultKeymap, ...historyKeymap]),
 					markdownSupport,
+					// the third backtick of a fence opens a code block that is already closed
+					autoCloseCodeFence(),
 					previewCompartment.of(previewExtension()),
 					editableCompartment.of(EditorView.editable.of(!disabled)),
 					EditorView.lineWrapping,
diff --git a/ui/apps/chat/src/lib/components/app/content/MarkdownEditor/markdown-code-fence.ts b/ui/apps/chat/src/lib/components/app/content/MarkdownEditor/markdown-code-fence.ts
new file mode 100644
index 000000000..5dcf17c3c
--- /dev/null
+++ b/ui/apps/chat/src/lib/components/app/content/MarkdownEditor/markdown-code-fence.ts
@@ -0,0 +1,84 @@
+// Opening a code block as it is typed: the last backticks of an opening fence write the
+// closing fence too and put the cursor between them, so what comes next is code.
+
+import { CODE_BLOCK_NAMES } from './markdown-blocks';
+import { syntaxTree } from '@codemirror/language';
+import { type EditorState, type Extension } from '@codemirror/state';
+import { EditorView } from '@codemirror/view';
+
+/** The fence that opens and closes a fenced code block. */
+const CODE_FENCE = '```';
+/** What a single input can add to a line to complete that fence, from a key or a gesture. */
+const FENCE_COMPLETIONS = ['`', '``', '```'];
+/** Markdown lets a fence be indented by up to three spaces. */
+const MAX_FENCE_INDENT = 3;
+
+/**
+ * Whether the cursor sits after a line that `typed` makes an opening fence all by itself:
+ * the fence's backticks, indented as markdown allows, with nothing else on the line.
+ */
+function opensFence(state: EditorState, from: number, to: number, typed: string): boolean {
+	const line = state.doc.lineAt(from);
+	const fence = `${line.text.slice(0, from - line.from)}${typed}`;
+	// What stands before the backticks, which is the line's indentation at most.
+	const indent = fence.length - CODE_FENCE.length;
+
+	return (
+		to === from &&
+		line.to === from &&
+		indent >= 0 &&
+		indent <= MAX_FENCE_INDENT &&
+		fence.endsWith(CODE_FENCE) &&
+		!fence.slice(0, indent).trim()
+	);
+}
+
+/** Whether `pos` is below a code block that is still open, where a fence is only text. */
+function inCodeBlock(state: EditorState, pos: number): boolean {
+	const { from } = state.doc.lineAt(pos);
+
+	// The start of a line falls between nodes, so ask what stands before it: a code block
+	// that is still open reaches past the line, while a closed one stops before its newline.
+	let node = syntaxTree(state).resolve(from, -1);
+
+	// Up through the parents until the top node, which has none: that ends the walk.
+	for (;;) {
+		if (CODE_BLOCK_NAMES.has(node.name)) return node.from < from && node.to >= from;
+
+		const parent = node.parent;
+
+		if (!parent) break;
+
+		node = parent;
+	}
+
+	return false;
+}
+
+/**
+ * The last backticks of an opening fence close the code block they open right away: the
+ * cursor moves to the next line, which already has the closing fence below it. A fence
+ * inside a code block stays the text it is, and the block is one undo step.
+ */
+export function autoCloseCodeFence(): Extension {
+	return EditorView.inputHandler.of((view, from, to, typed) => {
+		if (
+			// an input method may commit the backticks as part of a longer composition
+			view.composing ||
+			!FENCE_COMPLETIONS.includes(typed) ||
+			!opensFence(view.state, from, to, typed) ||
+			inCodeBlock(view.state, from)
+		) {
+			return false;
+		}
+
+		view.dispatch({
+			// the fence, the line the cursor goes to, and the one that closes the block
+			changes: { from, insert: `${typed}\n\n${CODE_FENCE}`, to },
+			selection: { anchor: from + typed.length + 1 },
+			userEvent: 'input.type'
+		});
+
+		return true;
+	});
+}
diff --git a/ui/apps/chat/tests/client/markdown-editor.svelte.test.ts b/ui/apps/chat/tests/client/markdown-editor.svelte.test.ts
index 1ed4853a1..dc6b651c1 100644
--- a/ui/apps/chat/tests/client/markdown-editor.svelte.test.ts
+++ b/ui/apps/chat/tests/client/markdown-editor.svelte.test.ts
@@ -1,6 +1,7 @@
 // Guards the MarkdownEditor contract beyond the chat form: which edits reach onChange,
-// undo of a programmatic replace, props changed after mount, blocks the live preview
-// keeps raw or joins, the gap after a raw block, and selecting text in rendered blocks.
+// undo of a programmatic replace, the code block a typed fence opens, props changed after
+// mount, blocks the live preview keeps raw or joins, the gap after a raw block, and
+// selecting text in rendered blocks.

 import { undo } from '@codemirror/commands';
 import { EditorView, type WidgetType } from '@codemirror/view';
@@ -8,6 +9,7 @@ import MarkdownEditor from '#lib/components/app/content/MarkdownEditor/MarkdownE
 import { SVG } from '#lib/constants/index.ts';
 import { tick } from 'svelte';
 import { describe, expect, it, vi } from 'vitest';
+import { userEvent } from 'vitest/browser';
 import { render } from 'vitest-browser-svelte';

 function editorIn(container: HTMLElement): EditorView {
@@ -63,6 +65,64 @@ describe('MarkdownEditor', () => {
 		expect(editor.state.doc.toString()).toBe('see @no');
 	});

+	it('closes a code block as its opening fence is typed', async () => {
+		const onChange = vi.fn();
+		const screen = render(MarkdownEditor, { onChange, value: 'note\n' });
+		const editor = editorIn(screen.container);
+
+		editor.focus();
+		editor.dispatch({ selection: { anchor: 'note\n'.length } });
+
+		await userEvent.keyboard('```');
+		await settle();
+
+		expect(editor.state.doc.toString()).toBe('note\n```\n\n```');
+		// the cursor waits on the line between the fences
+		expect(editor.state.selection.main.head).toBe('note\n```\n'.length);
+		expect(onChange).toHaveBeenLastCalledWith('note\n```\n\n```');
+	});
+
+	it('undoes a typed code block in one step', async () => {
+		const screen = render(MarkdownEditor, { value: '' });
+		const editor = editorIn(screen.container);
+
+		editor.focus();
+		await userEvent.keyboard('```');
+		await settle();
+
+		expect(editor.state.doc.toString()).toBe('```\n\n```');
+
+		undo(editor);
+
+		expect(editor.state.doc.toString()).toBe('');
+	});
+
+	it('keeps a fence that closes an open code block as text', async () => {
+		const screen = render(MarkdownEditor, { value: '```\n\n' });
+		const editor = editorIn(screen.container);
+
+		editor.focus();
+		editor.dispatch({ selection: { anchor: '```\n'.length } });
+
+		await userEvent.keyboard('```');
+		await settle();
+
+		expect(editor.state.doc.toString()).toBe('```\n```\n');
+	});
+
+	it('keeps backticks after text on their line as they are', async () => {
+		const screen = render(MarkdownEditor, { value: 'note' });
+		const editor = editorIn(screen.container);
+
+		editor.focus();
+		editor.dispatch({ selection: { anchor: 4 } });
+
+		await userEvent.keyboard('```');
+		await settle();
+
+		expect(editor.state.doc.toString()).toBe('note```');
+	});
+
 	it('follows placeholder and label changes after mount', async () => {
 		const screen = render(MarkdownEditor, { placeholder: 'First', value: '' });
 		const editor = editorIn(screen.container);