Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: stop dialog open and close from rescanning a long chat for every shortcut (#16983)

Daniel Hanf5133deb352a
diff --git a/studio/frontend/src/features/settings/hooks/use-shortcut.ts b/studio/frontend/src/features/settings/hooks/use-shortcut.ts
index 9a393b03f3b..04a73722e69 100644
--- a/studio/frontend/src/features/settings/hooks/use-shortcut.ts
+++ b/studio/frontend/src/features/settings/hooks/use-shortcut.ts
@@ -37,12 +37,28 @@ export function isImeComposing(event: KeyboardEvent): boolean {
return event.isComposing || event.keyCode === 229;
}
+// Set only while the listeners re-read their snapshots. Nothing mutates the DOM between two
+// listeners (React schedules their re-renders), so each id and each document query is answered
+// once per pass instead of once per subscriber; a long chat makes every miss a whole-tree walk.
+let passAnswers: Map<string, boolean> | null = null;
+
+function answerOncePerPass(key: string, compute: () => boolean): boolean {
+ if (!passAnswers) return compute();
+ const known = passAnswers.get(key);
+ if (known !== undefined) return known;
+ const answer = compute();
+ passAnswers.set(key, answer);
+ return answer;
+}
+
/** Checked at press time: a dialog leaves the route mounted and need not re-render `enabled`. */
export function isSurfaceInForeground(selector: string): boolean {
if (typeof document === "undefined") return false;
// Every match: Compare keeps an inert base composer mounted; Radix aria-hides the page under a modal.
- return [...document.querySelectorAll(selector)].some(
- (el) => !el.closest('[aria-hidden="true"], [inert]'),
+ return answerOncePerPass(`foreground\0${selector}`, () =>
+ [...document.querySelectorAll(selector)].some(
+ (el) => !el.closest('[aria-hidden="true"], [inert]'),
+ ),
);
}
@@ -50,11 +66,13 @@ export function isSurfaceInForeground(selector: string): boolean {
* backgrounded. */
export function isSurfaceBackgrounded(selector: string): boolean {
if (typeof document === "undefined") return false;
- const found = [...document.querySelectorAll(selector)];
- return (
- found.length > 0 &&
- found.every((el) => el.closest('[aria-hidden="true"], [inert]') !== null)
- );
+ return answerOncePerPass(`backgrounded\0${selector}`, () => {
+ const found = [...document.querySelectorAll(selector)];
+ return (
+ found.length > 0 &&
+ found.every((el) => el.closest('[aria-hidden="true"], [inert]') !== null)
+ );
+ });
}
/** Only Escape, function keys, and non-Shift modifier chords; caret keys count as typing. */
@@ -83,7 +101,23 @@ export interface ShortcutTrigger {
const triggers = new Map<ShortcutId, ShortcutTrigger[]>();
const triggerListeners = new Set<() => void>();
-const notifyTriggerListeners = () => triggerListeners.forEach((listener) => listener());
+let notifyQueued = false;
+function flushTriggerListeners(): void {
+ notifyQueued = false;
+ passAnswers = new Map();
+ try {
+ triggerListeners.forEach((listener) => listener());
+ } finally {
+ passAnswers = null;
+ }
+}
+// One pass per microtask: a dialog mounting or unmounting registers or drops a trigger per
+// shortcut and lands as several observer batches, and each pass re-asks every subscriber.
+const notifyTriggerListeners = () => {
+ if (notifyQueued) return;
+ notifyQueued = true;
+ queueMicrotask(flushTriggerListeners);
+};
/** Exported for the test. Returns the unregister. */
export function registerShortcutTrigger(
@@ -107,7 +141,8 @@ export function triggerShortcut(id: ShortcutId): boolean {
// Modals show as aria-hidden, inert, or only a body-portaled backdrop when an aria-live region exists.
let modalObserver: MutationObserver | null = null;
-function subscribeTriggers(listener: () => void, watchModals: boolean): () => void {
+/** Exported for the test. Returns the unsubscribe. */
+export function subscribeTriggers(listener: () => void, watchModals: boolean): () => void {
triggerListeners.add(listener);
if (watchModals && !modalObserver && typeof MutationObserver !== "undefined") {
modalObserver = new MutationObserver(notifyTriggerListeners);
@@ -134,7 +169,9 @@ export function useShortcutAvailable(id: ShortcutId, watchModals: boolean): bool
[watchModals],
);
return useSyncExternalStore(subscribe, () =>
- (triggers.get(id) ?? []).some((t) => t.claims()),
+ answerOncePerPass(`available\0${id}`, () =>
+ (triggers.get(id) ?? []).some((t) => t.claims()),
+ ),
);
}
diff --git a/studio/frontend/tests/shortcut-availability-pass.test.ts b/studio/frontend/tests/shortcut-availability-pass.test.ts
new file mode 100644
index 00000000000..519309d5c8a
--- /dev/null
+++ b/studio/frontend/tests/shortcut-availability-pass.test.ts
@@ -0,0 +1,114 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Opening or closing a dialog registers and drops a trigger per shortcut and fires several modal
+// observer batches. Each re-ask walks the whole document, which on a long chat is the cost of the
+// open or close itself, so the re-asks are batched into one pass per microtask that asks each
+// selector once. Press-time checks stay uncached.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { readSrc, registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+
+const {
+ isSurfaceBackgrounded,
+ isSurfaceInForeground,
+ registerShortcutTrigger,
+ subscribeTriggers,
+ triggerShortcut,
+} = await import("../src/features/settings/hooks/use-shortcut.ts");
+
+const covered = { closest: () => ({}) };
+const clear = { closest: () => null };
+
+function fakeDocument(): { queries: string[]; matches: unknown[] } {
+ const state = { queries: [] as string[], matches: [clear] as unknown[] };
+ (globalThis as { document?: unknown }).document = {
+ querySelectorAll: (selector: string) => {
+ state.queries.push(selector);
+ return state.matches;
+ },
+ };
+ return state;
+}
+
+const settle = () => new Promise<void>((resolve) => setTimeout(resolve, 0));
+
+test("a burst of trigger changes re-asks each subscriber once, each selector once", async () => {
+ const doc = globalThis.document;
+ const dom = fakeDocument();
+ const seen: boolean[][] = [[], []];
+ const offs = seen.map((answers) =>
+ subscribeTriggers(() => {
+ answers.push(isSurfaceBackgrounded(".aui-composer-input"));
+ answers.push(isSurfaceBackgrounded(".aui-composer-input"));
+ }, false),
+ );
+ const drops: (() => void)[] = [];
+ try {
+ for (let i = 0; i < 6; i += 1) {
+ drops.push(registerShortcutTrigger("toggleSidebar", { claims: () => true, run: () => {} }));
+ }
+ assert.deepEqual(seen, [[], []], "nobody is asked synchronously");
+ await settle();
+ assert.deepEqual(seen, [[false, false], [false, false]], "one pass, every subscriber");
+ assert.deepEqual(dom.queries, [".aui-composer-input"], "the pass shares one query");
+
+ // Outside a pass the answer is live: a press reads the DOM as it is now.
+ dom.matches = [covered];
+ assert.equal(isSurfaceBackgrounded(".aui-composer-input"), true);
+ assert.equal(isSurfaceInForeground(".aui-composer-input"), false);
+ assert.equal(dom.queries.length, 3);
+
+ drops.splice(0).forEach((drop) => drop());
+ await settle();
+ assert.deepEqual(seen[0].slice(2), [true, true], "the next pass asks again");
+ assert.equal(dom.queries.length, 4);
+ } finally {
+ drops.forEach((drop) => drop());
+ offs.forEach((off) => off());
+ (globalThis as { document?: unknown }).document = doc;
+ }
+});
+
+test("a menu trigger still asks its claims at press time", () => {
+ let claims = true;
+ const runs: string[] = [];
+ const off = registerShortcutTrigger("findInPage", {
+ claims: () => claims,
+ run: () => runs.push("find"),
+ });
+ try {
+ assert.equal(triggerShortcut("findInPage"), true);
+ claims = false;
+ assert.equal(triggerShortcut("findInPage"), false, "not answered from a cached pass");
+ assert.deepEqual(runs, ["find"]);
+ } finally {
+ off();
+ }
+});
+
+test("availability reads go through the per-pass answers", () => {
+ const hook = readSrc("features/settings/hooks/use-shortcut.ts");
+ assert.match(hook, /queueMicrotask\(flushTriggerListeners\)/);
+ assert.match(hook, /passAnswers = new Map\(\);\s*try \{\s*triggerListeners\.forEach/);
+ assert.match(hook, /\} finally \{\s*passAnswers = null;\s*\}/);
+ assert.match(hook, /answerOncePerPass\(`available\\0\$\{id\}`/);
+ assert.match(hook, /answerOncePerPass\(`backgrounded\\0\$\{selector\}`/);
+ assert.match(hook, /answerOncePerPass\(`foreground\\0\$\{selector\}`/);
+});
+
+test("the preload helper looks for the CSP nonce meta in <head> only", async () => {
+ const { scopePreloadNonceLookup } = await import("../vite-plugin-preload-nonce.ts");
+ for (const q of ["`", '"', "'"]) {
+ assert.equal(
+ scopePreloadNonceLookup(`let c=document.querySelector(${q}meta[property=csp-nonce]${q}),l=c?.nonce;`),
+ `let c=document.head.querySelector(${q}meta[property=csp-nonce]${q}),l=c?.nonce;`,
+ );
+ }
+ assert.equal(scopePreloadNonceLookup("document.querySelector(`meta`)"), "document.querySelector(`meta`)");
+ assert.match(readSrc("../vite.config.ts"), /katexWoff2Only\(\), preloadNonceInHead\(\)\]/);
+});
diff --git a/studio/frontend/vite-plugin-preload-nonce.ts b/studio/frontend/vite-plugin-preload-nonce.ts
new file mode 100644
index 00000000000..313dbfbb6ee
--- /dev/null
+++ b/studio/frontend/vite-plugin-preload-nonce.ts
@@ -0,0 +1,25 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import type { Plugin } from "vite";
+
+// Vite's preload helper looks up the CSP nonce meta on every lazy import with deps. Studio ships
+// no such meta, so each lookup walks the whole document, which on a long chat costs about 1 ms
+// per import (Settings opens 19). The meta can only sit in <head>, so ask <head>.
+const NONCE_LOOKUP = /document\.querySelector\((["'`])meta\[property=csp-nonce\]\1\)/g;
+
+export function scopePreloadNonceLookup(code: string): string {
+ return code.replace(NONCE_LOOKUP, "document.head.querySelector($1meta[property=csp-nonce]$1)");
+}
+
+export function preloadNonceInHead(): Plugin {
+ return {
+ name: "preload-nonce-in-head",
+ apply: "build",
+ renderChunk(code) {
+ if (!code.includes("csp-nonce")) return null;
+ const next = scopePreloadNonceLookup(code);
+ return next === code ? null : { code: next, map: null };
+ },
+ };
+}
diff --git a/studio/frontend/vite.config.ts b/studio/frontend/vite.config.ts
index dbe47313e26..20866ce8026 100644
--- a/studio/frontend/vite.config.ts
+++ b/studio/frontend/vite.config.ts
@@ -9,6 +9,7 @@ import { chatPagePreload } from "./vite-plugin-chat-preload";
import { childSelectorOrder } from "./vite-plugin-child-selectors";
import { hasAnchorOrder } from "./vite-plugin-has-anchor";
import { katexWoff2Only } from "./vite-plugin-katex-woff2";
+import { preloadNonceInHead } from "./vite-plugin-preload-nonce";
import { viewportMediaGate } from "./vite-plugin-viewport-media";
import { previewRuntime } from "./vite-preview-runtime.ts";
@@ -35,7 +36,7 @@ export default defineConfig({
cacheDir: process.env.VITE_TEST_CACHE_DIR || "node_modules/.vite",
// Reasoning's highlighter loads only the grammar it needs in its module worker.
worker: { format: "es" },
- plugins: [react(), tailwindcss(), childSelectorOrder(), hasAnchorOrder(), viewportMediaGate(), smokeModuleDelay(), previewRuntime(), chatPagePreload(), katexWoff2Only()],
+ plugins: [react(), tailwindcss(), childSelectorOrder(), hasAnchorOrder(), viewportMediaGate(), smokeModuleDelay(), previewRuntime(), chatPagePreload(), katexWoff2Only(), preloadNonceInHead()],
// prevent ancestor PostCSS configs from leaking into installs; Tailwind uses its Vite plugin.
css: {
postcss: {