Commit eb5657509 for llama.cpp

commit eb56575095e023a50f6d529a0397fec94a659f21
Author: Aleksander Grygier <aleksander.grygier@gmail.com>
Date:   Wed Nov 25 20:02:31 2026 +0100

    ui: stop the streaming reply with Escape (#33051)

    Assisted-by: Claude (Opus 5.5 Medium)

diff --git a/ui/apps/chat/README.md b/ui/apps/chat/README.md
index ec4b38b57..7838e7878 100644
--- a/ui/apps/chat/README.md
+++ b/ui/apps/chat/README.md
@@ -55,7 +55,7 @@ The app reaches the llama-server on its own origin by default (llama-server serv
 - **Rendering** - Markdown (GFM), code highlighting, KaTeX math and Mermaid diagrams
 - **Models** - in ROUTER mode, a selector and a models manager: load and unload, downloads, Discover from the Hugging Face Hub, favorites and hidden models
 - **Tools** - built-in browser tools, llama-server's tools and MCP servers, each behind a permission prompt
-- **Everywhere** - light and dark themes, phone layouts, installable as a PWA, keyboard shortcuts (`Ctrl/Cmd+K` search, `Shift+Ctrl/Cmd+O` new chat, `Ctrl/Cmd+B` sidebar)
+- **Everywhere** - light and dark themes, phone layouts, installable as a PWA, keyboard shortcuts (`Ctrl/Cmd+K` search, `Shift+Ctrl/Cmd+O` new chat, `Ctrl/Cmd+B` sidebar, `Esc` stop the reply)

 ## Development

diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte
index 82ffb3f6a..ca2c651da 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte
@@ -22,6 +22,7 @@
 		CLIPBOARD_CONTENT_QUOTE_PREFIX,
 		ICON_CLASS_DEFAULT,
 		INITIAL_FILE_SIZE,
+		OPEN_OVERLAY_SELECTOR,
 		PROMPT_CONTENT_SEPARATOR,
 		SETTING_CONFIG_DEFAULT,
 		SYSTEM_MESSAGE_PLACEHOLDER,
@@ -700,16 +701,29 @@
 		await submit();
 	}

-	// Escape drops a recording, wherever the focus is
-	function handleWindowKeydown(event: KeyboardEvent) {
-		if (event.key !== KeyboardKey.ESCAPE || !voice.isActive || event.defaultPrevented) return;
+	// Escape drops a recording, or else stops the reply, wherever the focus is. On the body, so it
+	// runs before the overlays' document listeners: a tooltip closing on Escape does not take the key
+	function handleBodyKeydown(event: KeyboardEvent) {
+		if (event.key !== KeyboardKey.ESCAPE || event.defaultPrevented) return;
+
+		if (document.querySelector(OPEN_OVERLAY_SELECTOR)) return;
+
+		if (voice.isActive) {
+			event.preventDefault();
+			voice.cancel();
+
+			return;
+		}
+
+		// the system message editor and a message edit take Escape in their own window listeners
+		if (!isLoading || systemMode || chatStore.isEditing() || isIMEComposing(event)) return;

 		event.preventDefault();
-		voice.cancel();
+		onStop?.();
 	}
 </script>

-<svelte:window onkeydown={handleWindowKeydown} />
+<svelte:body onkeydown={handleBodyKeydown} />

 {#snippet systemMessageLeading()}
 	{#if systemMessageAttachment}
diff --git a/ui/apps/chat/src/lib/components/app/models/ModelsManager/ModelsManager.svelte b/ui/apps/chat/src/lib/components/app/models/ModelsManager/ModelsManager.svelte
index 4cdf3112b..32156e4b4 100644
--- a/ui/apps/chat/src/lib/components/app/models/ModelsManager/ModelsManager.svelte
+++ b/ui/apps/chat/src/lib/components/app/models/ModelsManager/ModelsManager.svelte
@@ -13,7 +13,8 @@
 	import {
 		LOCAL_BACKEND_ID,
 		type ModalityKey,
-		MODELS_TABLE_GROUP_LABELS
+		MODELS_TABLE_GROUP_LABELS,
+		OPEN_OVERLAY_SELECTOR
 	} from '#lib/constants/index.ts';
 	import { ModelCapability, ModelsTableGroupKind } from '#lib/enums/index.ts';
 	import { modelsStore, uiStore } from '#lib/stores/index.ts';
@@ -169,14 +170,6 @@
 		void uiStore.closeModelsManager();
 	}

-	/** Overlays that handle their own Escape, so the page leaves them alone. */
-	const OPEN_OVERLAY_SELECTOR = [
-		'[role="dialog"][data-state="open"]',
-		'[role="alertdialog"][data-state="open"]',
-		'[role="menu"][data-state="open"]',
-		'[role="listbox"][data-state="open"]'
-	].join(', ');
-
 	// Escape steps back the way the dialog's did: the pane's drawer closes itself, then
 	// the next Escape leaves the page
 	function handleKeydown(event: KeyboardEvent): void {
diff --git a/ui/apps/chat/src/lib/constants/ui.constants.ts b/ui/apps/chat/src/lib/constants/ui.constants.ts
index a371aec8d..8253af8c8 100644
--- a/ui/apps/chat/src/lib/constants/ui.constants.ts
+++ b/ui/apps/chat/src/lib/constants/ui.constants.ts
@@ -25,6 +25,18 @@ export const COPY_FEEDBACK_RESET_MS = 1500;
 export const NATIVE_CONTEXT_MENU_SELECTOR =
 	'a, img, video, audio, pre, code, input, textarea, [contenteditable="true"]';

+/**
+ * Open overlays that take Escape themselves, so what is under them leaves the key alone.
+ * Not tooltips and hover cards, which only close on it.
+ */
+export const OPEN_OVERLAY_SELECTOR = [
+	'[role="dialog"][data-state="open"]',
+	'[role="alertdialog"][data-state="open"]',
+	'[role="menu"][data-state="open"]',
+	'[role="listbox"][data-state="open"]',
+	'[data-slot="popover-content"][data-state="open"]'
+].join(', ');
+
 /**
  * A sidebar section under a dragged chat, or one being moved: the faint tint
  * of the sidebar's resize handle, edged like the handle while it is dragged.
diff --git a/ui/apps/chat/src/lib/stores/sidebar-drag.svelte.ts b/ui/apps/chat/src/lib/stores/sidebar-drag.svelte.ts
index 73a0edefe..9e9f0b891 100644
--- a/ui/apps/chat/src/lib/stores/sidebar-drag.svelte.ts
+++ b/ui/apps/chat/src/lib/stores/sidebar-drag.svelte.ts
@@ -216,7 +216,7 @@ class SidebarDragStore {
 		window.removeEventListener('pointermove', this.#handleMove);
 		window.removeEventListener('pointerup', this.#handleUp);
 		window.removeEventListener('pointercancel', this.#handleCancel);
-		window.removeEventListener('keydown', this.#handleKeydown);
+		window.removeEventListener('keydown', this.#handleKeydown, { capture: true });

 		if (!gesture?.active) return;

@@ -257,7 +257,8 @@ class SidebarDragStore {
 		window.addEventListener('pointermove', this.#handleMove);
 		window.addEventListener('pointerup', this.#handleUp);
 		window.addEventListener('pointercancel', this.#handleCancel);
-		window.addEventListener('keydown', this.#handleKeydown);
+		// capture: a drag takes Escape before the listeners that would act on it too
+		window.addEventListener('keydown', this.#handleKeydown, { capture: true });
 	}

 	#scrollDelta(gesture: Gesture): number {
diff --git a/ui/apps/chat/tests/client/chat-form-escape.svelte.test.ts b/ui/apps/chat/tests/client/chat-form-escape.svelte.test.ts
new file mode 100644
index 000000000..6d6d85cdd
--- /dev/null
+++ b/ui/apps/chat/tests/client/chat-form-escape.svelte.test.ts
@@ -0,0 +1,144 @@
+// Guards the Escape contract of the chat form: while a reply streams Escape stops it, as the
+// stop button does, unless something else takes the key first - an open menu or drawer, a
+// picker, a selection in the editor, the system message editor or a message edit. A tooltip
+// does not take it.
+
+import ChatFormTestWrapper from './components/ChatFormTestWrapper.svelte';
+import { EditorView } from '@codemirror/view';
+import { OPEN_OVERLAY_SELECTOR } from '#lib/constants/index.ts';
+import { chatStore } from '#lib/stores/index.ts';
+import { tick } from 'svelte';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { page, userEvent } from 'vitest/browser';
+import { render } from 'vitest-browser-svelte';
+
+const PHONE = { height: 844, width: 390 };
+const DESKTOP = { height: 900, width: 1280 };
+const ADD_MENU_TRIGGER_SELECTOR = '.file-upload-button';
+const TOOLTIP_SELECTOR = '[data-slot="tooltip-content"]';
+// a tooltip opens after its hover delay
+const TOOLTIP_TIMEOUT_MS = 5000;
+const MENTION_PICKER_TEXT = 'File search is unavailable';
+
+async function renderForm({ isLoading = true, systemMode = false } = {}) {
+	const onStop = vi.fn();
+	const { container } = render(ChatFormTestWrapper, { isLoading, onStop, systemMode });
+
+	await tick();
+
+	const content = container.querySelector<HTMLElement>('.cm-content');
+	const editor = content && EditorView.findFromDOM(content);
+
+	if (!editor) throw new Error('editor not rendered');
+
+	await userEvent.click(editor.contentDOM);
+
+	return { container, editor, onStop };
+}
+
+describe('ChatForm Escape', () => {
+	afterEach(async () => {
+		chatStore.clearEditMode();
+		await page.viewport(DESKTOP.width, DESKTOP.height);
+	});
+
+	it('stops the reply from the editor', async () => {
+		const { onStop } = await renderForm();
+
+		await userEvent.keyboard('{Escape}');
+
+		expect(onStop).toHaveBeenCalledOnce();
+	});
+
+	it('stops the reply with the focus outside the form', async () => {
+		const { editor, onStop } = await renderForm();
+
+		editor.contentDOM.blur();
+		await userEvent.keyboard('{Escape}');
+
+		expect(onStop).toHaveBeenCalledOnce();
+	});
+
+	it('does nothing with no reply streaming', async () => {
+		const { onStop } = await renderForm({ isLoading: false });
+
+		await userEvent.keyboard('{Escape}');
+
+		expect(onStop).not.toHaveBeenCalled();
+	});
+
+	// the add menu is a dropdown on a desktop and a drawer on a phone
+	it.each([
+		{ overlay: 'menu', viewport: DESKTOP },
+		{ overlay: 'drawer', viewport: PHONE }
+	])('closes the open add $overlay first', async ({ viewport }) => {
+		await page.viewport(viewport.width, viewport.height);
+
+		const { container, onStop } = await renderForm();
+		const overlay = () => document.querySelector(OPEN_OVERLAY_SELECTOR);
+
+		await userEvent.click(container.querySelector<HTMLElement>(ADD_MENU_TRIGGER_SELECTOR)!);
+		await expect.poll(overlay).toBeTruthy();
+
+		await userEvent.keyboard('{Escape}');
+		await expect.poll(overlay).toBeNull();
+		expect(onStop).not.toHaveBeenCalled();
+
+		await userEvent.keyboard('{Escape}');
+		expect(onStop).toHaveBeenCalledOnce();
+	});
+
+	it('stops the reply with a tooltip showing', async () => {
+		const { container, onStop } = await renderForm();
+
+		await userEvent.hover(container.querySelector<HTMLElement>(ADD_MENU_TRIGGER_SELECTOR)!);
+		await expect
+			.poll(() => document.querySelector(TOOLTIP_SELECTOR), { timeout: TOOLTIP_TIMEOUT_MS })
+			.toBeTruthy();
+
+		await userEvent.keyboard('{Escape}');
+		expect(onStop).toHaveBeenCalledOnce();
+	});
+
+	it('closes the mention picker first', async () => {
+		const { onStop } = await renderForm();
+
+		await userEvent.keyboard('@m');
+		await expect.poll(() => document.body.textContent).toContain(MENTION_PICKER_TEXT);
+
+		await userEvent.keyboard('{Escape}');
+		await expect.poll(() => document.body.textContent).not.toContain(MENTION_PICKER_TEXT);
+		expect(onStop).not.toHaveBeenCalled();
+	});
+
+	it('drops a selection in the editor first', async () => {
+		const { editor, onStop } = await renderForm();
+
+		await userEvent.keyboard('hello');
+		editor.dispatch({ selection: { anchor: 0, head: editor.state.doc.length } });
+
+		await userEvent.keyboard('{Escape}');
+		expect(editor.state.selection.main.empty).toBe(true);
+		expect(onStop).not.toHaveBeenCalled();
+
+		await userEvent.keyboard('{Escape}');
+		expect(onStop).toHaveBeenCalledOnce();
+	});
+
+	it('leaves the key to the system message editor', async () => {
+		const { onStop } = await renderForm({ systemMode: true });
+
+		await userEvent.keyboard('{Escape}');
+
+		expect(onStop).not.toHaveBeenCalled();
+	});
+
+	it('leaves the key to a message edit', async () => {
+		const { onStop } = await renderForm();
+
+		chatStore.setEditModeActive(() => {});
+		await userEvent.keyboard('{Escape}');
+
+		expect(onStop).not.toHaveBeenCalled();
+	});
+});
diff --git a/ui/apps/chat/tests/client/chat-form-voice.svelte.test.ts b/ui/apps/chat/tests/client/chat-form-voice.svelte.test.ts
index 3c846682b..ca19b2e9c 100644
--- a/ui/apps/chat/tests/client/chat-form-voice.svelte.test.ts
+++ b/ui/apps/chat/tests/client/chat-form-voice.svelte.test.ts
@@ -43,7 +43,7 @@ function seed(

 async function renderForm({ isLoading = false } = {}) {
 	const recorder = new FakeVoiceRecorder();
-	const state = $state({ files: [] as ChatUploadedFile[], sent: 0, value: '' });
+	const state = $state({ files: [] as ChatUploadedFile[], sent: 0, stopped: 0, value: '' });
 	const screen = render(ChatFormVoiceTestWrapper, { isLoading, state, voiceRecorder: recorder });

 	await tick();
@@ -287,6 +287,20 @@ describe('while a reply streams', () => {
 			.element(screen.getByRole('button', { name: VOICE_MODE_MESSAGE.voiceMessage }).last())
 			.toBeEnabled();
 	});
+
+	it('drops the recording on Escape, and the reply goes on', async () => {
+		seed(true, VoiceInputMode.DICTATION);
+
+		const { recorder, recordingRow, screen, state } = await renderForm({ isLoading: true });
+
+		await screen.getByRole('button', { name: VOICE_MODE_MESSAGE.dictate }).last().click();
+		await expect.poll(recordingRow).toBeTruthy();
+
+		await userEvent.keyboard('{Escape}');
+		await expect.poll(recordingRow).toBeNull();
+		expect(recorder.cancelled).toBe(1);
+		expect(state.stopped).toBe(0);
+	});
 });

 describe('recording', () => {
diff --git a/ui/apps/chat/tests/client/components/ChatFormTestWrapper.svelte b/ui/apps/chat/tests/client/components/ChatFormTestWrapper.svelte
index badea196b..c97b0a628 100644
--- a/ui/apps/chat/tests/client/components/ChatFormTestWrapper.svelte
+++ b/ui/apps/chat/tests/client/components/ChatFormTestWrapper.svelte
@@ -7,11 +7,23 @@
 		expandable?: boolean;
 		/** The message the form starts with, as a restored draft would be. */
 		initialValue?: string;
+		/** A reply is streaming: the form offers stop in place of send. */
+		isLoading?: boolean;
+		onStop?: () => void;
 		onSubmit?: () => void;
 		singleRow?: boolean;
+		systemMode?: boolean;
 	}

-	let { expandable = false, initialValue = '', onSubmit, singleRow = false }: Props = $props();
+	let {
+		expandable = false,
+		initialValue = '',
+		isLoading = false,
+		onStop,
+		onSubmit,
+		singleRow = false,
+		systemMode = false
+	}: Props = $props();

 	let value = $state(untrack(() => initialValue));
 	let form: ChatForm | undefined = $state();
@@ -22,5 +34,14 @@
 </script>

 <Tooltip.Provider>
-	<ChatForm bind:this={form} bind:value {expandable} {onSubmit} {singleRow} />
+	<ChatForm
+		bind:this={form}
+		bind:value
+		{expandable}
+		{isLoading}
+		{onStop}
+		{onSubmit}
+		{singleRow}
+		{systemMode}
+	/>
 </Tooltip.Provider>
diff --git a/ui/apps/chat/tests/client/components/ChatFormVoiceTestWrapper.svelte b/ui/apps/chat/tests/client/components/ChatFormVoiceTestWrapper.svelte
index 34dfe4ce7..9c02dcd9b 100644
--- a/ui/apps/chat/tests/client/components/ChatFormVoiceTestWrapper.svelte
+++ b/ui/apps/chat/tests/client/components/ChatFormVoiceTestWrapper.svelte
@@ -6,8 +6,8 @@
 	interface Props {
 		/** A reply is streaming: the form offers stop in place of send. */
 		isLoading?: boolean;
-		/** The form's message and files, kept in step with it for the test to read, and how often it sent. */
-		state: { files: ChatUploadedFile[]; sent?: number; value: string };
+		/** The form's message and files, kept in step with it for the test to read, and how often it sent or stopped. */
+		state: { files: ChatUploadedFile[]; sent?: number; stopped?: number; value: string };
 		voiceRecorder: VoiceRecorderLike;
 	}

@@ -19,6 +19,7 @@
 		bind:uploadedFiles={state.files}
 		bind:value={state.value}
 		{isLoading}
+		onStop={() => (state.stopped = (state.stopped ?? 0) + 1)}
 		onSubmit={() => (state.sent = (state.sent ?? 0) + 1)}
 		{voiceRecorder}
 	/>