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: add prompt queue controls and composer preferences (#10980)

Michael Hanf4958cee8a92
diff --git a/.github/workflows/studio-composer-compatibility.yml b/.github/workflows/studio-composer-compatibility.yml
new file mode 100644
index 00000000000..e7dbe550a57
--- /dev/null
+++ b/.github/workflows/studio-composer-compatibility.yml
@@ -0,0 +1,145 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+name: Composer compatibility
+
+on:
+ pull_request:
+ paths:
+ - 'studio/frontend/src/components/assistant-ui/**'
+ - 'studio/frontend/src/features/chat/**'
+ - 'studio/frontend/src/features/settings/components/composer-settings.tsx'
+ - 'studio/frontend/src/index.css'
+ - 'studio/frontend/smoke-*'
+ - 'studio/frontend/tests/**'
+ - 'studio/frontend/package*.json'
+ - 'studio/frontend/vite.config.ts'
+ - 'tests/studio/*composer*'
+ - 'tests/studio/*prompt_queue*'
+ - 'tests/studio/_playwright_robust.py'
+ - '.github/workflows/studio-composer-compatibility.yml'
+ - '.github/scripts/retry-with-apt-lock.sh'
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ composer:
+ name: Composer (${{ matrix.os }}, ${{ matrix.suite }})
+ runs-on: ${{ matrix.os }}
+ timeout-minutes: 30
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - os: ubuntu-latest
+ suite: browsers
+ - os: macos-latest
+ suite: browsers
+ - os: windows-latest
+ suite: browsers
+ - os: macos-latest
+ suite: safari
+ defaults:
+ run:
+ shell: bash
+ env:
+ PLAYWRIGHT_BROWSERS_PATH: ${{ github.workspace }}/temp/queue-validation/browsers
+ PIP_CACHE_DIR: ${{ github.workspace }}/temp/queue-validation/pip-cache
+ npm_config_cache: ${{ github.workspace }}/temp/queue-validation/npm-cache
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
+ with:
+ node-version: '22'
+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
+ with:
+ python-version: '3.12'
+ - name: Audit dependencies
+ run: python scripts/lockfile_supply_chain_audit.py
+ - name: Install frontend dependencies without lifecycle scripts
+ working-directory: studio/frontend
+ run: npm ci --ignore-scripts --no-fund --no-audit
+ - name: Create isolated test environment
+ run: |
+ mkdir -p temp/queue-validation/tmp
+ echo "TMPDIR=$GITHUB_WORKSPACE/temp/queue-validation/tmp" >> "$GITHUB_ENV"
+ echo "TMP=$GITHUB_WORKSPACE/temp/queue-validation/tmp" >> "$GITHUB_ENV"
+ echo "TEMP=$GITHUB_WORKSPACE/temp/queue-validation/tmp" >> "$GITHUB_ENV"
+ python -m venv temp/queue-validation/venv
+ python - <<'PY'
+ import os
+ import subprocess
+ from pathlib import Path
+ folder = "Scripts" if os.name == "nt" else "bin"
+ executable = "python.exe" if os.name == "nt" else "python"
+ bin_dir = (Path("temp/queue-validation/venv") / folder).resolve()
+ subprocess.check_call([str(bin_dir / executable), "-m", "pip", "install", "playwright==1.62.0", "selenium==4.49.0"])
+ with open(os.environ["GITHUB_PATH"], "a", encoding="utf-8") as path_file:
+ path_file.write(str(bin_dir) + "\n")
+ PY
+ - name: Install browser engines
+ if: matrix.suite == 'browsers'
+ timeout-minutes: 10
+ run: python -m playwright install chromium firefox webkit
+ - name: Install Linux browser libraries
+ if: runner.os == 'Linux'
+ timeout-minutes: 10
+ env:
+ APT_ACQUIRE_RETRIES: '0'
+ run: |
+ if python - <<'PY'
+ from playwright.sync_api import sync_playwright
+ with sync_playwright() as p:
+ for name in ("chromium", "firefox", "webkit"):
+ browser = getattr(p, name).launch()
+ browser.close()
+ PY
+ then
+ echo "Browser libraries are already installed"
+ else
+ bash .github/scripts/retry-with-apt-lock.sh \
+ python -m playwright install-deps chromium firefox webkit
+ fi
+ - name: Queue engine and composer regressions
+ if: matrix.suite == 'browsers'
+ working-directory: studio/frontend
+ run: node --experimental-strip-types --test tests/composer-*.test.ts tests/prompt-queue-*.test.ts tests/model-lifecycle-gate.test.ts tests/loading-model-selection.test.ts tests/pre-stream-run-reservation.test.ts tests/auto-compaction-settings.test.ts
+ - name: Browser simulations
+ if: matrix.suite == 'browsers'
+ run: |
+ mkdir -p temp/queue-validation/compatibility
+ status=0
+ for browser in chromium firefox webkit chrome msedge; do
+ export PW_ENGINE=chromium
+ unset PW_CHANNEL PW_EXECUTABLE
+ case "$browser" in
+ firefox|webkit) export PW_ENGINE="$browser" ;;
+ chrome|msedge) export PW_CHANNEL="$browser" ;;
+ esac
+ python tests/studio/playwright_prompt_queue_actions.py \
+ > "temp/queue-validation/compatibility/$browser-queue.log" 2>&1 || status=1
+ python tests/studio/playwright_composer_settings.py \
+ > "temp/queue-validation/compatibility/$browser-composer.log" 2>&1 || status=1
+ done
+ exit "$status"
+ - name: Native Safari simulations
+ if: ${{ !cancelled() && matrix.suite == 'safari' }}
+ run: |
+ sudo safaridriver --enable
+ python tests/studio/selenium_composer_safari.py
+ - name: Upload simulation reports
+ if: ${{ !cancelled() }}
+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
+ with:
+ name: composer-${{ runner.os }}-${{ matrix.suite }}
+ path: temp/queue-validation/compatibility
+ retention-days: 7
+ if-no-files-found: warn
diff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.ts
index d5cdbcb77fc..96d9e06a4e4 100644
--- a/studio/frontend/scripts/check-bundle-budget.ts
+++ b/studio/frontend/scripts/check-bundle-budget.ts
@@ -48,8 +48,8 @@ export const BUDGET = {
// days. rawBytes stays put at 64.7 KB spare so both halves come up for one re-measure
// together instead of each dragging main red on its own.
transferBytes: 1_690_000,
- // Library locale messages: 5,499,994 to 5,502,720 raw bytes, still 85 eager chunks.
- rawBytes: 5_510_000,
+ // same-toolchain merge comparison: 5381.0 to 5384.0 kib raw, with 84 eager chunks.
+ rawBytes: 5_520_000,
};
// The chunk count is reported but not budgeted. Splitting a page out of the entry raises it while lowering the
diff --git a/studio/frontend/smoke-composer-settings-main.tsx b/studio/frontend/smoke-composer-settings-main.tsx
new file mode 100644
index 00000000000..ca2fb3e57e4
--- /dev/null
+++ b/studio/frontend/smoke-composer-settings-main.tsx
@@ -0,0 +1,88 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Production settings, preview, preferences and assistant-ui input. No backend.
+import { useState } from "react";
+import { createRoot } from "react-dom/client";
+import {
+ AssistantRuntimeProvider,
+ ComposerPrimitive,
+ useLocalRuntime,
+ useAui,
+ useAuiState,
+} from "@assistant-ui/react";
+import { ComposerSettings } from "@/features/settings/components/composer-settings";
+import { ComposerDraftPreview } from "@/components/assistant-ui/composer-draft-preview";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import { useChatPreferencesStore } from "@/features/chat/stores/chat-preferences-store";
+import {
+ composerSubmitIntent,
+ composerFollowUpBehavior,
+} from "@/features/chat/utils/composer-preferences";
+import "./src/index.css";
+
+function Draft() {
+ const aui = useAui();
+ const text = useAuiState((s) => s.composer.text);
+ const prefs = useChatPreferencesStore();
+ const [sent, setSent] = useState<{ text: string; behavior: string }[]>([]);
+ return (
+ <div className="mt-8">
+ <ComposerPrimitive.Root
+ className="rounded-3xl border border-border bg-background p-5 shadow-sm"
+ onSubmit={(e) => e.preventDefault()}
+ >
+ <ComposerDraftPreview text={text} />
+ <ComposerPrimitive.Input
+ aria-label="Message"
+ placeholder="Ask anything"
+ submitMode="none"
+ className="min-h-24 w-full resize-none bg-transparent text-sm outline-none"
+ onKeyDown={(e) => {
+ const intent = composerSubmitIntent(
+ { ...e, isComposing: e.nativeEvent.isComposing },
+ prefs.sendShortcut,
+ );
+ if (!intent) return;
+ e.preventDefault();
+ setSent((old) => [
+ ...old,
+ {
+ text: aui.composer().getState().text,
+ behavior: composerFollowUpBehavior(
+ prefs.followUpBehavior,
+ intent,
+ ),
+ },
+ ]);
+ aui.composer().setText("");
+ }}
+ />
+ <div className="mt-3 text-xs text-muted-foreground">
+ Try your send shortcut here
+ </div>
+ </ComposerPrimitive.Root>
+ <output aria-label="Submitted messages" className="sr-only">
+ {JSON.stringify(sent)}
+ </output>
+ </div>
+ );
+}
+function App() {
+ const runtime = useLocalRuntime({
+ async *run() {
+ yield { content: [{ type: "text", text: "Fixture" }] };
+ },
+ });
+ return (
+ <AssistantRuntimeProvider runtime={runtime}>
+ <TooltipProvider>
+ <main className="mx-auto max-w-4xl px-5 py-12">
+ <ComposerSettings />
+ <Draft />
+ </main>
+ </TooltipProvider>
+ </AssistantRuntimeProvider>
+ );
+}
+createRoot(document.getElementById("root")!).render(<App />);
diff --git a/studio/frontend/smoke-composer-settings.html b/studio/frontend/smoke-composer-settings.html
new file mode 100644
index 00000000000..1f7af7c2043
--- /dev/null
+++ b/studio/frontend/smoke-composer-settings.html
@@ -0,0 +1,2 @@
+<!doctype html>
+<html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Composer settings smoke test</title></head><body><div id="root"></div><script src="/crypto-boot.js"></script><script type="module" src="/smoke-composer-settings-main.tsx"></script></body></html>
diff --git a/studio/frontend/smoke-prompt-queue-actions-main.tsx b/studio/frontend/smoke-prompt-queue-actions-main.tsx
new file mode 100644
index 00000000000..1c26cd443f1
--- /dev/null
+++ b/studio/frontend/smoke-prompt-queue-actions-main.tsx
@@ -0,0 +1,180 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Mount the real view against an in-memory queue; no model or backend is needed.
+import { StrictMode, useState } from "react";
+import { createRoot } from "react-dom/client";
+import { MotionConfig } from "motion/react";
+import { PromptQueueList } from "@/components/assistant-ui/lazy-prompt-queue-list";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import {
+ type PromptQueueUIItem,
+ reorderPromptQueueItems,
+ useChatPreferencesStore,
+} from "@/features/chat";
+import "./src/index.css";
+
+const queueSize = Math.max(
+ 3,
+ Math.min(500, Number(new URLSearchParams(location.search).get("size")) || 3),
+);
+const initialItems: PromptQueueUIItem[] = Array.from(
+ { length: queueSize },
+ (_, index) => ({
+ id: `q${index}`,
+ runId: "smoke",
+ prompt:
+ ["First prompt", "Second prompt", "Third prompt"][index] ??
+ `Prompt ${index + 1}`,
+ position: index + 1,
+ total: queueSize,
+ status: "queued",
+ threadIds: ["smoke"],
+ canEdit: true,
+ canRemove: true,
+ }),
+);
+
+function App() {
+ const followUpBehavior = useChatPreferencesStore((s) => s.followUpBehavior);
+ const [items, setItems] = useState(initialItems);
+ const [paused, setPaused] = useState(false);
+ const [rejectMoves, setRejectMoves] = useState(false);
+ const [steered, setSteered] = useState("");
+ const [moveAttempts, setMoveAttempts] = useState(0);
+ const [draft, setDraft] = useState("Unsent composer draft");
+ const [submissions, setSubmissions] = useState(0);
+ return (
+ <TooltipProvider>
+ <div style={{ padding: 16 }}>
+ <button
+ type="button"
+ onClick={() => {
+ setItems(initialItems);
+ setPaused(false);
+ setRejectMoves(false);
+ setSteered("");
+ setMoveAttempts(0);
+ setDraft("Unsent composer draft");
+ setSubmissions(0);
+ useChatPreferencesStore.getState().setFollowUpBehavior("queue");
+ }}
+ >
+ Reset fixture
+ </button>
+ <button type="button" onClick={() => setRejectMoves(true)}>
+ Simulate dispatch race
+ </button>
+ <button type="button" onClick={() => setPaused(true)}>
+ Simulate paused queue
+ </button>
+ <button type="button" onClick={() => setItems((old) => old.slice(1))}>
+ Dispatch first
+ </button>
+ <button
+ type="button"
+ onClick={() => {
+ setMoveAttempts(0);
+ setItems(
+ Array.from({ length: 12 }, (_, index) => ({
+ ...initialItems[0],
+ id: `long-${index}`,
+ prompt: `Queued prompt ${index + 1}`,
+ position: index + 1,
+ total: 12,
+ })),
+ );
+ }}
+ >
+ Long queue
+ </button>
+ <button
+ type="button"
+ onClick={() =>
+ setItems((old) =>
+ old.map((item) => ({
+ ...item,
+ canEdit: false,
+ canRemove: false,
+ })),
+ )
+ }
+ >
+ Lock prompts
+ </button>
+ <output aria-label="Steered prompt">{steered}</output>
+ <output aria-label="Follow-up behavior">{followUpBehavior}</output>
+ <output aria-label="Move attempts">{moveAttempts}</output>
+ </div>
+ <form
+ style={{ maxWidth: 850, margin: "180px auto 0" }}
+ onSubmit={(event) => {
+ event.preventDefault();
+ setSubmissions((count) => count + 1);
+ setDraft("");
+ }}
+ >
+ <PromptQueueList
+ entry={{
+ runId: "smoke",
+ current: 1,
+ total: items.length,
+ local: true,
+ temporary: false,
+ dispatched: false,
+ paused,
+ }}
+ items={items}
+ onEdit={(id, prompt) => {
+ setItems((old) =>
+ old.map((item) =>
+ item.id === id ? { ...item, prompt: prompt.trim() } : item,
+ ),
+ );
+ return true;
+ }}
+ onRemove={(id) => {
+ setItems((old) => old.filter((item) => item.id !== id));
+ return true;
+ }}
+ onMove={(id, targetId) => {
+ setMoveAttempts((count) => count + 1);
+ if (rejectMoves) return false;
+ const reordered = reorderPromptQueueItems(
+ items,
+ items.findIndex((item) => item.id === id),
+ items.findIndex((item) => item.id === targetId),
+ );
+ if (!reordered) return false;
+ setItems(reordered);
+ return true;
+ }}
+ onSteer={(id) => {
+ if (rejectMoves) return false;
+ const item = items.find((item) => item.id === id);
+ if (!item) return false;
+ setSteered(item.prompt);
+ setItems((old) => old.filter((item) => item.id !== id));
+ setPaused(false);
+ return true;
+ }}
+ onResume={() => setPaused(false)}
+ />
+ <textarea
+ aria-label="Composer draft"
+ value={draft}
+ onChange={(event) => setDraft(event.currentTarget.value)}
+ />
+ <output aria-label="Composer submissions">{submissions}</output>
+ </form>
+ </TooltipProvider>
+ );
+}
+
+createRoot(document.getElementById("root")!).render(
+ <StrictMode>
+ <MotionConfig reducedMotion="user">
+ <App />
+ </MotionConfig>
+ </StrictMode>,
+);
diff --git a/studio/frontend/smoke-prompt-queue-actions.html b/studio/frontend/smoke-prompt-queue-actions.html
new file mode 100644
index 00000000000..9413a94a40c
--- /dev/null
+++ b/studio/frontend/smoke-prompt-queue-actions.html
@@ -0,0 +1,5 @@
+<!doctype html>
+<html lang="en">
+ <head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Prompt queue actions smoke test</title></head>
+ <body><div id="root"></div><script src="/crypto-boot.js"></script><script type="module" src="/smoke-prompt-queue-actions-main.tsx"></script></body>
+</html>
diff --git a/studio/frontend/src/components/assistant-ui/composer-draft-preview.tsx b/studio/frontend/src/components/assistant-ui/composer-draft-preview.tsx
new file mode 100644
index 00000000000..2f9a9d78dc8
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/composer-draft-preview.tsx
@@ -0,0 +1,44 @@
+// 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 { useDeferredValue, type ComponentProps } from "react";
+import { Streamdown } from "streamdown";
+import { useChatPreferencesStore } from "@/features/chat";
+import { useT } from "@/i18n";
+
+// Render draft URLs without navigation or image requests.
+const components: NonNullable<ComponentProps<typeof Streamdown>["components"]> =
+ {
+ a: ({ children }) => (
+ <span className="text-primary underline">{children}</span>
+ ),
+ img: ({ alt }) => (
+ <span className="text-muted-foreground">[{alt || "image"}]</span>
+ ),
+ };
+
+export function ComposerDraftPreview({ text }: { text: string }) {
+ const plain = useChatPreferencesStore((s) => s.plainTextComposer);
+ const draft = useDeferredValue(text);
+ const t = useT();
+ if (plain || !text.trim() || !draft.trim()) return null;
+ return (
+ <section
+ aria-label={t("composerSettings.preview")}
+ className="mb-3 max-h-48 min-w-0 overflow-auto rounded-xl border border-border/60 bg-muted/20 p-3 text-sm"
+ >
+ <div className="mb-2 text-xs text-muted-foreground">
+ {t("composerSettings.preview")}
+ </div>
+ <Streamdown
+ mode="static"
+ controls={false}
+ components={components}
+ skipHtml
+ className="min-w-0 space-y-2 [overflow-wrap:anywhere] [&_pre]:whitespace-pre-wrap [&_table]:block [&_table]:overflow-x-auto"
+ >
+ {draft}
+ </Streamdown>
+ </section>
+ );
+}
diff --git a/studio/frontend/src/components/assistant-ui/lazy-prompt-queue-list.tsx b/studio/frontend/src/components/assistant-ui/lazy-prompt-queue-list.tsx
new file mode 100644
index 00000000000..df9e57b3ea5
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/lazy-prompt-queue-list.tsx
@@ -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 { lazy, Suspense, type ComponentProps } from "react";
+import type { PromptQueueList as QueueList } from "./prompt-queue-list";
+
+const List = lazy(() =>
+ import("./prompt-queue-list").then((module) => ({
+ default: module.PromptQueueList,
+ })),
+);
+
+export function PromptQueueList(props: ComponentProps<typeof QueueList>) {
+ return (
+ <Suspense
+ fallback={
+ <div role="status" className="px-5 py-2 text-sm text-muted-foreground">
+ Loading queued prompts
+ </div>
+ }
+ >
+ <List {...props} />
+ </Suspense>
+ );
+}
diff --git a/studio/frontend/src/components/assistant-ui/prompt-queue-list.tsx b/studio/frontend/src/components/assistant-ui/prompt-queue-list.tsx
new file mode 100644
index 00000000000..a7fb83b446f
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/prompt-queue-list.tsx
@@ -0,0 +1,359 @@
+// 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 { useEffect, useId, useRef, useState } from "react";
+import {
+ CornerDownRightIcon,
+ GripVerticalIcon,
+ ListEndIcon,
+ MoreHorizontalIcon,
+ PlayIcon,
+} from "lucide-react";
+import {
+ Copy01Icon,
+ Delete02Icon,
+ Edit03Icon,
+} from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+} from "@/components/ui/dropdown-menu";
+import { NonModalDropdownMenu } from "@/components/ui/non-modal-dropdown-menu";
+import { usePromptQueueReorder } from "./use-prompt-queue-reorder";
+import { TooltipIconButton } from "@/components/assistant-ui/tooltip-icon-button";
+import {
+ type PromptQueueUIEntry,
+ type PromptQueueUIItem,
+ useChatPreferencesStore,
+} from "@/features/chat";
+import { copyToClipboard } from "@/lib/copy-to-clipboard";
+import { cn } from "@/lib/utils";
+
+type PromptQueueListProps = {
+ entry: PromptQueueUIEntry;
+ items: PromptQueueUIItem[];
+ onEdit: (id: string, prompt: string) => boolean;
+ onRemove: (id: string) => boolean;
+ onMove: (id: string, targetId: string) => boolean;
+ onSteer: (id: string) => boolean;
+ onResume: () => void;
+};
+
+/** The queue engine owns dispatch and validates every mutation against live IDs. */
+export function PromptQueueList({
+ entry,
+ items,
+ onEdit,
+ onRemove,
+ onMove,
+ onSteer,
+ onResume,
+}: PromptQueueListProps) {
+ const followUpBehavior = useChatPreferencesStore((s) => s.followUpBehavior);
+ const setFollowUpBehavior = useChatPreferencesStore((s) => s.setFollowUpBehavior);
+ const [editingId, setEditingId] = useState<string | null>(null);
+ const [draft, setDraft] = useState("");
+ const [announcement, setAnnouncement] = useState("");
+ const inputRef = useRef<HTMLTextAreaElement>(null);
+ const editFromMenuRef = useRef(false);
+ const instructionsId = useId();
+ const editingItem = items.find(
+ (item) => item.id === editingId && item.canEdit,
+ );
+ const activeEditingId = editingItem?.id;
+ const movableItems = items.filter((item) => item.canEdit && item.canRemove);
+ const {
+ listRef,
+ draggingId,
+ move,
+ cancelDrag,
+ onPointerDown,
+ onPointerMove,
+ onPointerUp,
+ } = usePromptQueueReorder(
+ items,
+ Boolean(activeEditingId),
+ onMove,
+ setAnnouncement,
+ );
+
+ useEffect(() => {
+ if (!activeEditingId) return;
+ inputRef.current?.focus();
+ inputRef.current?.select();
+ }, [activeEditingId]);
+
+ function startEditing(item: PromptQueueUIItem) {
+ setDraft(item.prompt);
+ setEditingId(item.id);
+ }
+
+ function finishEditing() {
+ const id = editingId;
+ setEditingId(null);
+ setDraft("");
+ // The editor replaces its row controls. Restore focus once they return.
+ requestAnimationFrame(() => {
+ const row = Array.from(
+ listRef.current?.querySelectorAll<HTMLElement>(
+ "[data-queue-item-id]",
+ ) ?? [],
+ ).find((element) => element.dataset.queueItemId === id);
+ row?.querySelector<HTMLButtonElement>("[data-queue-menu]")?.focus();
+ });
+ }
+
+ function saveEditing() {
+ if (!editingItem || !draft.trim()) return;
+ if (onEdit(editingItem.id, draft)) {
+ setAnnouncement("Queued prompt updated.");
+ finishEditing();
+ } else {
+ setAnnouncement(
+ "This prompt can no longer be edited because the queue changed.",
+ );
+ }
+ }
+
+ return (
+ <div
+ ref={listRef}
+ className="relative z-0 mx-3 mb-[-8px] max-h-[28dvh] overflow-y-auto rounded-t-[20px] border border-border/60 bg-background px-1.5 pt-1 pb-3 text-muted-foreground sm:mx-5 sm:px-2 dark:bg-card [&_button]:border-0 [&_button]:shadow-none [&_.aui-button-icon:focus-visible]:bg-accent"
+ aria-label={`Prompt queue, ${entry.current} of ${entry.total}`}
+ >
+ <p id={instructionsId} className="sr-only">
+ Drag the handle to reorder. With the handle focused, use Up or Down to
+ move one position, or Home or End to move to the front or end.
+ </p>
+ <div role="status" aria-live="polite" className="sr-only">
+ {announcement}
+ </div>
+ <div role="list" aria-label="Queued prompts">
+ {items.map((item, index) => {
+ const isEditing = editingItem?.id === item.id;
+ const position = index + 1;
+ const moveIndex = movableItems.findIndex(
+ (candidate) => candidate.id === item.id,
+ );
+ const canMove =
+ !activeEditingId && moveIndex >= 0 && movableItems.length > 1;
+ const previous = movableItems[moveIndex - 1];
+ const next = movableItems[moveIndex + 1];
+ return (
+ <div
+ key={item.id}
+ role="listitem"
+ data-queue-item-id={item.id}
+ data-queue-dragging={draggingId === item.id || undefined}
+ aria-label={`Queued prompt ${position} of ${items.length}: ${item.prompt}`}
+ className={cn(
+ "group relative rounded-lg transition-colors",
+ draggingId && "will-change-transform",
+ draggingId === item.id && "z-10 opacity-50",
+ )}
+ >
+ {isEditing ? (
+ <div className="flex flex-wrap items-center justify-end gap-2 px-1 py-2">
+ <textarea
+ ref={inputRef}
+ value={draft}
+ rows={2}
+ onChange={(event) => setDraft(event.currentTarget.value)}
+ onKeyDown={(event) => {
+ if (
+ event.nativeEvent.isComposing ||
+ event.nativeEvent.keyCode === 229 ||
+ event.repeat
+ ) return;
+ if (
+ event.key === "Enter" &&
+ (event.metaKey || event.ctrlKey)
+ ) {
+ event.preventDefault();
+ event.stopPropagation();
+ saveEditing();
+ } else if (event.key === "Escape") {
+ event.preventDefault();
+ event.stopPropagation();
+ finishEditing();
+ }
+ }}
+ className="max-h-40 min-h-16 w-full resize-y rounded-lg border border-border bg-background px-3 py-2 text-sm text-foreground focus-visible:outline focus-visible:outline-ring"
+ aria-label={`Edit queued prompt ${position}`}
+ />
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="focus-visible:bg-accent"
+ onClick={finishEditing}
+ >
+ Cancel
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ className="focus-visible:bg-primary/80"
+ disabled={!draft.trim()}
+ onClick={saveEditing}
+ >
+ Save
+ </Button>
+ </div>
+ ) : (
+ <div className="flex min-h-11 items-center gap-1 sm:min-h-12">
+ <TooltipIconButton
+ type="button"
+ tooltip="Drag to reorder"
+ aria-label={`Reorder queued prompt ${position} of ${items.length}`}
+ aria-describedby={instructionsId}
+ className="h-8 w-4 shrink-0 touch-none cursor-grab text-muted-foreground/50 hover:text-muted-foreground active:cursor-grabbing pointer-coarse:h-11 pointer-coarse:w-8"
+ disabled={!canMove}
+ onPointerDown={(event) => onPointerDown(event, item.id)}
+ onPointerMove={onPointerMove}
+ onPointerUp={onPointerUp}
+ onPointerCancel={cancelDrag}
+ onLostPointerCapture={cancelDrag}
+ onKeyDown={(event) => {
+ if (event.key === "Escape" && cancelDrag()) {
+ event.preventDefault();
+ event.stopPropagation();
+ return;
+ }
+ const targets: Record<string, string | undefined> = {
+ ArrowUp: previous?.id,
+ ArrowDown: next?.id,
+ Home: movableItems[0]?.id,
+ End: movableItems.at(-1)?.id,
+ };
+ if (!(event.key in targets)) return;
+ event.preventDefault();
+ event.stopPropagation();
+ move(item.id, targets[event.key]);
+ }}
+ >
+ <GripVerticalIcon className="size-4" />
+ </TooltipIconButton>
+ <ListEndIcon
+ className="hidden size-4 shrink-0 text-muted-foreground/60 sm:block"
+ aria-hidden="true"
+ />
+ <span className="min-w-0 flex-1 truncate px-1.5 text-sm text-foreground/80">
+ {item.prompt}
+ </span>
+ {index === 0 && entry.paused && (
+ <span className="hidden shrink-0 px-1 text-xs text-muted-foreground sm:inline">
+ Paused
+ </span>
+ )}
+ <TooltipIconButton
+ type="button"
+ tooltip="Interrupt the response and send this prompt next"
+ aria-label={`Steer with queued prompt ${position}`}
+ disabled={!item.canEdit || !item.canRemove}
+ className="h-8 w-auto shrink-0 gap-1.5 px-2 font-normal text-muted-foreground hover:text-foreground pointer-coarse:h-11"
+ onClick={() => {
+ setAnnouncement(
+ onSteer(item.id)
+ ? "This prompt will steer the response next."
+ : "This prompt could not steer the response. Check the queue and try again.",
+ );
+ }}
+ >
+ <CornerDownRightIcon className="size-4" />
+ <span>Steer</span>
+ </TooltipIconButton>
+ <TooltipIconButton
+ type="button"
+ tooltip="Remove from queue"
+ aria-label={`Remove queued prompt ${position}`}
+ disabled={!item.canRemove}
+ className="size-8 shrink-0 text-muted-foreground hover:text-destructive pointer-coarse:size-11"
+ onClick={() => {
+ if (onRemove(item.id))
+ setAnnouncement("Prompt removed from queue.");
+ }}
+ >
+ <HugeiconsIcon icon={Delete02Icon} strokeWidth={1.8} />
+ </TooltipIconButton>
+ <NonModalDropdownMenu
+ trigger={(triggerRef) => (
+ <TooltipIconButton
+ ref={triggerRef}
+ tooltip="More options"
+ data-queue-menu
+ aria-label={`More options for queued prompt ${position}`}
+ className="size-8 shrink-0 text-muted-foreground hover:text-foreground data-[state=open]:bg-accent data-[state=open]:text-foreground pointer-coarse:size-11"
+ >
+ <MoreHorizontalIcon className="size-4" />
+ </TooltipIconButton>
+ )}
+ align="end"
+ side="bottom"
+ sideOffset={6}
+ className="w-56 rounded-2xl border border-border/60 p-1.5 shadow-lg"
+ // Opening the menu must not select an item on pointer release.
+ onPointerUpCapture={(event) => event.preventDefault()}
+ onCloseAutoFocus={(event) => {
+ if (!editFromMenuRef.current) return;
+ event.preventDefault();
+ editFromMenuRef.current = false;
+ inputRef.current?.focus();
+ }}
+ >
+ <DropdownMenuItem
+ disabled={!item.canEdit}
+ onSelect={() => {
+ editFromMenuRef.current = true;
+ startEditing(item);
+ }}
+ >
+ <HugeiconsIcon icon={Edit03Icon} strokeWidth={1.8} /> Edit
+ message
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onSelect={() => {
+ void copyToClipboard(item.prompt).then((copied) =>
+ setAnnouncement(
+ copied
+ ? "Prompt copied."
+ : "Could not copy this prompt. Try again.",
+ ),
+ );
+ }}
+ >
+ <HugeiconsIcon icon={Copy01Icon} strokeWidth={1.8} /> Copy
+ message
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onSelect={() => {
+ const behavior = followUpBehavior === "queue" ? "steer" : "queue";
+ setFollowUpBehavior(behavior);
+ setAnnouncement(
+ behavior === "queue"
+ ? "New follow-ups will queue after the current response."
+ : "New follow-ups will steer the current response.",
+ );
+ }}
+ >
+ <ListEndIcon />
+ {followUpBehavior === "queue" ? "Turn off queueing" : "Turn on queueing"}
+ </DropdownMenuItem>
+ {entry.paused && (
+ <DropdownMenuItem onSelect={onResume}>
+ <PlayIcon /> Resume queue
+ </DropdownMenuItem>
+ )}
+ </NonModalDropdownMenu>
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ );
+}
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index 804e79fc564..08b6781b715 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -21,6 +21,8 @@ import {
MessageResponseDetailsSheet,
MessageResponseModelBadge,
} from "@/components/assistant-ui/message-response-details-sheet";
+import { ComposerDraftPreview } from "@/components/assistant-ui/composer-draft-preview";
+import { PromptQueueList } from "@/components/assistant-ui/lazy-prompt-queue-list";
import { ProgressiveMessages } from "@/components/assistant-ui/progressive-messages";
import { MessageTiming } from "@/components/assistant-ui/message-timing";
import { attachThreadFastCopy } from "@/components/assistant-ui/thread-fast-copy";
@@ -52,13 +54,17 @@ import { WebSearchToolUI } from "@/components/assistant-ui/tool-ui-web-search";
import { ChatDictationBar } from "@/components/assistant-ui/chat-dictation-bar";
import {
ChatSkillsDialog,
-
- PROMPT_QUEUE_DRAG_TYPE,
+ composerSubmitIntent,
+ composerFollowUpBehavior,
+ composerShortcutLabels,
+ steeringInsertionIndex,
+ cancelPreStreamRunForThreadIds,
+ type ComposerSendShortcut,
+ type ComposerSubmitIntent,
+ type ComposerFollowUpBehavior,
attachmentsPastedText,
hasPendingPromptQueueStart,
isPastedTextFile,
- isPromptQueueChord,
- isPromptQueueDragTypes,
pastedTextQueueKey,
promptQueueActiveItemChanged,
reorderPromptQueueItems,
@@ -162,8 +168,11 @@ import {
COMPOSER_INPUT_SELECTOR,
isSurfaceInForeground,
useShortcut,
+ useSettingsDialogStore,
+ isMacPlatform,
} from "@/features/settings";
import { FIND_SKIP_ATTRIBUTE } from "@/features/find-in-page";
+import { useT } from "@/i18n";
import { create } from "zustand";
import {
clampReasoningEffortToLevels,
@@ -312,7 +321,8 @@ import {
ChevronLeftIcon,
ChevronRightIcon,
Columns2Icon,
- CornerDownRightIcon,
+ SlidersHorizontalIcon,
+ CornerUpRightIcon,
FastForwardIcon,
GitBranchIcon,
GlobeIcon,
@@ -390,6 +400,7 @@ type PromptQueueItem = {
target: PromptQueueTarget;
dispatched: boolean;
dispatchRetries: number;
+ blockedByModelFailure?: boolean;
};
type PromptQueueRun = {
@@ -642,7 +653,7 @@ function isActivePromptQueueItem(
if (promptQueueRuns.get(run.id) !== run || generation !== run.generation) {
return false;
}
- return getActivePromptQueueItem(run) === item;
+ return getActivePromptQueueItem(run) === item && !item.blockedByModelFailure;
}
function scheduleQueuedPromptDispatch(
@@ -666,6 +677,7 @@ function isPromptQueueRunReadyToDispatch(run: PromptQueueRun) {
item &&
run.index >= 0 &&
!item.dispatched &&
+ !item.blockedByModelFailure &&
!run.waitingForTargetIdle &&
!run.paused &&
!run.retryTimer &&
@@ -746,6 +758,11 @@ async function dispatchQueuedPrompt(
if (!isActivePromptQueueItem(run, item, generation)) {
return;
}
+ // Keep prompts editable until the local model finishes loading.
+ if (item.target.usesLocalModel && useChatRuntimeStore.getState().modelLoading) {
+ scheduleQueuedPromptDispatch(run, item, PROMPT_QUEUE_DISPATCH_RETRY_MS);
+ return;
+ }
if (
isPromptQueueTargetRunning(
item.target,
@@ -768,7 +785,11 @@ async function dispatchQueuedPrompt(
if (!isActivePromptQueueItem(run, item, generation)) {
return;
}
- if (hasIndexingDocuments) {
+ // Recheck loading after the document probe.
+ if (
+ hasIndexingDocuments ||
+ (item.target.usesLocalModel && useChatRuntimeStore.getState().modelLoading)
+ ) {
promptQueueActiveRunIds.delete(run.id);
scheduleQueuedPromptDispatch(run, item, PROMPT_QUEUE_INDEXING_RETRY_MS);
return;
@@ -897,6 +918,7 @@ function getPromptQueueItemStatus(
index: number,
activeItemIndex: number,
): PromptQueueUIItemStatus {
+ if (run.items[index]?.blockedByModelFailure) return "paused";
if (run.paused && run.index >= 0 && index === activeItemIndex) {
return "paused";
}
@@ -963,7 +985,7 @@ function syncPromptQueueUI() {
local: promptQueueRunUsesLocalModel(run),
temporary: promptQueueRunIsTemporary(run),
dispatched: Boolean(getActivePromptQueueItem(run)?.dispatched),
- paused: run.paused,
+ paused: run.paused || run.items.some((item) => item.blockedByModelFailure),
};
for (const id of ids) {
byThreadId[id] = entry;
@@ -1244,24 +1266,81 @@ function ensurePromptQueueSubscription() {
});
}
+function steerPromptQueueTarget(target: PromptQueueTarget) {
+ const targetIds = getPromptQueueTargetIds(target);
+ const run = findPromptQueueRunByTarget(target);
+ const active = run && run.index >= 0 ? getActivePromptQueueItem(run) : null;
+ const cancelledTarget = active?.dispatched ? active.target : null;
+ pausePromptQueueRun(targetIds);
+ cancelPreStreamRunForThreadIds(targetIds);
+ try {
+ // Pausing already cancels the dispatched target once.
+ if (cancelledTarget !== target) target.cancelActiveRun();
+ } catch {
+ toast.info("Your follow-up is queued next", {
+ description: "The current response could not be interrupted.",
+ });
+ }
+ // Dispatch waits for cancellation to finish.
+ resumePromptQueueRun(targetIds);
+}
+
+function steerPromptQueueItem(itemId: string) {
+ const match = findPromptQueueRunByItemId(itemId);
+ if (!match) return false;
+ const { run, itemIndex, item } = match;
+ if (
+ item.dispatched ||
+ itemIndex < Math.max(run.index, 0) ||
+ getPromptQueueTargetIds(item.target).length === 0
+ ) {
+ return false;
+ }
+ if (item.target.researchStarted()) {
+ toast.info("Research is still running", {
+ description: "Stop research before steering with a queued prompt.",
+ });
+ return false;
+ }
+ // Move the existing item so its captured settings and identity stay intact.
+ run.items.splice(itemIndex, 1);
+ run.items.splice(steeringInsertionIndex(run.items, run.index), 0, item);
+ steerPromptQueueTarget(item.target);
+ return true;
+}
+
function startPromptQueue(
items: string[],
target: PromptQueueTarget,
waitForCurrentRun = false,
+ behavior: ComposerFollowUpBehavior = "queue",
) {
const filtered = items.map((item) => item.trim()).filter(Boolean);
if (filtered.length === 0) {
return;
}
+ const steering = behavior === "steer";
+ const targetIds = getPromptQueueTargetIds(target);
+ if (steering && targetIds.length === 0) {
+ throw new Error("The chat is no longer available for steering.");
+ }
const existingRun = findPromptQueueRunByTarget(target);
if (existingRun) {
if (existingRun.deepResearchConsumed) {
target.consumeDeepResearch();
}
- existingRun.items.push(
- ...filtered.map((prompt) => createQueuedPrompt(prompt, target)),
- );
+ const newItems = filtered.map((prompt) => createQueuedPrompt(prompt, target));
+ if (steering) {
+ existingRun.items.splice(
+ steeringInsertionIndex(existingRun.items, existingRun.index),
+ 0,
+ ...newItems,
+ );
+ steerPromptQueueTarget(target);
+ return;
+ }
+ existingRun.items.push(...newItems);
syncPromptQueueUI();
requestPromptQueuePump();
return;
@@ -1269,7 +1348,7 @@ function startPromptQueue(
const runningByThreadId = useChatRuntimeStore.getState().runningByThreadId;
const shouldWaitForCurrentRun =
- waitForCurrentRun &&
+ (waitForCurrentRun || steering) &&
isPromptQueueTargetRunning(target, runningByThreadId);
const run: PromptQueueRun = {
id: createPromptQueueRunId(),
@@ -1286,6 +1365,10 @@ function startPromptQueue(
promptQueueRunOrder.push(run.id);
syncPromptQueueUI();
ensurePromptQueueSubscription();
+ if (steering) {
+ steerPromptQueueTarget(target);
+ return;
+ }
if (shouldWaitForCurrentRun) {
handlePromptQueueRunState(
run,
@@ -1364,6 +1447,10 @@ function pausePromptQueueRun(threadIds?: string[]) {
function resumePromptQueueRun(threadIds?: string[]) {
for (const run of getPromptQueueRunsForThreadIds(threadIds)) {
+ if (run.items.some((item) => item.blockedByModelFailure)) {
+ for (const item of run.items) item.blockedByModelFailure = false;
+ syncPromptQueueUI();
+ }
if (!run.paused) {
continue;
}
@@ -1544,15 +1631,32 @@ function stopAllPromptQueueRuns() {
}
}
-function handlePromptQueueRunFailed(threadId?: string | null) {
+function handlePromptQueueRunFailed(threadId?: string | null, localOnly = false) {
+ if (localOnly) {
+ for (const run of promptQueueRuns.values()) {
+ for (const item of run.items.slice(Math.max(run.index, 0))) {
+ if (item.target.usesLocalModel && !item.dispatched) {
+ item.blockedByModelFailure = true;
+ }
+ }
+ if (getActivePromptQueueItem(run)?.blockedByModelFailure) {
+ // Invalidate the failed local attempt without disturbing external work.
+ run.generation += 1;
+ clearPromptQueueRetryTimer(run);
+ promptQueueDispatchingRunIds.delete(run.id);
+ promptQueueActiveRunIds.delete(run.id);
+ }
+ }
+ syncPromptQueueUI();
+ return;
+ }
if (threadId) {
const failedRun = findPromptQueueRunByThreadIds([threadId]);
if (failedRun) {
if (!retainPendingPromptQueueItemsAfterFailure(failedRun)) {
- // A direct-send preflight failure invalidates follow-ups that were
- // waiting for that run to establish a usable thread.
+ // Keep accepted follow-ups editable after a failed load or preflight.
discardQueuedChatRunSettingsForThread(threadId);
- deletePromptQueueRun(failedRun);
+ pausePromptQueueRun([threadId]);
}
} else {
discardQueuedChatRunSettingsForThread(threadId);
@@ -1581,9 +1685,9 @@ if (typeof window !== "undefined") {
stopAllPromptQueueRuns();
});
window.addEventListener(PROMPT_QUEUE_RUN_FAILED_EVENT, (event) => {
- const { threadId } =
+ const { threadId, localOnly } =
(event as CustomEvent<PromptQueueRunFailedEventDetail>).detail ?? {};
- handlePromptQueueRunFailed(threadId);
+ handlePromptQueueRunFailed(threadId, localOnly);
});
}
@@ -2452,22 +2556,17 @@ const Composer: FC<{
const pastedTextMinChars = useChatPreferencesStore(
(state) => state.pastedTextMinChars,
);
- // Set by Cmd/Ctrl+Enter and read once by the handleSubmit that requestSubmit
- // reaches synchronously. Armed only when that call will happen: with no form,
- // or no requestSubmit, it would stay armed and queue whatever submit came
- // next.
- const forceQueueRef = useRef(false);
- const queueOnModEnter = useCallback(
- (event: KeyboardEvent<HTMLTextAreaElement>) => {
+ const sendShortcut = useChatPreferencesStore((s) => s.sendShortcut);
+ const submitIntentRef = useRef<ComposerSubmitIntent>("default");
+ const submitOnKey = useCallback(
+ (event: KeyboardEvent<HTMLTextAreaElement>, intent: ComposerSubmitIntent) => {
const form = event.currentTarget.form;
- if (typeof form?.requestSubmit !== "function") {
- return;
- }
- forceQueueRef.current = true;
+ if (typeof form?.requestSubmit !== "function") return;
+ submitIntentRef.current = intent;
try {
form.requestSubmit();
- } catch {
- forceQueueRef.current = false;
+ } finally {
+ submitIntentRef.current = "default";
}
},
[],
@@ -2492,7 +2591,8 @@ const Composer: FC<{
useImeComposerInputHandlers({
submitOnEnter: true,
skipEnterRef: mentionConsumesEnterRef,
- onModEnter: queueOnModEnter,
+ sendShortcut,
+ onSubmitKey: submitOnKey,
justSentRef,
draftKeyRef,
});
@@ -3513,6 +3613,8 @@ const Composer: FC<{
threadId: string | null;
localModelBoundaryGeneration: number;
queuedSettingsEpoch: number;
+ waitForCurrentRun: boolean;
+ behavior: ComposerFollowUpBehavior;
}
>(),
);
@@ -3571,10 +3673,8 @@ const Composer: FC<{
}, [aui, referenceThreadId]);
const [pendingSend, setPendingSend] = useState(false);
const pendingSendRef = useRef(false);
- // Whether the parked send is a queue gesture. A chord pressed while this
- // chat's settings load parks like any other send, and the release path would
- // otherwise send the prompt the user asked to stack.
- const pendingSendForceQueueRef = useRef(false);
+ // Retain follow-up behavior across preflight waits.
+ const pendingFollowUpBehaviorRef = useRef<ComposerFollowUpBehavior>("queue");
const waitToastRef = useRef<string | number | null>(null);
// This chat's own settings are still on their way; a send now would run on the
// installation defaults showing in their place.
@@ -3626,8 +3726,20 @@ const Composer: FC<{
const usesKnowledgeBaseAtQueueStart =
chatStateAtQueueStart.ragEnabled &&
chatStateAtQueueStart.ragSource.type === "kb";
- const runSettingsAtQueueStart =
- snapshotQueuedChatRunSettings(chatStateAtQueueStart);
+ const runSettingsAtQueueStart = snapshotQueuedChatRunSettings(
+ chatStateAtQueueStart,
+ {
+ // Resolve the incoming model at dispatch; retain the prompt's settings.
+ deferModelResolution:
+ chatStateAtQueueStart.modelLoading &&
+ parseExternalModelId(
+ chatStateAtQueueStart.loadingModelPick &&
+ !chatStateAtQueueStart.loadingModelPick.selectionSuperseded
+ ? chatStateAtQueueStart.loadingModelPick.id
+ : chatStateAtQueueStart.params.checkpoint,
+ ) === null,
+ },
+ );
const getThreadListItemState = () => {
const runtime =
assistantRuntime ?? aui.threads().__internal_getAssistantRuntime?.();
@@ -3912,16 +4024,16 @@ const Composer: FC<{
queuedSettingsEpoch: number;
temporary: boolean;
},
+ behavior: ComposerFollowUpBehavior = "queue",
) => {
- const reservationKey = JSON.stringify([
- referenceThreadId,
- items,
- waitForCurrentRun,
- ]);
+ const reservationKey = JSON.stringify([referenceThreadId, items]);
// A reservation that is still going to start owns this prompt. One that
// is already invalid is replaced, so the retry is the one that queues.
const existing = promptQueueStartPendingRef.current.get(reservationKey);
if (existing && !pendingQueueStartIsStale(existing)) {
+ // A new shortcut updates the pending draft instead of sending it twice.
+ existing.waitForCurrentRun = waitForCurrentRun;
+ existing.behavior = behavior;
return false;
}
const reservation = {
@@ -3935,6 +4047,8 @@ const Composer: FC<{
queuedSettingsEpoch:
capturedAt?.queuedSettingsEpoch ??
useChatRuntimeStore.getState().queuedSettingsEpoch,
+ waitForCurrentRun,
+ behavior,
};
promptQueueStartPendingRef.current.set(reservationKey, reservation);
void createPromptQueueTarget()
@@ -3945,7 +4059,6 @@ const Composer: FC<{
capturedGeneration:
reservation.localModelBoundaryGeneration,
usesLocalModel: target.usesLocalModel,
- modelLoading: currentQueueSettings.modelLoading,
})
: false;
const settingsInvalidated =
@@ -3963,7 +4076,12 @@ const Composer: FC<{
promptQueueStartPendingRef.current.get(reservationKey) ===
reservation
) {
- startPromptQueue(items, target, waitForCurrentRun);
+ startPromptQueue(
+ items,
+ target,
+ reservation.waitForCurrentRun,
+ reservation.behavior,
+ );
onStarted?.();
} else if (
promptQueueStartPendingRef.current.get(reservationKey) ===
@@ -3997,7 +4115,10 @@ const Composer: FC<{
// The queue carries text, and a long paste is text the composer parked in a
// chip, so fold it back in rather than refusing to queue it as a file.
const queuePastedTextPrompt = useCallback(
- (waitForCurrentRun: boolean): boolean => {
+ (
+ waitForCurrentRun: boolean,
+ behavior: ComposerFollowUpBehavior = "queue",
+ ): boolean => {
const composer = aui.composer();
const attachments = composer.getState().attachments;
const files: File[] = [];
@@ -4051,6 +4172,7 @@ const Composer: FC<{
});
},
capturedAt,
+ behavior,
);
};
@@ -4138,23 +4260,30 @@ const Composer: FC<{
// live composer, not the rendered text, which at release time can be a commit
// behind.
const queueComposerText = useCallback(
- (waitForCurrentRun: boolean) => {
+ (waitForCurrentRun: boolean, behavior: ComposerFollowUpBehavior = "queue") => {
const queuedPrompt = aui.composer().getState().text.trim();
if (!queuedPrompt) {
return;
}
- startHydratedPromptQueue([queuedPrompt], waitForCurrentRun, () => {
- // Guard the untrimmed text too: that is what a late write carries.
- const cleared = aui.composer().getState().text;
- if (cleared.trim() !== queuedPrompt) {
- return;
- }
- flushResourcesSync(() => {
- aui.composer().setText("");
- });
- clearStoredDraft();
- armJustSent(queuedPrompt, cleared);
- });
+ startHydratedPromptQueue(
+ [queuedPrompt],
+ waitForCurrentRun,
+ () => {
+ // Guard the untrimmed text too: that is what a late write carries.
+ const cleared = aui.composer().getState().text;
+ if (cleared.trim() !== queuedPrompt) {
+ return;
+ }
+ flushResourcesSync(() => {
+ aui.composer().setText("");
+ });
+ clearStoredDraft();
+ armJustSent(queuedPrompt, cleared);
+ },
+ undefined,
+ undefined,
+ behavior,
+ );
},
[armJustSent, aui, clearStoredDraft, startHydratedPromptQueue],
);
@@ -4173,7 +4302,7 @@ const Composer: FC<{
const cancelQueuedSend = useCallback(() => {
pendingSendRef.current = false;
- pendingSendForceQueueRef.current = false;
+ pendingFollowUpBehaviorRef.current = "queue";
setPendingSend(false);
// A dictation send held behind the same block would otherwise fire alone.
sendAfterDictationRef.current = false;
@@ -4380,9 +4509,9 @@ const Composer: FC<{
return;
}
const { text, attachments } = aui.composer().getState();
- const forceQueue = pendingSendForceQueueRef.current;
+ const behavior = pendingFollowUpBehaviorRef.current;
pendingSendRef.current = false;
- pendingSendForceQueueRef.current = false;
+ pendingFollowUpBehaviorRef.current = "queue";
setPendingSend(false);
dismissWaitToast();
if (text.trim().length > 0 || attachments.length > 0) {
@@ -4404,7 +4533,10 @@ const Composer: FC<{
if (isResearchActive) {
return;
}
- if (waitForCurrentRun) {
+ const queueAlreadyActive = Boolean(
+ findPromptQueueEntry(usePromptQueueUI.getState(), preStreamThreadIds),
+ );
+ if (waitForCurrentRun || queueAlreadyActive) {
// Queueing on the project new-chat composer binds the follow-up to a
// thread that does not exist yet.
if (disableQueue) {
@@ -4414,12 +4546,15 @@ const Composer: FC<{
// queueComposerText clears the draft from its onStarted callback, so a
// queue that never starts leaves the text recoverable.
if (canQueueCurrentPrompt) {
- queueComposerText(true);
+ queueComposerText(waitForCurrentRun, behavior);
return;
}
// A long paste lives in an attachment, so queueing the text alone
// queues nothing when that is all there is.
- if (canQueuePastedTextPrompt && queuePastedTextPrompt(true)) {
+ if (
+ canQueuePastedTextPrompt &&
+ queuePastedTextPrompt(waitForCurrentRun, behavior)
+ ) {
return;
}
// Nothing queueable while a run is live: keep it and say why. Sending
@@ -4432,16 +4567,6 @@ const Composer: FC<{
}
return;
}
- // Nothing running: the chord still queues up front, as it does live.
- if (forceQueue && !disableQueue) {
- if (canQueueCurrentPrompt) {
- queueComposerText(false);
- return;
- }
- if (canQueuePastedTextPrompt && queuePastedTextPrompt(false)) {
- return;
- }
- }
clearStoredDraft();
sendReservedComposer();
}
@@ -4472,7 +4597,7 @@ const Composer: FC<{
useEffect(
() => () => {
pendingSendRef.current = false;
- pendingSendForceQueueRef.current = false;
+ pendingFollowUpBehaviorRef.current = "queue";
if (waitToastRef.current !== null) toast.dismiss(waitToastRef.current);
},
[],
@@ -4666,9 +4791,12 @@ const Composer: FC<{
preventDefault: () => void;
stopPropagation?: () => void;
}) => {
- // Read once per submit: a rejected send must not leave it armed.
- const forceQueue = forceQueueRef.current;
- forceQueueRef.current = false;
+ const behavior = composerFollowUpBehavior(
+ useChatPreferencesStore.getState().followUpBehavior,
+ submitIntentRef.current,
+ );
+ submitIntentRef.current = "default";
+ pendingFollowUpBehaviorRef.current = behavior;
if (isResearchActive) {
event.preventDefault();
return;
@@ -4683,10 +4811,6 @@ const Composer: FC<{
// defaults on screen, so a chat stored as "ask" would queue as "off".
if (threadScopedSettingsPending && !overlay) {
event.preventDefault();
- // The intent rides with the parked send; the release reads it back.
- if (forceQueue) {
- pendingSendForceQueueRef.current = true;
- }
enqueueSend("settings");
return;
}
@@ -4729,7 +4853,10 @@ const Composer: FC<{
if (!canQueueCurrentPrompt) {
if (
canQueuePastedTextPrompt &&
- queuePastedTextPrompt(liveThreadIsRunning || livePreStreamRunActive)
+ queuePastedTextPrompt(
+ liveThreadIsRunning || livePreStreamRunActive,
+ behavior,
+ )
) {
return;
}
@@ -4746,27 +4873,13 @@ const Composer: FC<{
}
return;
}
- queueComposerText(liveThreadIsRunning || livePreStreamRunActive);
+ queueComposerText(
+ liveThreadIsRunning || livePreStreamRunActive,
+ behavior,
+ );
return;
}
- // Cmd/Ctrl+Enter queues even with nothing running, so prompts can be
- // stacked up front. The queue dispatches this one immediately; the next
- // Cmd/Ctrl+Enter lands behind it.
- if (forceQueue && !disableQueue) {
- if (canQueueCurrentPrompt) {
- event.preventDefault();
- queueComposerText(false);
- return;
- }
- if (canQueuePastedTextPrompt) {
- event.preventDefault();
- if (queuePastedTextPrompt(false)) {
- return;
- }
- }
- }
-
if (interceptSend(event)) return;
if (overlay) {
@@ -4906,6 +5019,7 @@ const Composer: FC<{
onIndexingChange={handleIndexingChange}
/>
</div>
+ {!isDictating ? <ComposerDraftPreview text={composerText} /> : null}
{!isDictating ? <ToolStatusDisplay /> : null}
<div
className="unsloth-composer-line"
@@ -4968,6 +5082,7 @@ const Composer: FC<{
>
<ComposerPrimitive.Input
id={inputId}
+ submitMode="none"
placeholder={
overlay ? "Type your edits for your image" : "Ask anything"
}
@@ -5037,36 +5152,7 @@ const Composer: FC<{
disableQueue ||
!(canQueueCurrentPrompt || canQueuePastedTextPrompt)
}
- onQueueClick={() => {
- if (disableQueue) return;
- // Same pasted-text path the Enter key takes, or the button
- // would refuse what submitting the form accepts.
- if (
- canQueuePastedTextPrompt &&
- queuePastedTextPrompt(true)
- ) {
- return;
- }
- const queuedPrompt = composerText.trim();
- if (queuedPrompt.length === 0) {
- return;
- }
- startHydratedPromptQueue(
- [queuedPrompt],
- true,
- () => {
- const cleared = aui.composer().getState().text;
- if (cleared.trim() !== queuedPrompt) {
- return;
- }
- flushResourcesSync(() => {
- aui.composer().setText("");
- });
- clearStoredDraft();
- armJustSent(queuedPrompt, cleared);
- },
- );
- }}
+ onQueueClick={() => formRef.current?.requestSubmit()}
// ComposerPrimitive.Send handles clicks itself rather than
// submitting the form, so run the complete queue/capacity path.
onSendClick={handleSubmit}
@@ -5212,15 +5298,20 @@ const IME_STUCK_TIMEOUT_MS = 2500;
function useImeComposerInputHandlers({
submitOnEnter = false,
skipEnterRef,
- onModEnter,
+ onSubmitKey,
+ sendShortcut = "enter",
justSentRef,
draftKeyRef,
}: {
submitOnEnter?: boolean;
/** Set while a composer popover will consume plain Enter itself. */
skipEnterRef?: RefObject<boolean>;
- /** Cmd/Ctrl+Enter without Shift, claimed before the plain-Enter submit. */
- onModEnter?: (event: KeyboardEvent<HTMLTextAreaElement>) => void;
+ /** The selected send chord, carrying the one-message follow-up override. */
+ onSubmitKey?: (
+ event: KeyboardEvent<HTMLTextAreaElement>,
+ intent: ComposerSubmitIntent,
+ ) => void;
+ sendShortcut?: ComposerSendShortcut;
// Guard armed by the last send or queue. See setComposerText below.
justSentRef?: RefObject<SentTextGuard | null>;
// Thread on screen. The composer outlives a thread switch, so this is what
@@ -5374,24 +5465,19 @@ function useImeComposerInputHandlers({
// rather than waiting for the 2500ms watchdog.
setCompositionState(false);
}
- if (onModEnter && isPromptQueueChord(e)) {
- e.preventDefault();
- onModEnter(e);
- return;
- }
- if (
- submitOnEnter &&
- e.key === "Enter" &&
- !e.shiftKey &&
- !skipEnterRef?.current
- ) {
- e.preventDefault();
- e.currentTarget.form?.requestSubmit();
+ if (submitOnEnter && !skipEnterRef?.current) {
+ const intent = composerSubmitIntent(e, sendShortcut);
+ if (intent) {
+ e.preventDefault();
+ if (onSubmitKey) onSubmitKey(e, intent);
+ else e.currentTarget.form?.requestSubmit();
+ }
}
},
[
justSentRef,
- onModEnter,
+ onSubmitKey,
+ sendShortcut,
refreshStuckTimer,
setCompositionState,
skipEnterRef,
@@ -6019,6 +6105,7 @@ const ComposerToolsMenu: FC<{
side?: "top" | "bottom";
researchAvailable: boolean;
}> = ({ side = "bottom", researchAvailable }) => {
+ const t = useT();
const navigate = useNavigate();
const toolsEnabled = useChatRuntimeStore((s) => s.toolsEnabled);
const setToolsEnabled = useChatRuntimeStore((s) => s.setToolsEnabled);
@@ -6540,6 +6627,15 @@ const ComposerToolsMenu: FC<{
</DropdownMenuSubContent>
</DropdownMenuSub>
) : null}
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onSelect={() => useSettingsDialogStore.getState().openDialog("chat", {
+ scrollTarget: "chat-composer",
+ })}
+ >
+ <SlidersHorizontalIcon className="size-4" />
+ {t("composerSettings.settings")}
+ </DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<NewProjectDialog
@@ -6550,30 +6646,6 @@ const ComposerToolsMenu: FC<{
);
};
-function promptQueueStatusLabel(status: PromptQueueUIItemStatus) {
- switch (status) {
- case "running":
- return "Running now";
- case "waiting":
- return "Waiting";
- case "next":
- return "Next";
- case "paused":
- return "Paused";
- case "queued":
- return "Queued";
- default: {
- const exhaustiveStatus: never = status;
- throw new Error(`Unhandled prompt queue status: ${exhaustiveStatus}`);
- }
- }
-}
-
-// dataTransfer.getData is blocked during dragover, but types is always readable.
-function isPromptQueueDrag(event: ReactDragEvent): boolean {
- return isPromptQueueDragTypes(event.dataTransfer?.types);
-}
-
const PromptQueueStack: FC<{ queueThreadIds: string[] }> = ({
queueThreadIds,
}) => {
@@ -6581,223 +6653,23 @@ const PromptQueueStack: FC<{ queueThreadIds: string[] }> = ({
findPromptQueueEntry(s, queueThreadIds),
);
const items = usePromptQueueUI((s) => s.items);
- const [editingItemId, setEditingItemId] = useState<string | null>(null);
- const [draftPrompt, setDraftPrompt] = useState("");
- const [draggingItemId, setDraggingItemId] = useState<string | null>(null);
- const [dragOverItemId, setDragOverItemId] = useState<string | null>(null);
- const editInputRef = useRef<HTMLTextAreaElement>(null);
const visibleItems = queueEntry
? items.filter((item) => item.runId === queueEntry.runId)
: [];
- const editingItem = visibleItems.find((item) => item.id === editingItemId);
- const activeEditingItemId = editingItem ? editingItemId : null;
-
- useEffect(() => {
- if (!activeEditingItemId) {
- return;
- }
- editInputRef.current?.focus();
- editInputRef.current?.select();
- }, [activeEditingItemId]);
-
- if (!queueEntry || visibleItems.length === 0) {
- return null;
- }
- const { current, total } = queueEntry;
-
- const startEditing = (item: PromptQueueUIItem) => {
- if (!item.canEdit) {
- return;
- }
- setEditingItemId(item.id);
- setDraftPrompt(item.prompt);
- };
- const saveEditing = () => {
- if (!activeEditingItemId) {
- return;
- }
- if (editPromptQueueItem(activeEditingItemId, draftPrompt)) {
- setEditingItemId(null);
- setDraftPrompt("");
- }
- };
- const cancelEditing = () => {
- setEditingItemId(null);
- setDraftPrompt("");
- };
- const endDrag = () => {
- setDraggingItemId(null);
- setDragOverItemId(null);
- };
- // Keyboard equivalent of a drag, since HTML5 drag events never fire for keys.
- const moveByOffset = (index: number, offset: number) => {
- const target = visibleItems[index + offset];
- if (!target) {
- return;
- }
- movePromptQueueItem(visibleItems[index].id, target.id);
- };
- const reorderable = visibleItems.length > 1;
+ if (!queueEntry || visibleItems.length === 0) return null;
return (
- <div
- className="relative z-0 mx-7 mb-[-8px] max-h-[28dvh] overflow-y-auto rounded-t-[18px] rounded-b-none border border-border/45 bg-background/90 px-5 py-2 text-muted-foreground shadow-none backdrop-blur-md dark:bg-card/85"
- aria-label={`Prompt queue, ${current} of ${total}`}
- >
- <div className="divide-y divide-border/25">
- {visibleItems.map((item, visibleIndex) => {
- const isEditing = item.id === activeEditingItemId;
- const visiblePosition = visibleIndex + 1;
- return (
- <div
- key={item.id}
- className={cn(
- "min-h-10",
- isEditing ? "h-auto" : "h-10",
- draggingItemId === item.id && "opacity-40",
- dragOverItemId === item.id &&
- draggingItemId !== item.id &&
- "rounded-md ring-1 ring-ring/60",
- )}
- draggable={reorderable && !isEditing}
- onDragStart={(event) => {
- setDraggingItemId(item.id);
- event.dataTransfer.effectAllowed = "move";
- event.dataTransfer.setData(PROMPT_QUEUE_DRAG_TYPE, item.id);
- }}
- onDragEnd={endDrag}
- onDragOver={(event) => {
- // Own type only: a file dragged over a row must reach the page
- // dropzone, which skips events already prevented here.
- if (!isPromptQueueDrag(event) || draggingItemId === item.id) {
- return;
- }
- event.preventDefault();
- event.dataTransfer.dropEffect = "move";
- setDragOverItemId(item.id);
- }}
- onDragLeave={() => {
- setDragOverItemId((id) => (id === item.id ? null : id));
- }}
- onDrop={(event) => {
- if (!isPromptQueueDrag(event)) {
- return;
- }
- event.preventDefault();
- const sourceId =
- event.dataTransfer.getData(PROMPT_QUEUE_DRAG_TYPE) ||
- draggingItemId;
- if (sourceId) {
- movePromptQueueItem(sourceId, item.id);
- }
- endDrag();
- }}
- aria-label={`${promptQueueStatusLabel(item.status)} prompt ${visiblePosition} of ${visibleItems.length}: ${item.prompt}`}
- >
- {isEditing ? (
- <div className="grid min-h-10 grid-cols-[minmax(0,1fr)_auto_auto] items-center gap-2.5 py-1">
- <textarea
- ref={editInputRef}
- value={draftPrompt}
- rows={1}
- onChange={(event) =>
- setDraftPrompt(event.currentTarget.value)
- }
- onKeyDown={(event) => {
- if (
- event.key === "Enter" &&
- (event.metaKey || event.ctrlKey)
- ) {
- event.preventDefault();
- saveEditing();
- } else if (event.key === "Escape") {
- event.preventDefault();
- cancelEditing();
- }
- }}
- className="max-h-20 min-h-8 min-w-0 resize-none rounded-md border border-border/45 bg-transparent px-2 py-1.5 text-sm leading-5 text-foreground outline-none transition-colors focus-visible:border-ring"
- aria-label={`Edit queued prompt ${visiblePosition}`}
- />
- <Button
- type="button"
- variant="ghost"
- size="sm"
- className="h-7 px-2 text-xs text-muted-foreground"
- onClick={cancelEditing}
- >
- Cancel
- </Button>
- <Button
- type="button"
- size="sm"
- className="h-7 px-2 text-xs"
- disabled={draftPrompt.trim().length === 0}
- onClick={saveEditing}
- >
- Save
- </Button>
- </div>
- ) : (
- <div className="grid h-10 grid-cols-[minmax(0,1fr)_auto_2rem] items-center gap-2.5">
- <div className="flex min-w-0 items-center gap-2.5">
- {reorderable ? (
- <button
- type="button"
- className="shrink-0 cursor-grab text-muted-foreground/50 outline-none hover:text-muted-foreground focus-visible:text-foreground active:cursor-grabbing"
- aria-label={`Reorder queued prompt ${visiblePosition} of ${visibleItems.length}`}
- onKeyDown={(event) => {
- if (event.key !== "ArrowUp" && event.key !== "ArrowDown") {
- return;
- }
- event.preventDefault();
- moveByOffset(
- visibleIndex,
- event.key === "ArrowUp" ? -1 : 1,
- );
- }}
- >
- <CornerDownRightIcon className="size-4" />
- </button>
- ) : (
- <CornerDownRightIcon className="size-4 shrink-0 text-muted-foreground/50" />
- )}
- <div className="truncate text-sm text-muted-foreground">
- {item.prompt}
- </div>
- </div>
- {item.canEdit ? (
- <Button
- type="button"
- variant="ghost"
- size="sm"
- className="h-7 w-[5.25rem] justify-center gap-1 px-0 text-sm font-normal text-muted-foreground/80 hover:text-foreground"
- onClick={() => startEditing(item)}
- >
- <HugeiconsIcon icon={Edit03Icon} strokeWidth={2} />
- Edit
- </Button>
- ) : null}
- <TooltipIconButton
- tooltip="Remove from queue"
- side="bottom"
- type="button"
- variant="ghost"
- size="icon"
- className="col-start-3 size-7 justify-self-center text-muted-foreground/70 hover:text-destructive"
- aria-label={`Remove queued prompt ${visiblePosition}`}
- disabled={!item.canRemove}
- onClick={() => removePromptQueueItem(item.id)}
- >
- <HugeiconsIcon icon={Delete02Icon} strokeWidth={2} />
- </TooltipIconButton>
- </div>
- )}
- </div>
- );
- })}
- </div>
- </div>
+ <PromptQueueList
+ key={queueEntry.runId}
+ entry={queueEntry}
+ items={visibleItems}
+ onEdit={editPromptQueueItem}
+ onRemove={removePromptQueueItem}
+ onMove={movePromptQueueItem}
+ onSteer={steerPromptQueueItem}
+ onResume={() => resumePromptQueueRun(queueThreadIds)}
+ />
);
};
@@ -6824,6 +6696,11 @@ const ComposerRightControls: FC<{
menuSide,
queueThreadIds,
}) => {
+ const followUpBehavior = useChatPreferencesStore((s) => s.followUpBehavior);
+ const sendShortcut = useChatPreferencesStore((s) => s.sendShortcut);
+ const shortcutLabels = composerShortcutLabels(sendShortcut, isMacPlatform());
+ const followUpLabel = followUpBehavior === "queue" ? "Queue message" : "Steer response";
+ const followUpTooltip = `${followUpLabel} (${shortcutLabels.send}) · ${shortcutLabels.opposite} for the opposite`;
const queueEntry = usePromptQueueUI((s) =>
findPromptQueueEntry(s, queueThreadIds),
);
@@ -6911,7 +6788,9 @@ const ComposerRightControls: FC<{
>
<ComposerPrimitive.Send asChild={true}>
<TooltipIconButton
- tooltip={pendingSend ? "Waiting for documents…" : "Send message"}
+ tooltip={
+ pendingSend ? "Waiting for documents…" : `Send message (${shortcutLabels.send})`
+ }
side="bottom"
type="submit"
variant="default"
@@ -6959,7 +6838,7 @@ const ComposerRightControls: FC<{
</Button>
) : (
<TooltipIconButton
- tooltip="Queue message"
+ tooltip={followUpTooltip}
side="bottom"
type="button"
variant="default"
@@ -6967,9 +6846,13 @@ const ComposerRightControls: FC<{
disabled={disabled || queueDisabled}
onClick={onQueueClick}
className="aui-composer-send ml-1.5 size-9 rounded-full"
- aria-label="Queue message"
+ aria-label={followUpLabel}
>
- <ArrowUpIcon className="unsloth-send-icon aui-composer-send-icon size-[21px] stroke-2" />
+ {followUpBehavior === "steer" ? (
+ <CornerUpRightIcon className="size-[21px] stroke-2" />
+ ) : (
+ <ArrowUpIcon className="unsloth-send-icon aui-composer-send-icon size-[21px] stroke-2" />
+ )}
</TooltipIconButton>
)}
</AuiIf>
@@ -7010,7 +6893,7 @@ const ComposerRightControls: FC<{
</ComposerPrimitive.Cancel>
) : (
<TooltipIconButton
- tooltip="Queue message"
+ tooltip={followUpTooltip}
side="bottom"
type="button"
variant="default"
@@ -7018,9 +6901,13 @@ const ComposerRightControls: FC<{
disabled={queueDisabled}
onClick={onQueueClick}
className="aui-composer-send size-9 rounded-full"
- aria-label="Queue message"
+ aria-label={followUpLabel}
>
- <ArrowUpIcon className="unsloth-send-icon aui-composer-send-icon size-[21px] stroke-2" />
+ {followUpBehavior === "steer" ? (
+ <CornerUpRightIcon className="size-[21px] stroke-2" />
+ ) : (
+ <ArrowUpIcon className="unsloth-send-icon aui-composer-send-icon size-[21px] stroke-2" />
+ )}
</TooltipIconButton>
)}
</div>
@@ -8507,6 +8394,7 @@ const UserActionBar: FC = () => {
const EditComposer: FC = () => {
const aui = useAui();
+ const sendShortcut = useChatPreferencesStore((s) => s.sendShortcut);
const { inputProps, isComposingRef } = useImeComposerInputHandlers();
const resendAfterCancelRef = useRef(false);
const researchActive = useThreadResearchActive();
@@ -8523,6 +8411,7 @@ const EditComposer: FC = () => {
<MessagePrimitive.Root className="aui-edit-composer-wrapper mx-auto flex w-full max-w-(--thread-content-max-width) flex-col py-3">
<ComposerPrimitive.Root className="aui-edit-composer-root ml-auto flex w-full max-w-[85%] flex-col rounded-2xl bg-muted">
<ComposerPrimitive.Input
+ submitMode={sendShortcut === "mod-enter" ? "ctrlEnter" : "enter"}
className="aui-edit-composer-input min-h-14 w-full resize-none bg-transparent p-4 text-foreground text-sm font-[450] outline-none"
autoFocus={true}
// See main composer above for the dir="auto" rationale.
diff --git a/studio/frontend/src/components/assistant-ui/use-prompt-queue-reorder.ts b/studio/frontend/src/components/assistant-ui/use-prompt-queue-reorder.ts
new file mode 100644
index 00000000000..ff0d5f1e095
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/use-prompt-queue-reorder.ts
@@ -0,0 +1,319 @@
+// 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 {
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useState,
+ type PointerEvent,
+} from "react";
+import { useReducedMotionConfig } from "motion/react";
+import type { PromptQueueUIItem } from "@/features/chat";
+
+const SETTLE_MS = 180;
+const EASING = "cubic-bezier(0.2, 0.8, 0.2, 1)";
+const ROW_SELECTOR = "[data-queue-item-id]";
+
+type Row = {
+ id: string;
+ element: HTMLElement;
+ top: number;
+ height: number;
+ movable: boolean;
+};
+type Drag = {
+ id: string;
+ pointerId: number;
+ handle: HTMLButtonElement;
+ originY: number;
+ scrollTop: number;
+ scale: number;
+ x: number;
+ y: number;
+ from: number;
+ target: string | null;
+ rows: Row[];
+ signature: string;
+ moved: boolean;
+ frame: number;
+ lastTime: number;
+};
+
+function getQueueScale(list: HTMLElement | null) {
+ return list ? list.getBoundingClientRect().width / list.offsetWidth || 1 : 1;
+}
+
+export function usePromptQueueReorder(
+ items: PromptQueueUIItem[],
+ disabled: boolean,
+ onMove: (id: string, targetId: string) => boolean,
+ announce: (message: string) => void,
+) {
+ const listRef = useRef<HTMLDivElement>(null);
+ const dragRef = useRef<Drag | null>(null);
+ const animations = useRef<Animation[]>([]);
+ const pendingPositions = useRef<Map<string, number> | null>(null);
+ const [draggingId, setDraggingId] = useState<string | null>(null);
+ const reducedMotion = useReducedMotionConfig();
+ const signature = JSON.stringify([
+ disabled,
+ items.map((item) => [item.id, item.canEdit, item.canRemove]),
+ ]);
+
+ const stopAnimations = useCallback(() => {
+ for (const animation of animations.current) animation.cancel();
+ animations.current = [];
+ }, []);
+
+ const capturePositions = useCallback(() => {
+ const list = listRef.current;
+ const scale = getQueueScale(list);
+ return new Map(
+ Array.from(list?.querySelectorAll<HTMLElement>(ROW_SELECTOR) ?? []).map(
+ (row) => [
+ row.dataset.queueItemId!,
+ row.getBoundingClientRect().top / scale + (list?.scrollTop ?? 0),
+ ],
+ ),
+ );
+ }, []);
+
+ const clearDrag = useCallback((drag: Drag) => {
+ cancelAnimationFrame(drag.frame);
+ dragRef.current = null;
+ for (const row of drag.rows) {
+ row.element.style.removeProperty("transform");
+ row.element.style.removeProperty("transition");
+ }
+ if (drag.handle.hasPointerCapture(drag.pointerId)) {
+ drag.handle.releasePointerCapture(drag.pointerId);
+ }
+ }, []);
+
+ const cancelDrag = useCallback(() => {
+ const drag = dragRef.current;
+ if (!drag) return false;
+ if (drag.moved) pendingPositions.current = capturePositions();
+ clearDrag(drag);
+ setDraggingId(null);
+ return true;
+ }, [capturePositions, clearDrag]);
+
+ function move(id: string, targetId: string | undefined) {
+ if (!targetId || id === targetId) return;
+ pendingPositions.current ??= capturePositions();
+ if (onMove(id, targetId)) {
+ const position = items.findIndex((item) => item.id === targetId) + 1;
+ announce(`Prompt moved to position ${position} of ${items.length}.`);
+ } else {
+ if (!draggingId) pendingPositions.current = null;
+ announce(
+ "The queue changed before this prompt could be moved. Try again.",
+ );
+ }
+ }
+
+ useLayoutEffect(() => {
+ const drag = dragRef.current;
+ if (drag && (drag.signature !== signature || disabled)) {
+ clearDrag(drag);
+ setDraggingId(null);
+ announce(
+ "The queue changed. Drag again to reorder the remaining prompts.",
+ );
+ }
+ const previous = pendingPositions.current;
+ pendingPositions.current = null;
+ if (!previous) return;
+ stopAnimations();
+ if (reducedMotion) return;
+ const list = listRef.current;
+ const scale = getQueueScale(list);
+ for (const row of list?.querySelectorAll<HTMLElement>(ROW_SELECTOR) ?? []) {
+ const before = previous.get(row.dataset.queueItemId!);
+ if (before === undefined) continue;
+ const offset =
+ before - row.getBoundingClientRect().top / scale - (list?.scrollTop ?? 0);
+ if (Math.abs(offset) < 0.5) continue;
+ animations.current.push(
+ row.animate(
+ [
+ { transform: `translateY(${offset}px)` },
+ { transform: "translateY(0)" },
+ ],
+ { duration: SETTLE_MS, easing: EASING },
+ ),
+ );
+ }
+ }, [
+ signature,
+ disabled,
+ reducedMotion,
+ announce,
+ draggingId,
+ clearDrag,
+ stopAnimations,
+ ]);
+
+ useEffect(() => {
+ const cancel = () => cancelDrag();
+ window.addEventListener("blur", cancel);
+ window.addEventListener("resize", cancel);
+ return () => {
+ window.removeEventListener("blur", cancel);
+ window.removeEventListener("resize", cancel);
+ const drag = dragRef.current;
+ if (drag) clearDrag(drag);
+ stopAnimations();
+ };
+ }, [cancelDrag, clearDrag, stopAnimations]);
+
+ function updateDrag(time: number) {
+ const drag = dragRef.current;
+ const list = listRef.current;
+ if (!drag || !drag.moved || !list) return;
+ const bounds = list.getBoundingClientRect();
+ const insideX = drag.x >= bounds.left && drag.x <= bounds.right;
+ const elapsed = Math.min(time - drag.lastTime, 32);
+ drag.lastTime = time;
+ // Keep scrolling when the pointer rests at an edge.
+ if (insideX) {
+ const edge = Math.min(36, bounds.height / 4);
+ const speed =
+ drag.y < bounds.top + edge
+ ? -Math.min(1, (bounds.top + edge - drag.y) / edge)
+ : drag.y > bounds.bottom - edge
+ ? Math.min(1, (drag.y - bounds.bottom + edge) / edge)
+ : 0;
+ list.scrollTop += (speed * elapsed * 0.45) / drag.scale;
+ }
+ const source = drag.rows[drag.from];
+ // Pointer coordinates include interface scaling; transforms do not.
+ const delta =
+ (drag.y - drag.originY) / drag.scale + list.scrollTop - drag.scrollTop;
+ const first = drag.rows[0];
+ const last = drag.rows[drag.rows.length - 1];
+ const offset = Math.max(
+ first.top - source.top,
+ Math.min(delta, last.top + last.height - source.top - source.height),
+ );
+ const center = source.top + source.height / 2 + offset;
+ const inside = insideX && drag.y >= bounds.top && drag.y <= bounds.bottom;
+ let to = drag.from;
+ let distance = Infinity;
+ if (inside) {
+ drag.rows.forEach((row, index) => {
+ const nextDistance = Math.abs(center - row.top - row.height / 2);
+ if (row.movable && nextDistance < distance) {
+ to = index;
+ distance = nextDistance;
+ }
+ });
+ }
+ drag.target = inside ? drag.rows[to].id : null;
+ drag.rows.forEach((row, index) => {
+ let shift = 0;
+ if (index === drag.from) shift = offset;
+ else if (index > drag.from && index <= to) shift = -source.height;
+ else if (index < drag.from && index >= to) shift = source.height;
+ row.element.style.transform = `translate3d(0, ${shift}px, 0)`;
+ });
+ drag.frame = requestAnimationFrame(updateDrag);
+ }
+
+ function onPointerDown(event: PointerEvent<HTMLButtonElement>, id: string) {
+ if (disabled || event.button !== 0 || !event.isPrimary || dragRef.current)
+ return;
+ const list = listRef.current;
+ if (!list) return;
+ stopAnimations();
+ const bounds = list.getBoundingClientRect();
+ const scale = getQueueScale(list);
+ const rows = Array.from(
+ list.querySelectorAll<HTMLElement>(ROW_SELECTOR),
+ ).map((element) => {
+ const rect = element.getBoundingClientRect();
+ const item = items.find(
+ (item) => item.id === element.dataset.queueItemId,
+ )!;
+ return {
+ id: item.id,
+ element,
+ top: (rect.top - bounds.top) / scale + list.scrollTop,
+ height: rect.height / scale,
+ movable: item.canEdit && item.canRemove,
+ };
+ });
+ const from = rows.findIndex((row) => row.id === id);
+ if (
+ from < 0 ||
+ !rows[from].movable ||
+ rows.filter((row) => row.movable).length < 2
+ )
+ return;
+ event.preventDefault();
+ event.currentTarget.focus({ preventScroll: true });
+ event.currentTarget.setPointerCapture(event.pointerId);
+ dragRef.current = {
+ id,
+ pointerId: event.pointerId,
+ handle: event.currentTarget,
+ originY: event.clientY,
+ scrollTop: list.scrollTop,
+ scale,
+ x: event.clientX,
+ y: event.clientY,
+ from,
+ target: null,
+ rows,
+ signature,
+ moved: false,
+ frame: 0,
+ lastTime: performance.now(),
+ };
+ }
+
+ function onPointerMove(event: PointerEvent<HTMLButtonElement>) {
+ const drag = dragRef.current;
+ if (!drag || drag.pointerId !== event.pointerId) return;
+ drag.x = event.clientX;
+ drag.y = event.clientY;
+ if (drag.moved || Math.abs(drag.y - drag.originY) < 5) return;
+ drag.moved = true;
+ for (const row of drag.rows) {
+ row.element.style.transition =
+ row.id === drag.id || reducedMotion
+ ? "none"
+ : `transform ${SETTLE_MS}ms ${EASING}`;
+ }
+ setDraggingId(drag.id);
+ drag.frame = requestAnimationFrame(updateDrag);
+ }
+
+ function onPointerUp(event: PointerEvent<HTMLButtonElement>) {
+ const drag = dragRef.current;
+ if (!drag || drag.pointerId !== event.pointerId) return;
+ if (drag.moved) {
+ drag.x = event.clientX;
+ drag.y = event.clientY;
+ cancelAnimationFrame(drag.frame);
+ updateDrag(performance.now());
+ pendingPositions.current = capturePositions();
+ }
+ clearDrag(drag);
+ if (drag.moved && drag.target) move(drag.id, drag.target);
+ setDraggingId(null);
+ }
+
+ return {
+ listRef,
+ draggingId,
+ move,
+ cancelDrag,
+ onPointerDown,
+ onPointerMove,
+ onPointerUp,
+ };
+}
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index a38543dbf35..a24455e42c7 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -3829,11 +3829,12 @@ async function resolveQueuedEmptyLocalModel(abortSignal: AbortSignal): Promise<{
loadFailureReported?: boolean;
modelRuntime: QueuedResolvedModelRuntime | null;
}> {
- let lifecycleLease = useChatRuntimeStore.getState().beginModelLoading();
+ // Auto-load does not sweep queues, so follow-ups can be accepted immediately.
+ let lifecycleLease = useChatRuntimeStore.getState().beginModelLoading("loading");
while (lifecycleLease === null) {
await waitForModelReady(abortSignal);
abortSignal.throwIfAborted();
- lifecycleLease = useChatRuntimeStore.getState().beginModelLoading();
+ lifecycleLease = useChatRuntimeStore.getState().beginModelLoading("loading");
}
try {
diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsx
index ded99595905..863bb5b13b1 100644
--- a/studio/frontend/src/features/chat/chat-page.tsx
+++ b/studio/frontend/src/features/chat/chat-page.tsx
@@ -2183,6 +2183,9 @@ export function ChatPage({
search,
active,
}: { search: ChatSearch; active: boolean }): ReactElement {
+ const showContextWindowUsage = useChatPreferencesStore(
+ (s) => s.showContextWindowUsage,
+ );
const navigate = useNavigate();
const settingsOpen = useChatRuntimeStore((s) => s.settingsPanelOpen);
@@ -4113,7 +4116,9 @@ export function ChatPage({
) : null}
</div>
<div className="pointer-events-auto ml-auto flex items-center gap-1">
- {view.mode === "single" && (contextUsage || contextWindowKnown) ? (
+ {showContextWindowUsage &&
+ view.mode === "single" &&
+ (contextUsage || contextWindowKnown) ? (
<ContextUsageBar
used={contextUsage?.totalTokens ?? null}
// null on external providers; the bar handles that.
diff --git a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
index ed5ecd56694..f6a059d6e71 100644
--- a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
+++ b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
@@ -61,9 +61,15 @@ import {
} from "../api/chat-api";
import { formatEta, formatRate } from "../utils/format-transfer";
import { confirmStopRunningChatsIfNeeded } from "../utils/confirm-stop-running-chats";
-import { requestLocalPromptQueueStop } from "../utils/prompt-queue-boundary";
+import {
+ requestLocalPromptQueueStop,
+ notifyLocalPromptQueueLoadFailed,
+} from "../utils/prompt-queue-boundary";
import { cancelPreStreamRunReservations } from "../utils/pre-stream-run-reservation";
-import type { ModelLifecycleLease } from "../utils/model-lifecycle-gate";
+import {
+ chatModelLifecycleGate,
+ type ModelLifecycleLease,
+} from "../utils/model-lifecycle-gate";
import {
GPU_LAYERS_AUTO,
isLocalModelPath,
@@ -792,6 +798,7 @@ export function useChatModelRuntime() {
const cancelLoading = useCallback(() => {
const model = loadingModelRef.current;
if (!model) return;
+ notifyLocalPromptQueueLoadFailed(loadLifecycleLeaseRef.current);
loadAbortRef.current?.abort();
loadAbortRef.current = null;
loadingModelRef.current = null;
@@ -1095,11 +1102,10 @@ export function useChatModelRuntime() {
}
}
- // Block queue materialization before taking the cancellation snapshot: a queue that appears while
- // the dialog is open must not be stopped without having been included in the confirmation.
+ // Hold the lifecycle lease through confirmation and loading.
const lifecycleLease = useChatRuntimeStore
.getState()
- .beginModelLoading();
+ .beginModelLoading("preparing");
if (lifecycleLease === null) {
restorePreviousConfig();
toast.info("A model is loading", {
@@ -1741,9 +1747,11 @@ export function useChatModelRuntime() {
);
const effectiveChatTemplateOverride =
loadChatTemplateOverride?.trim() ? loadChatTemplateOverride : null;
- // A queue can be created while the preliminary unload is pending, so stop a second time at the
- // final boundary.
+ // Invalidate factories started before the final loading boundary.
requestLocalPromptQueueStop();
+ if (lifecycleLease !== null) {
+ chatModelLifecycleGate.markLoading(lifecycleLease);
+ }
const loadResponse = await loadModel({
model_path: loadPath,
nativePathLease: loadNativePathLease,
@@ -2053,7 +2061,8 @@ export function useChatModelRuntime() {
});
}
} catch (error) {
- // Skip rollback if the user cancelled: the model is already being unloaded.
+ notifyLocalPromptQueueLoadFailed(lifecycleLease);
+ // Cancellation already handles unloading.
if (abortCtrl.signal.aborted) throw error;
if (previousWasUnloaded && previousCheckpoint) {
let rollbackNativePathLease: string | undefined;
@@ -2549,9 +2558,10 @@ export function useChatModelRuntime() {
}
let lifecycleLease: ModelLifecycleLease | null = null;
try {
- // Block queue materialization before taking the confirmation snapshot, or a queue can appear
- // while the dialog is open and be stopped without the user confirming it.
- lifecycleLease = useChatRuntimeStore.getState().beginModelLoading();
+ // Hold the lifecycle lease through confirmation and unloading.
+ lifecycleLease = useChatRuntimeStore
+ .getState()
+ .beginModelLoading("unloading");
if (lifecycleLease === null) {
return false;
}
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index 726606f9908..f2b102a09c6 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -135,6 +135,7 @@ export {
export {
adoptPreStreamRunReservation,
cancelPreStreamRunReservations,
+ cancelPreStreamRunForThreadIds,
findPreStreamRunReservation,
hasPreStreamRunReservation,
preStreamRunThreadIdsForAdapter,
@@ -388,3 +389,12 @@ export {
useSkillsCatalog,
type SkillRecord,
} from "./api/skills-api";
+export {
+ composerSubmitIntent,
+ composerFollowUpBehavior,
+ composerShortcutLabels,
+ steeringInsertionIndex,
+ type ComposerSendShortcut,
+ type ComposerFollowUpBehavior,
+ type ComposerSubmitIntent,
+} from "./utils/composer-preferences";
diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsx
index 69bcd25cb59..ca5ec2ee7c2 100644
--- a/studio/frontend/src/features/chat/shared-composer.tsx
+++ b/studio/frontend/src/features/chat/shared-composer.tsx
@@ -13,6 +13,13 @@ import {
thinkEffortAriaLabel,
thinkToggleAriaLabel,
} from "@/components/assistant-ui/think-aria-label";
+import { ComposerDraftPreview } from "@/components/assistant-ui/composer-draft-preview";
+import { useChatPreferencesStore } from "./stores/chat-preferences-store";
+import {
+ composerSubmitIntent,
+ composerShortcutLabels,
+} from "./utils/composer-preferences";
+import { useT } from "@/i18n";
import { Button } from "@/components/ui/button";
import { BulbIcon } from "@/lib/bulb-icon";
import { MicIcon } from "@/lib/mic-icon";
@@ -43,6 +50,8 @@ import {
COMPOSER_INPUT_SELECTOR,
isSurfaceInForeground,
useShortcut,
+ useSettingsDialogStore,
+ isMacPlatform,
} from "@/features/settings";
import { useVoiceSettingsStore } from "@/features/settings/stores/voice-settings-store";
import {
@@ -78,6 +87,7 @@ import {
MoreHorizontalIcon,
PlusIcon,
SquareIcon,
+ SlidersHorizontalIcon,
XIcon,
} from "lucide-react";
import {
@@ -558,6 +568,9 @@ export function SharedComposer({
sendUnavailableReason?: string;
requireStableCheckpoint?: boolean;
}): ReactElement {
+ const t = useT();
+ const sendShortcut = useChatPreferencesStore((s) => s.sendShortcut);
+ const shortcutLabels = composerShortcutLabels(sendShortcut, isMacPlatform());
const navigate = useNavigate();
// Exit compare: parent's restore handler, or fresh chat if opened by URL.
const handleExitCompare = useCallback(() => {
@@ -1159,7 +1172,7 @@ export function SharedComposer({
if (isGeneralizedCompare) {
compareLifecycleLease = useChatRuntimeStore
.getState()
- .beginModelLoading();
+ .beginModelLoading("preparing");
if (compareLifecycleLease === null) {
toast.info("A model is loading", {
description: "Wait for it to finish or cancel it first.",
@@ -1181,7 +1194,7 @@ export function SharedComposer({
}
compareLifecycleLease = useChatRuntimeStore
.getState()
- .beginModelLoading();
+ .beginModelLoading("preparing");
if (compareLifecycleLease === null) {
throw new Error("Another model load started during comparison");
}
@@ -1912,7 +1925,7 @@ export function SharedComposer({
}
setCompositionState(false);
}
- if (e.key === "Enter" && !e.shiftKey) {
+ if (composerSubmitIntent(e, sendShortcut)) {
e.preventDefault();
if (!busy && !isDictating) {
send();
@@ -2240,6 +2253,7 @@ export function SharedComposer({
</div>
)}
{skillMentions.popover}
+ <ComposerDraftPreview text={text} />
<textarea
{...skillMentions.inputProps}
@@ -2451,6 +2465,15 @@ export function SharedComposer({
</DropdownMenuSubContent>
</DropdownMenuSub>
) : null}
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onSelect={() => useSettingsDialogStore.getState().openDialog("chat", {
+ scrollTarget: "chat-composer",
+ })}
+ >
+ <SlidersHorizontalIcon className="size-4" />
+ {t("composerSettings.settings")}
+ </DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
{/* Active in compare mode; sits first. Click to exit back to single chat. */}
@@ -2842,7 +2865,7 @@ export function SharedComposer({
</Button>
) : (
<TooltipIconButton
- tooltip={sendUnavailableReason ?? "Send message"}
+ tooltip={sendUnavailableReason ?? `Send message (${shortcutLabels.send})`}
side="bottom"
variant="default"
size="icon"
diff --git a/studio/frontend/src/features/chat/stores/chat-preferences-store.ts b/studio/frontend/src/features/chat/stores/chat-preferences-store.ts
index 12078ba23f5..5faea98714c 100644
--- a/studio/frontend/src/features/chat/stores/chat-preferences-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-preferences-store.ts
@@ -3,6 +3,11 @@
import { create } from "zustand";
import { persist } from "zustand/middleware";
+import {
+ type ComposerSendShortcut,
+ type ComposerFollowUpBehavior,
+ normalizeComposerPreferences,
+} from "../utils/composer-preferences.ts";
import {
PASTED_TEXT_DEFAULT_MIN_CHARS,
PASTED_TEXT_THRESHOLD_CHOICES,
@@ -14,6 +19,14 @@ import {
// the producing model on responses. collapseThinkingByDefault: on keeps thinking collapsed.
// pastedTextMinChars: paste length that becomes a .txt attachment; 0 is off.
export interface ChatPreferencesState {
+ plainTextComposer: boolean;
+ setPlainTextComposer: (value: boolean) => void;
+ showContextWindowUsage: boolean;
+ setShowContextWindowUsage: (value: boolean) => void;
+ sendShortcut: ComposerSendShortcut;
+ setSendShortcut: (value: ComposerSendShortcut) => void;
+ followUpBehavior: ComposerFollowUpBehavior;
+ setFollowUpBehavior: (value: ComposerFollowUpBehavior) => void;
confirmDeleteChats: boolean;
setConfirmDeleteChats: (value: boolean) => void;
alwaysDeleteChatFiles: boolean;
@@ -42,6 +55,12 @@ function normalisePastedTextMinChars(value: unknown): number {
export const useChatPreferencesStore = create<ChatPreferencesState>()(
persist(
(set) => ({
+ ...normalizeComposerPreferences(null),
+ setPlainTextComposer: (plainTextComposer) => set({ plainTextComposer }),
+ setShowContextWindowUsage: (showContextWindowUsage) =>
+ set({ showContextWindowUsage }),
+ setSendShortcut: (sendShortcut) => set({ sendShortcut }),
+ setFollowUpBehavior: (followUpBehavior) => set({ followUpBehavior }),
confirmDeleteChats: true,
setConfirmDeleteChats: (confirmDeleteChats) =>
set({ confirmDeleteChats }),
@@ -70,6 +89,7 @@ export const useChatPreferencesStore = create<ChatPreferencesState>()(
const saved = persisted as Partial<ChatPreferencesState> | undefined;
return {
...current,
+ ...normalizeComposerPreferences(saved),
confirmDeleteChats: saved?.confirmDeleteChats ?? true,
alwaysDeleteChatFiles: saved?.alwaysDeleteChatFiles ?? false,
showModelDisclaimer: saved?.showModelDisclaimer ?? false,
diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
index ed077816ebd..ad097cc7489 100644
--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
@@ -99,6 +99,7 @@ import {
import {
chatModelLifecycleGate,
type ModelLifecycleLease,
+ type ModelLifecyclePhase,
} from "../utils/model-lifecycle-gate";
import { shouldAdvanceQueuedSettingsEpoch } from "../utils/queued-settings-epoch";
import type { MmprojFallbackReason } from "../types/api";
@@ -2436,7 +2437,7 @@ type ChatRuntimeStore = {
* conversation's, and a background run may not write it. */
contextUsageByThreadId: Record<string, ContextUsageSnapshot>;
modelLoading: boolean;
- loadingModelPick: LoadingModelPick | null;
+ loadingModelPick: (LoadingModelPick & { selectionSuperseded: boolean }) | null;
// What the resident model loaded from, when that is not its id: a reload rebuilds its target
// from the checkpoint, so without this it goes back down the ref the pin avoided.
activeLoadId: string | null;
@@ -2445,7 +2446,7 @@ type ChatRuntimeStore = {
// so a reload prompts re-selection instead of reusing a dead token.
activeNativePathExpiresAtMs: number | null;
hydratePersistedSettings: () => Promise<void>;
- beginModelLoading: () => ModelLifecycleLease | null;
+ beginModelLoading: (phase?: ModelLifecyclePhase) => ModelLifecycleLease | null;
endModelLoading: (lease: ModelLifecycleLease) => void;
setLoadingModelPick: (pick: LoadingModelPick | null) => void;
clearLoadingModelPick: (expected: LoadingModelPick) => void;
@@ -4259,8 +4260,8 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
})();
return settingsHydrationPromise;
},
- beginModelLoading: () => {
- const lease = chatModelLifecycleGate.tryAcquire();
+ beginModelLoading: (phase) => {
+ const lease = chatModelLifecycleGate.tryAcquire(phase);
if (lease !== null) {
set({ modelLoading: true });
}
@@ -4271,7 +4272,12 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
set({ modelLoading: false });
}
},
- setLoadingModelPick: (pick) => set({ loadingModelPick: pick }),
+ setLoadingModelPick: (pick) =>
+ set({
+ loadingModelPick: pick
+ ? { ...pick, selectionSuperseded: false }
+ : null,
+ }),
clearLoadingModelPick: (expected) =>
set((state) => {
const current = state.loadingModelPick;
@@ -4642,6 +4648,10 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
: nextParams;
return {
params: restoredParams,
+ loadingModelPick:
+ checkpointChanged && state.loadingModelPick
+ ? { ...state.loadingModelPick, selectionSuperseded: true }
+ : state.loadingModelPick,
...getReplayStatePatch(state, nextParams, outgoing, baseParams),
activeGgufVariant: nextGgufVariant,
...(queuedSettingsChanged
diff --git a/studio/frontend/src/features/chat/utils/composer-preferences.ts b/studio/frontend/src/features/chat/utils/composer-preferences.ts
new file mode 100644
index 00000000000..34b419f5e75
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/composer-preferences.ts
@@ -0,0 +1,94 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+export type ComposerSendShortcut = "enter" | "mod-enter";
+export type ComposerFollowUpBehavior = "queue" | "steer";
+export type ComposerSubmitIntent = "default" | "opposite";
+
+export type ComposerKeyEvent = {
+ key: string;
+ metaKey: boolean;
+ ctrlKey: boolean;
+ shiftKey: boolean;
+ altKey: boolean;
+ repeat?: boolean;
+ isComposing?: boolean;
+ keyCode?: number;
+};
+
+/** Only called for the focused composer, after its IME and mention-picker guards. */
+export function composerSubmitIntent(
+ event: ComposerKeyEvent,
+ shortcut: ComposerSendShortcut,
+): ComposerSubmitIntent | null {
+ if (
+ event.key !== "Enter" ||
+ event.altKey ||
+ event.repeat ||
+ event.isComposing ||
+ event.keyCode === 229 ||
+ (event.metaKey && event.ctrlKey)
+ )
+ return null;
+ const mod = event.metaKey || event.ctrlKey;
+ if (shortcut === "mod-enter") {
+ return mod ? (event.shiftKey ? "opposite" : "default") : null;
+ }
+ if (event.shiftKey) return null;
+ return mod ? "opposite" : "default";
+}
+
+export function composerFollowUpBehavior(
+ preference: ComposerFollowUpBehavior,
+ intent: ComposerSubmitIntent,
+): ComposerFollowUpBehavior {
+ if (intent === "default") return preference;
+ return preference === "queue" ? "steer" : "queue";
+}
+
+export function composerShortcutLabels(
+ shortcut: ComposerSendShortcut,
+ mac: boolean,
+) {
+ const mod = mac ? "⌘" : "Ctrl+";
+ return {
+ send: shortcut === "enter" ? "Enter" : `${mod}Enter`,
+ opposite:
+ shortcut === "enter"
+ ? `${mod}Enter`
+ : mac
+ ? "⇧⌘Enter"
+ : "Ctrl+Shift+Enter",
+ };
+}
+
+export function normalizeComposerPreferences(value: unknown) {
+ const saved = value as Record<string, unknown> | null | undefined;
+ return {
+ plainTextComposer:
+ typeof saved?.plainTextComposer === "boolean"
+ ? saved.plainTextComposer
+ : true,
+ showContextWindowUsage:
+ typeof saved?.showContextWindowUsage === "boolean"
+ ? saved.showContextWindowUsage
+ : true,
+ sendShortcut:
+ saved?.sendShortcut === "mod-enter"
+ ? ("mod-enter" as const)
+ : ("enter" as const),
+ followUpBehavior:
+ saved?.followUpBehavior === "steer"
+ ? ("steer" as const)
+ : ("queue" as const),
+ };
+}
+
+/** Put a steering prompt after a dispatched item, or before the next pending item. */
+export function steeringInsertionIndex(
+ items: readonly { dispatched: boolean }[],
+ runIndex: number,
+) {
+ const index = Math.max(0, runIndex);
+ return Math.min(items.length, index + (items[index]?.dispatched ? 1 : 0));
+}
diff --git a/studio/frontend/src/features/chat/utils/model-lifecycle-gate.ts b/studio/frontend/src/features/chat/utils/model-lifecycle-gate.ts
index 10a616eeb3b..8a14f1a8ba7 100644
--- a/studio/frontend/src/features/chat/utils/model-lifecycle-gate.ts
+++ b/studio/frontend/src/features/chat/utils/model-lifecycle-gate.ts
@@ -1,26 +1,50 @@
export type ModelLifecycleLease = number;
+export type ModelLifecyclePhase = "preparing" | "loading" | "unloading";
/** Exclusive ownership for the singleton local-model lifecycle. The store mirrors this gate into
* `modelLoading` for UI consumers, while the lease prevents one async caller from clearing
* another caller's loading state. */
export class ModelLifecycleGate {
private activeLease: ModelLifecycleLease | null = null;
+ private phase: ModelLifecyclePhase | null = null;
private nextLease = 1;
- tryAcquire(): ModelLifecycleLease | null {
+ tryAcquire(
+ phase: ModelLifecyclePhase = "preparing",
+ ): ModelLifecycleLease | null {
if (this.activeLease !== null) {
return null;
}
const lease = this.nextLease++;
this.activeLease = lease;
+ this.phase = phase;
return lease;
}
+ canQueue(): boolean {
+ return this.activeLease === null || this.phase === "loading";
+ }
+
+ markLoading(lease: ModelLifecycleLease): boolean {
+ if (this.activeLease !== lease || this.phase !== "preparing") {
+ return false;
+ }
+ this.phase = "loading";
+ return true;
+ }
+
+ markFailed(lease: ModelLifecycleLease): boolean {
+ if (this.activeLease !== lease || this.phase !== "loading") return false;
+ this.phase = "preparing";
+ return true;
+ }
+
release(lease: ModelLifecycleLease): boolean {
if (this.activeLease !== lease) {
return false;
}
this.activeLease = null;
+ this.phase = null;
return true;
}
}
diff --git a/studio/frontend/src/features/chat/utils/pre-stream-run-reservation.ts b/studio/frontend/src/features/chat/utils/pre-stream-run-reservation.ts
index 045a4aa2877..b37348272c5 100644
--- a/studio/frontend/src/features/chat/utils/pre-stream-run-reservation.ts
+++ b/studio/frontend/src/features/chat/utils/pre-stream-run-reservation.ts
@@ -101,39 +101,51 @@ export function listLocalPreStreamRunReservations(): LocalPreStreamRunReservatio
}));
}
+function cancelPreStreamReservation(token: symbol): boolean {
+ const reservation = reservations.get(token);
+ if (!reservation || reservation.cancelled) return false;
+ reservation.cancelled = true;
+ try {
+ reservation.cancel?.(
+ [...reservation.threadIds].filter((id) => id !== DEFAULT_THREAD_ID),
+ );
+ } catch {
+ // A response may have ended between the user's gesture and cancellation.
+ }
+ reservation.cancel = undefined;
+ for (const id of reservation.threadIds) {
+ if (reservationByThreadId.get(id) === token)
+ reservationByThreadId.delete(id);
+ }
+ if (!reservation.claimed) reservations.delete(token);
+ return true;
+}
+
export function cancelPreStreamRunReservations(
tokens: Iterable<symbol>,
): number {
let cancelled = 0;
for (const token of new Set(tokens)) {
- const reservation = reservations.get(token);
- if (!reservation || !reservation.usesLocalModel || reservation.cancelled) {
- continue;
- }
- reservation.cancelled = true;
- cancelled += 1;
- try {
- reservation.cancel?.(
- [...reservation.threadIds].filter(
- (threadId) => threadId !== DEFAULT_THREAD_ID,
- ),
- );
- } catch {
- // The run may have ended between the confirmation snapshot and cancellation.
- }
- reservation.cancel = undefined;
- for (const threadId of reservation.threadIds) {
- if (reservationByThreadId.get(threadId) === token) {
- reservationByThreadId.delete(threadId);
- }
- }
- if (!reservation.claimed) {
- reservations.delete(token);
- }
+ // Model unload and app-wide stop actions remain local-model-only.
+ if (
+ reservations.get(token)?.usesLocalModel &&
+ cancelPreStreamReservation(token)
+ )
+ cancelled += 1;
}
return cancelled;
}
+/** A composer steering gesture may cancel its own local or external response. */
+export function cancelPreStreamRunForThreadIds(
+ threadIds: readonly string[],
+): boolean {
+ // An unresolved composer must never target the shared default reservation.
+ if (threadIds.length === 0) return false;
+ const token = findPreStreamRunReservation(threadIds);
+ return token ? cancelPreStreamReservation(token) : false;
+}
+
export function claimPreStreamRunReservation(token: symbol): boolean {
const reservation = reservations.get(token);
if (!reservation || reservation.cancelled) {
diff --git a/studio/frontend/src/features/chat/utils/prompt-queue-boundary.ts b/studio/frontend/src/features/chat/utils/prompt-queue-boundary.ts
index 118260403da..79a557ede38 100644
--- a/studio/frontend/src/features/chat/utils/prompt-queue-boundary.ts
+++ b/studio/frontend/src/features/chat/utils/prompt-queue-boundary.ts
@@ -4,6 +4,10 @@ import {
PROMPT_QUEUE_STOP_EVENT,
} from "./prompt-queue-events";
import { localPromptQueueModelBoundary } from "./prompt-queue-model-boundary";
+import {
+ chatModelLifecycleGate,
+ type ModelLifecycleLease,
+} from "./model-lifecycle-gate";
// Re-exported so existing importers and the barrel keep their paths. Module scope readers should
// use ./prompt-queue-events directly: this module has dependencies, so the cycle can catch it
@@ -88,3 +92,19 @@ export function notifyPromptQueueRunFailed(threadId?: string | null) {
),
);
}
+
+export function notifyLocalPromptQueueLoadFailed(
+ lease: ModelLifecycleLease | null,
+) {
+ if (lease === null || !chatModelLifecycleGate.markFailed(lease)) return;
+ localPromptQueueModelBoundary.advance();
+ if (typeof window === "undefined") return;
+ window.dispatchEvent(
+ new CustomEvent<PromptQueueRunFailedEventDetail>(
+ PROMPT_QUEUE_RUN_FAILED_EVENT,
+ {
+ detail: { localOnly: true },
+ },
+ ),
+ );
+}
diff --git a/studio/frontend/src/features/chat/utils/prompt-queue-events.ts b/studio/frontend/src/features/chat/utils/prompt-queue-events.ts
index eff37996c29..469060e80fd 100644
--- a/studio/frontend/src/features/chat/utils/prompt-queue-events.ts
+++ b/studio/frontend/src/features/chat/utils/prompt-queue-events.ts
@@ -18,4 +18,5 @@ export type PromptQueueStopEventDetail = {
export type PromptQueueRunFailedEventDetail = {
threadId?: string | null;
+ localOnly?: boolean;
};
diff --git a/studio/frontend/src/features/chat/utils/prompt-queue-model-boundary.ts b/studio/frontend/src/features/chat/utils/prompt-queue-model-boundary.ts
index 37c2374b9e9..663e60e2579 100644
--- a/studio/frontend/src/features/chat/utils/prompt-queue-model-boundary.ts
+++ b/studio/frontend/src/features/chat/utils/prompt-queue-model-boundary.ts
@@ -1,3 +1,5 @@
+import { chatModelLifecycleGate } from "./model-lifecycle-gate.ts";
+
export class PromptQueueModelBoundary {
private generation = 0;
@@ -54,15 +56,14 @@ export function planLocalPromptQueueStop(
export function shouldAbortPendingQueueForModelBoundary({
capturedGeneration,
usesLocalModel,
- modelLoading,
}: {
capturedGeneration: number;
usesLocalModel: boolean;
- modelLoading: boolean;
}): boolean {
+ // Preparation can still clear queues at the final model-switch boundary.
return (
usesLocalModel &&
- (modelLoading ||
+ (!chatModelLifecycleGate.canQueue() ||
capturedGeneration !== localPromptQueueModelBoundary.capture())
);
}
diff --git a/studio/frontend/src/features/chat/utils/queued-chat-run-settings.ts b/studio/frontend/src/features/chat/utils/queued-chat-run-settings.ts
index e1a6df06f2d..cf96fcb9222 100644
--- a/studio/frontend/src/features/chat/utils/queued-chat-run-settings.ts
+++ b/studio/frontend/src/features/chat/utils/queued-chat-run-settings.ts
@@ -68,6 +68,7 @@ const pendingSettings: PendingSettings[] = [];
export function snapshotQueuedChatRunSettings(
state: ChatRuntimeState,
+ options?: { deferModelResolution?: boolean },
): QueuedChatRunSettings {
const snapshot = {
params: { ...state.params },
@@ -75,6 +76,10 @@ export function snapshotQueuedChatRunSettings(
for (const key of QUEUED_SETTING_KEYS) {
Object.assign(snapshot, { [key]: state[key] });
}
+ if (options?.deferModelResolution) {
+ snapshot.params.checkpoint = "";
+ snapshot.activeGgufVariant = null;
+ }
return snapshot;
}
diff --git a/studio/frontend/src/features/settings/components/composer-settings.tsx b/studio/frontend/src/features/settings/components/composer-settings.tsx
new file mode 100644
index 00000000000..c0a86f34315
--- /dev/null
+++ b/studio/frontend/src/features/settings/components/composer-settings.tsx
@@ -0,0 +1,118 @@
+// 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 { useEffect, useRef } from "react";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import {
+ useChatPreferencesStore,
+ composerShortcutLabels,
+} from "@/features/chat";
+import { useT } from "@/i18n";
+import { isMacPlatform } from "../lib/keyboard-shortcuts";
+import { useSettingsDialogStore } from "../stores/settings-dialog-store";
+import { SettingsRow } from "./settings-row";
+import { SettingsSection } from "./settings-section";
+
+export function ComposerSettings() {
+ const t = useT();
+ const prefs = useChatPreferencesStore();
+ const ref = useRef<HTMLDivElement>(null);
+ const scrollTarget = useSettingsDialogStore((s) => s.scrollTarget);
+ const labels = composerShortcutLabels(prefs.sendShortcut, isMacPlatform());
+ useEffect(() => {
+ if (scrollTarget !== "chat-composer") return;
+ const frame = requestAnimationFrame(() => {
+ ref.current?.scrollIntoView({ block: "start", behavior: "smooth" });
+ useSettingsDialogStore.getState().consumeScrollTarget("chat-composer");
+ });
+ return () => cancelAnimationFrame(frame);
+ }, [scrollTarget]);
+
+ return (
+ <div ref={ref}>
+ <SettingsSection title={t("composerSettings.title")}>
+ <div className="mt-2 divide-y divide-border/60 rounded-2xl border border-border/60 bg-muted/20 px-4">
+ <SettingsRow
+ label={t("composerSettings.plainText")}
+ description={t("composerSettings.plainTextDescription")}
+ >
+ <Switch
+ aria-label={t("composerSettings.plainText")}
+ checked={prefs.plainTextComposer}
+ onCheckedChange={prefs.setPlainTextComposer}
+ />
+ </SettingsRow>
+ <SettingsRow label={t("composerSettings.showContext")}>
+ <Switch
+ aria-label={t("composerSettings.showContext")}
+ checked={prefs.showContextWindowUsage}
+ onCheckedChange={prefs.setShowContextWindowUsage}
+ />
+ </SettingsRow>
+ <SettingsRow
+ label={t("composerSettings.sendShortcut")}
+ description={t("composerSettings.sendDescription")}
+ >
+ <Select
+ value={prefs.sendShortcut}
+ onValueChange={(value) =>
+ prefs.setSendShortcut(
+ value === "mod-enter" ? "mod-enter" : "enter",
+ )
+ }
+ >
+ <SelectTrigger
+ className="w-36"
+ aria-label={t("composerSettings.sendShortcut")}
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="enter">Enter</SelectItem>
+ <SelectItem value="mod-enter">
+ {composerShortcutLabels("mod-enter", isMacPlatform()).send}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ </SettingsRow>
+ <SettingsRow
+ label={t("composerSettings.followUp")}
+ description={t("composerSettings.followUpDescription", {
+ shortcut: labels.opposite,
+ })}
+ hint={t("composerSettings.steerDescription")}
+ >
+ <div
+ className="inline-flex gap-1 rounded-full bg-muted p-1"
+ role="group"
+ aria-label={t("composerSettings.followUp")}
+ >
+ {(["queue", "steer"] as const).map((behavior) => (
+ <button
+ key={behavior}
+ type="button"
+ aria-pressed={prefs.followUpBehavior === behavior}
+ onClick={() => prefs.setFollowUpBehavior(behavior)}
+ className="cursor-pointer rounded-full px-3 py-1.5 text-sm text-muted-foreground transition-colors aria-pressed:bg-background aria-pressed:text-foreground aria-pressed:shadow-sm"
+ >
+ {t(
+ behavior === "queue"
+ ? "composerSettings.queue"
+ : "composerSettings.steer",
+ )}
+ </button>
+ ))}
+ </div>
+ </SettingsRow>
+ </div>
+ </SettingsSection>
+ </div>
+ );
+}
diff --git a/studio/frontend/src/features/settings/index.ts b/studio/frontend/src/features/settings/index.ts
index 80015c6f96f..42f5e7a3cd0 100644
--- a/studio/frontend/src/features/settings/index.ts
+++ b/studio/frontend/src/features/settings/index.ts
@@ -90,3 +90,5 @@ export type { ShortcutId } from "./lib/keyboard-shortcuts";
export { useSettingsDialogStore } from "./stores/settings-dialog-store";
export type { SettingsTab } from "./stores/settings-dialog-store";
export type { Palette, ResolvedTheme, Theme } from "./stores/theme-store";
+
+export { isMacPlatform } from "./lib/keyboard-shortcuts";
diff --git a/studio/frontend/src/features/settings/stores/settings-dialog-store.ts b/studio/frontend/src/features/settings/stores/settings-dialog-store.ts
index 250e29aff4e..539eaeec83f 100644
--- a/studio/frontend/src/features/settings/stores/settings-dialog-store.ts
+++ b/studio/frontend/src/features/settings/stores/settings-dialog-store.ts
@@ -30,6 +30,7 @@ export type SettingsTab = (typeof SETTINGS_TABS)[number];
export type SettingsScrollTarget =
| "about-updates"
| "appearance-sidebar-nav"
+ | "chat-composer"
| "chat-canvas-network";
/** Which archive the Data tab should open straight into. */
@@ -107,6 +108,7 @@ function loadInitialTab(): SettingsTab {
/** The panel that delivers each scroll target, so a navigation elsewhere abandons it. */
const SCROLL_TARGET_TAB: Record<SettingsScrollTarget, SettingsTab> = {
+ "chat-composer": "chat",
"about-updates": "about",
"appearance-sidebar-nav": "appearance",
"chat-canvas-network": "chat",
diff --git a/studio/frontend/src/features/settings/tabs/chat-tab.tsx b/studio/frontend/src/features/settings/tabs/chat-tab.tsx
index cb5d79b9ef1..6d2fab2eb8f 100644
--- a/studio/frontend/src/features/settings/tabs/chat-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/chat-tab.tsx
@@ -48,6 +48,7 @@ import {
updateCurrentDatePrompt,
} from "../api/current-date-prompt";
import { SettingsRow } from "../components/settings-row";
+import { ComposerSettings } from "../components/composer-settings";
import { SettingsSection } from "../components/settings-section";
import { useSettingsDialogStore } from "../stores/settings-dialog-store";
@@ -352,6 +353,7 @@ export function ChatTab() {
</p>
</header>
+ <ComposerSettings />
<SettingsSection title={t("settings.chat.modelSelection.title")}>
<SettingsRow
label={t("settings.chat.modelSelection.expandQuantizations")}
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 1d9bfd66353..ddcd712fd6c 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -5,6 +5,21 @@ import type { DeepPartialMessageTree } from "../types";
import type { en } from "./en";
export const ar = {
+ composerSettings: {
+ title: "كتابة الرسائل",
+ plainText: "محرر نص عادي",
+ plainTextDescription: "إبقاء التعليمات البرمجية وMarkdown والروابط كنص حرفي. عطّل هذا الخيار لعرض معاينة منسقة.",
+ showContext: "إظهار استخدام نافذة السياق",
+ sendShortcut: "اختصار الإرسال",
+ sendDescription: "اختر ما إذا كان Enter يرسل الرسالة أو يضيف سطرًا جديدًا.",
+ followUp: "سلوك رسائل المتابعة",
+ followUpDescription: "اختر ما يحدث عند الإرسال أثناء الرد. اضغط {shortcut} لتنفيذ الإجراء المعاكس لرسالة واحدة.",
+ queue: "إضافة للطابور",
+ steer: "توجيه",
+ steerDescription: "التوجيه يوقف الرد الحالي ويرسل رسالة المتابعة بعده مباشرة.",
+ settings: "إعدادات كتابة الرسائل",
+ preview: "معاينة منسقة",
+ },
picker: {
onDevice: "على الجهاز",
huggingFace: "Hugging Face",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index a6396eeb61f..c8bd4d72e8f 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -5,6 +5,21 @@ import type { DeepPartialMessageTree } from "../types";
import type { en } from "./en";
export const de = {
+ composerSettings: {
+ title: "Nachrichteneingabe",
+ plainText: "Eingabe als Klartext",
+ plainTextDescription: "Code, Markdown und Links als wörtlichen Text anzeigen. Ausschalten, um eine formatierte Vorschau zu sehen.",
+ showContext: "Auslastung des Kontextfensters anzeigen",
+ sendShortcut: "Tastenkürzel zum Senden",
+ sendDescription: "Wähle, ob Enter eine Nachricht sendet oder eine neue Zeile einfügt.",
+ followUp: "Folgenachrichten",
+ followUpDescription: "Wähle, was beim Senden während einer Antwort passiert. Drücke {shortcut}, um für eine Nachricht das Gegenteil zu tun.",
+ queue: "Einreihen",
+ steer: "Umlenken",
+ steerDescription: "Umlenken stoppt die aktuelle Antwort und sendet deine Folgenachricht als Nächstes.",
+ settings: "Eingabeeinstellungen",
+ preview: "Formatierte Vorschau",
+ },
picker: {
onDevice: "Auf dem Gerät",
huggingFace: "Hugging Face",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index a156c44b208..161c22292e2 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -2,6 +2,21 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
export const en = {
+ composerSettings: {
+ title: "Composer",
+ plainText: "Plain text composer",
+ plainTextDescription: "Keep code, Markdown, and links as literal text. Turn off to show a formatted preview.",
+ showContext: "Show context window usage",
+ sendShortcut: "Send shortcut",
+ sendDescription: "Choose when Enter sends a prompt or inserts a new line.",
+ followUp: "Follow-up behavior",
+ followUpDescription: "Choose what happens when you send during a response. Press {shortcut} to do the opposite for one message.",
+ queue: "Queue",
+ steer: "Steer",
+ steerDescription: "Steer stops the current response and sends your follow-up next.",
+ settings: "Composer settings",
+ preview: "Formatted preview",
+ },
picker: {
onDevice: "On Device",
huggingFace: "Hugging Face",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index d5d620aaf5e..f5175d6fafb 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -5,6 +5,21 @@ import type { DeepPartialMessageTree } from "../types";
import type { en } from "./en";
export const es = {
+ composerSettings: {
+ title: "Redacción de mensajes",
+ plainText: "Redactor de texto sin formato",
+ plainTextDescription: "Mantener el código, Markdown y los enlaces como texto literal. Desactívalo para mostrar una vista previa con formato.",
+ showContext: "Mostrar uso de la ventana de contexto",
+ sendShortcut: "Atajo para enviar",
+ sendDescription: "Elige si Intro envía un mensaje o inserta una línea nueva.",
+ followUp: "Mensajes de seguimiento",
+ followUpDescription: "Elige qué ocurre al enviar durante una respuesta. Pulsa {shortcut} para hacer lo contrario con un mensaje.",
+ queue: "En cola",
+ steer: "Redirigir",
+ steerDescription: "Redirigir detiene la respuesta actual y envía tu mensaje de seguimiento a continuación.",
+ settings: "Ajustes del redactor",
+ preview: "Vista previa con formato",
+ },
picker: {
onDevice: "En el dispositivo",
huggingFace: "Hugging Face",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 3a29b0ab554..7cf6e0b6a88 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -5,6 +5,21 @@ import type { DeepPartialMessageTree } from "../types";
import type { en } from "./en";
export const fr = {
+ composerSettings: {
+ title: "Saisie des messages",
+ plainText: "Saisie en texte brut",
+ plainTextDescription: "Conserver le code, le Markdown et les liens en texte brut. Désactivez pour afficher un aperçu mis en forme.",
+ showContext: "Afficher l’utilisation de la fenêtre de contexte",
+ sendShortcut: "Raccourci d’envoi",
+ sendDescription: "Choisissez si Entrée envoie un message ou insère une nouvelle ligne.",
+ followUp: "Messages de suivi",
+ followUpDescription: "Choisissez l’action lors d’un envoi pendant une réponse. Appuyez sur {shortcut} pour inverser ce choix pour un message.",
+ queue: "File d’attente",
+ steer: "Réorienter",
+ steerDescription: "Réorienter arrête la réponse en cours et envoie votre message de suivi en priorité.",
+ settings: "Paramètres de saisie",
+ preview: "Aperçu mis en forme",
+ },
picker: {
onDevice: "Sur l'appareil",
huggingFace: "Hugging Face",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index 6d10aa1e0ee..496b0bc6e88 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -5,6 +5,21 @@ import type { DeepPartialMessageTree } from "../types";
import type { en } from "./en";
export const hi = {
+ composerSettings: {
+ title: "संदेश लिखना",
+ plainText: "सादा टेक्स्ट इनपुट",
+ plainTextDescription: "कोड, Markdown और लिंक को मूल टेक्स्ट के रूप में रखें। फ़ॉर्मैट किया हुआ पूर्वावलोकन दिखाने के लिए इसे बंद करें।",
+ showContext: "कॉन्टेक्स्ट विंडो का उपयोग दिखाएँ",
+ sendShortcut: "भेजने का शॉर्टकट",
+ sendDescription: "चुनें कि Enter से संदेश भेजना है या नई पंक्ति जोड़नी है।",
+ followUp: "अगले संदेश का व्यवहार",
+ followUpDescription: "उत्तर के दौरान संदेश भेजने पर क्या होगा, चुनें। एक संदेश के लिए विपरीत विकल्प इस्तेमाल करने हेतु {shortcut} दबाएँ।",
+ queue: "कतार में जोड़ें",
+ steer: "दिशा बदलें",
+ steerDescription: "दिशा बदलने से वर्तमान उत्तर रुक जाता है और आपका अगला संदेश पहले भेजा जाता है।",
+ settings: "संदेश इनपुट की सेटिंग",
+ preview: "फ़ॉर्मैट किया हुआ पूर्वावलोकन",
+ },
picker: {
onDevice: "डिवाइस पर",
huggingFace: "Hugging Face",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 4a88d9b8d20..f3d18b9925d 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -2,6 +2,21 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
export const it = {
+ composerSettings: {
+ title: "Composizione dei messaggi",
+ plainText: "Composizione in testo semplice",
+ plainTextDescription: "Mantieni codice, Markdown e link come testo letterale. Disattiva per mostrare un’anteprima formattata.",
+ showContext: "Mostra l’utilizzo della finestra di contesto",
+ sendShortcut: "Scorciatoia di invio",
+ sendDescription: "Scegli se Invio invia un messaggio o inserisce una nuova riga.",
+ followUp: "Messaggi successivi",
+ followUpDescription: "Scegli cosa accade quando invii durante una risposta. Premi {shortcut} per fare il contrario per un messaggio.",
+ queue: "In coda",
+ steer: "Riorienta",
+ steerDescription: "Riorienta interrompe la risposta corrente e invia subito dopo il tuo messaggio successivo.",
+ settings: "Impostazioni di composizione",
+ preview: "Anteprima formattata",
+ },
common: {
cancel: "Annulla",
close: "Chiudi",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index 483fdc2a013..779459ee12b 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -6,6 +6,21 @@ import type { DeepPartialMessageTree } from "../types";
import type { en } from "./en";
export const ja = {
+ composerSettings: {
+ title: "入力欄",
+ plainText: "プレーンテキスト入力",
+ plainTextDescription: "コード、Markdown、リンクをそのままのテキストで表示します。オフにすると書式付きプレビューを表示します。",
+ showContext: "コンテキストウィンドウの使用量を表示",
+ sendShortcut: "送信ショートカット",
+ sendDescription: "Enter キーで送信するか改行するかを選択します。",
+ followUp: "追加メッセージの動作",
+ followUpDescription: "応答中に送信した場合の動作を選択します。{shortcut} を押すと、そのメッセージだけ逆の動作になります。",
+ queue: "キューに追加",
+ steer: "方向を変更",
+ steerDescription: "現在の応答を停止し、追加メッセージを次に送信します。",
+ settings: "入力欄の設定",
+ preview: "書式付きプレビュー",
+ },
picker: {
onDevice: "デバイス上",
huggingFace: "Hugging Face",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 4211f372ea1..b67ee91d55e 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -5,6 +5,21 @@ import type { DeepPartialMessageTree } from "../types";
import type { en } from "./en";
export const ko = {
+ composerSettings: {
+ title: "메시지 입력",
+ plainText: "일반 텍스트 입력",
+ plainTextDescription: "코드, Markdown, 링크를 원문 그대로 표시합니다. 끄면 서식 미리보기를 표시합니다.",
+ showContext: "컨텍스트 창 사용량 표시",
+ sendShortcut: "전송 단축키",
+ sendDescription: "Enter 키로 메시지를 보내거나 줄을 바꿀지 선택합니다.",
+ followUp: "후속 메시지 동작",
+ followUpDescription: "응답 중에 전송할 때의 동작을 선택합니다. {shortcut}을 누르면 해당 메시지만 반대로 처리합니다.",
+ queue: "대기열",
+ steer: "방향 변경",
+ steerDescription: "현재 응답을 중지하고 후속 메시지를 다음에 전송합니다.",
+ settings: "메시지 입력 설정",
+ preview: "서식 미리보기",
+ },
picker: {
onDevice: "기기",
huggingFace: "Hugging Face",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 630194cc4a1..99454cf6476 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -5,6 +5,21 @@ import type { DeepPartialMessageTree } from "../types";
import type { en } from "./en";
export const ptBR = {
+ composerSettings: {
+ title: "Composição de mensagens",
+ plainText: "Composição em texto simples",
+ plainTextDescription: "Manter código, Markdown e links como texto literal. Desative para mostrar uma prévia formatada.",
+ showContext: "Mostrar uso da janela de contexto",
+ sendShortcut: "Atalho de envio",
+ sendDescription: "Escolha se Enter envia uma mensagem ou insere uma nova linha.",
+ followUp: "Mensagens de acompanhamento",
+ followUpDescription: "Escolha o que acontece ao enviar durante uma resposta. Pressione {shortcut} para fazer o contrário em uma mensagem.",
+ queue: "Enfileirar",
+ steer: "Redirecionar",
+ steerDescription: "Redirecionar interrompe a resposta atual e envia sua mensagem de acompanhamento em seguida.",
+ settings: "Configurações de composição",
+ preview: "Prévia formatada",
+ },
picker: {
onDevice: "No dispositivo",
huggingFace: "Hugging Face",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index c464e8fde54..4b553eb0568 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -5,6 +5,21 @@ import type { DeepPartialMessageTree } from "../types";
import type { en } from "./en";
export const ru = {
+ composerSettings: {
+ title: "Ввод сообщений",
+ plainText: "Обычный текст",
+ plainTextDescription: "Показывать код, Markdown и ссылки как обычный текст. Отключите для предпросмотра форматирования.",
+ showContext: "Показывать использование контекстного окна",
+ sendShortcut: "Клавиши отправки",
+ sendDescription: "Выберите, отправляет ли Enter сообщение или добавляет новую строку.",
+ followUp: "Последующие сообщения",
+ followUpDescription: "Выберите действие при отправке во время ответа. Нажмите {shortcut}, чтобы выполнить противоположное действие для одного сообщения.",
+ queue: "В очередь",
+ steer: "Перенаправить",
+ steerDescription: "Перенаправление останавливает текущий ответ и отправляет ваше сообщение следующим.",
+ settings: "Настройки ввода",
+ preview: "Предпросмотр форматирования",
+ },
picker: {
onDevice: "На устройстве",
huggingFace: "Hugging Face",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 53527b7a464..3954752bc86 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -5,6 +5,21 @@ import type { DeepPartialMessageTree } from "../types";
import type { en } from "./en";
export const zhCN = {
+ composerSettings: {
+ title: "消息输入",
+ plainText: "纯文本输入",
+ plainTextDescription: "将代码、Markdown 和链接保留为原始文本。关闭后显示格式化预览。",
+ showContext: "显示上下文窗口使用量",
+ sendShortcut: "发送快捷键",
+ sendDescription: "选择按 Enter 发送消息还是插入新行。",
+ followUp: "后续消息行为",
+ followUpDescription: "选择在回复过程中发送消息时的操作。按 {shortcut} 可对单条消息执行相反操作。",
+ queue: "排队",
+ steer: "调整方向",
+ steerDescription: "调整方向会停止当前回复,并优先发送后续消息。",
+ settings: "输入设置",
+ preview: "格式化预览",
+ },
picker: {
onDevice: "本机",
huggingFace: "Hugging Face",
diff --git a/studio/frontend/tests/composer-preferences.test.ts b/studio/frontend/tests/composer-preferences.test.ts
new file mode 100644
index 00000000000..10434450177
--- /dev/null
+++ b/studio/frontend/tests/composer-preferences.test.ts
@@ -0,0 +1,133 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import {
+ composerSubmitIntent,
+ composerFollowUpBehavior,
+ composerShortcutLabels,
+ normalizeComposerPreferences,
+ type ComposerKeyEvent,
+} from "../src/features/chat/utils/composer-preferences.ts";
+import { installLocalStorageFake } from "./helpers/kit.ts";
+
+const enter: ComposerKeyEvent = {
+ key: "Enter",
+ metaKey: false,
+ ctrlKey: false,
+ shiftKey: false,
+ altKey: false,
+};
+for (const mod of ["metaKey", "ctrlKey"] as const) {
+ test(`${mod}: configured send, opposite follow-up, and newline chords`, () => {
+ assert.equal(composerSubmitIntent(enter, "enter"), "default");
+ assert.equal(
+ composerSubmitIntent({ ...enter, [mod]: true }, "enter"),
+ "opposite",
+ );
+ assert.equal(
+ composerSubmitIntent({ ...enter, shiftKey: true }, "enter"),
+ null,
+ );
+ assert.equal(
+ composerSubmitIntent({ ...enter, [mod]: true, shiftKey: true }, "enter"),
+ null,
+ );
+ assert.equal(composerSubmitIntent(enter, "mod-enter"), null);
+ assert.equal(
+ composerSubmitIntent({ ...enter, shiftKey: true }, "mod-enter"),
+ null,
+ );
+ assert.equal(
+ composerSubmitIntent({ ...enter, [mod]: true }, "mod-enter"),
+ "default",
+ );
+ assert.equal(
+ composerSubmitIntent(
+ { ...enter, [mod]: true, shiftKey: true },
+ "mod-enter",
+ ),
+ "opposite",
+ );
+ });
+}
+for (const blocked of [
+ { key: "a" },
+ { altKey: true },
+ { isComposing: true },
+ { keyCode: 229 },
+ { repeat: true },
+ { metaKey: true, ctrlKey: true },
+]) {
+ test(`do not submit ${JSON.stringify(blocked)}`, () => {
+ for (const shortcut of ["enter", "mod-enter"] as const) {
+ assert.equal(
+ composerSubmitIntent({ ...enter, ...blocked }, shortcut),
+ null,
+ );
+ assert.equal(
+ composerSubmitIntent({ ...enter, ctrlKey: true, ...blocked }, shortcut),
+ null,
+ );
+ }
+ });
+}
+test("one-message override flips both preferences without changing the default", () => {
+ assert.equal(composerFollowUpBehavior("queue", "default"), "queue");
+ assert.equal(composerFollowUpBehavior("queue", "opposite"), "steer");
+ assert.equal(composerFollowUpBehavior("steer", "default"), "steer");
+ assert.equal(composerFollowUpBehavior("steer", "opposite"), "queue");
+ assert.deepEqual(composerShortcutLabels("mod-enter", true), {
+ send: "⌘Enter",
+ opposite: "⇧⌘Enter",
+ });
+ assert.deepEqual(composerShortcutLabels("mod-enter", false), {
+ send: "Ctrl+Enter",
+ opposite: "Ctrl+Shift+Enter",
+ });
+});
+test("legacy and malformed saved settings retain usable defaults", () => {
+ const defaults = {
+ plainTextComposer: true,
+ showContextWindowUsage: true,
+ sendShortcut: "enter",
+ followUpBehavior: "queue",
+ };
+ for (const value of [
+ null,
+ undefined,
+ {},
+ {
+ plainTextComposer: "false",
+ showContextWindowUsage: 0,
+ sendShortcut: "tab",
+ followUpBehavior: "other",
+ },
+ ]) {
+ assert.deepEqual(normalizeComposerPreferences(value), defaults);
+ }
+});
+test("the real preference store persists all controls and restores them on reload", async () => {
+ const { store } = installLocalStorageFake();
+ const { useChatPreferencesStore: prefs } = await import(
+ "../src/features/chat/stores/chat-preferences-store.ts"
+ );
+ prefs.getState().setPlainTextComposer(false);
+ prefs.getState().setShowContextWindowUsage(false);
+ prefs.getState().setSendShortcut("mod-enter");
+ prefs.getState().setFollowUpBehavior("steer");
+ const saved = store.get("unsloth_chat_preferences")!;
+ const expected = {
+ plainTextComposer: false,
+ showContextWindowUsage: false,
+ sendShortcut: "mod-enter",
+ followUpBehavior: "steer",
+ };
+ assert.deepEqual(
+ normalizeComposerPreferences(JSON.parse(saved).state),
+ expected,
+ );
+ prefs.setState(normalizeComposerPreferences(null));
+ store.set("unsloth_chat_preferences", saved);
+ await prefs.persist.rehydrate();
+ assert.deepEqual(normalizeComposerPreferences(prefs.getState()), expected);
+ assert.equal(typeof prefs.getState().setFollowUpBehavior, "function");
+});
diff --git a/studio/frontend/tests/composer-steering.test.ts b/studio/frontend/tests/composer-steering.test.ts
new file mode 100644
index 00000000000..3d001ad8701
--- /dev/null
+++ b/studio/frontend/tests/composer-steering.test.ts
@@ -0,0 +1,1083 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import ts from "typescript";
+import { readSrc } from "./helpers/kit.ts";
+import {
+ localPromptQueueModelBoundary,
+ shouldAbortPendingQueueForModelBoundary,
+ shouldAbortPendingQueueForSettingsChange,
+} from "../src/features/chat/utils/prompt-queue-model-boundary.ts";
+import { snapshotQueuedChatRunSettings } from "../src/features/chat/utils/queued-chat-run-settings.ts";
+import { reorderPromptQueueItems } from "../src/features/chat/utils/prompt-queue-reorder.ts";
+import { steeringInsertionIndex } from "../src/features/chat/utils/composer-preferences.ts";
+import { chatModelLifecycleGate } from "../src/features/chat/utils/model-lifecycle-gate.ts";
+import { parseExternalModelId } from "../src/features/chat/external-providers.ts";
+import {
+ planUserPromptQueueStop,
+ userStopTargetCancelMode,
+} from "../src/features/chat/utils/prompt-queue-user-stop.ts";
+
+// Run the production queue engine with controlled stores and transport.
+const source = ts.createSourceFile(
+ "thread.tsx",
+ readSrc("components/assistant-ui/thread.tsx"),
+ ts.ScriptTarget.Latest,
+ true,
+ ts.ScriptKind.TSX,
+);
+const names = [
+ "startPromptQueue",
+ "steerPromptQueueTarget",
+ "steerPromptQueueItem",
+ "findPromptQueueRunByItemId",
+ "pausePromptQueueRun",
+ "resumePromptQueueRun",
+ "getPromptQueueRunsForThreadIds",
+ "getActivePromptQueueItem",
+ "createQueuedPrompt",
+ "getPromptQueueTargetIds",
+ "getPromptQueueRunTargetIds",
+ "promptQueueRunMatchesThreadIds",
+ "findPromptQueueRunByTarget",
+ "findPromptQueueRunByThreadIds",
+ "isPromptQueueTargetRunning",
+ "isActivePromptQueueItem",
+ "dispatchQueuedPrompt",
+ "isPromptQueueRunReadyToDispatch",
+ "handlePromptQueueRunState",
+ "isPromptQueueRunTargetRunning",
+ "advancePromptQueue",
+ "handlePromptQueueRunFailed",
+ "retainPendingPromptQueueItemsAfterFailure",
+];
+const declarations = names
+ .map((name) => {
+ const node = source.statements.find(
+ (node) => ts.isFunctionDeclaration(node) && node.name?.text === name,
+ );
+ assert.ok(node, `Missing production function ${name}`);
+ return node.getText(source);
+ })
+ .join("\n");
+const js = ts.transpileModule(declarations, {
+ compilerOptions: {
+ target: ts.ScriptTarget.ES2022,
+ module: ts.ModuleKind.None,
+ },
+}).outputText;
+
+type Target = ReturnType<typeof makeTarget>;
+type Item = { id: string; prompt: string; target: Target; dispatched: boolean };
+type Run = {
+ id: string;
+ items: Item[];
+ index: number;
+ generation: number;
+ paused: boolean;
+ waitingForTargetIdle: boolean;
+};
+function makeTarget(id: string, running = true) {
+ return {
+ getRunningThreadIds: () => (id ? [id] : []),
+ getDocumentThreadId: () => id || null,
+ running,
+ usesLocalModel: true,
+ researchStarted: () => false,
+ complete: () => undefined,
+ cancels: 0,
+ permanentCancels: 0,
+ deepResearch: 0,
+ isRunning() {
+ return this.running;
+ },
+ cancelActiveRun() {
+ this.cancels += 1;
+ },
+ cancel() {
+ this.permanentCancels += 1;
+ },
+ consumeDeepResearch() {
+ this.deepResearch += 1;
+ },
+ };
+}
+function world() {
+ const runs = new Map<string, Run>();
+ const appended: string[] = [];
+ const scopedCancels: string[][] = [];
+ let serial = 0;
+ let modelLoading = false;
+ let dispatchRetries = 0;
+ let indexing: () => Promise<boolean> = async () => false;
+ const noop = () => undefined;
+ const deps = {
+ promptQueueRuns: runs,
+ promptQueueRunOrder: [],
+ promptQueueActiveRunIds: new Set(),
+ promptQueueDispatchingRunIds: new Set(),
+ compactIds: (ids: unknown[]) => [...new Set(ids.filter(Boolean))],
+ createPromptQueueRunId: () => `run-${++serial}`,
+ createPromptQueueItemId: () => `item-${++serial}`,
+ planUserPromptQueueStop,
+ userStopTargetCancelMode,
+ steeringInsertionIndex,
+ cancelPreStreamRunForThreadIds: (ids: string[]) => scopedCancels.push(ids),
+ useChatRuntimeStore: {
+ getState: () => ({ runningByThreadId: {}, modelLoading }),
+ },
+ syncPromptQueueUI: noop,
+ ensurePromptQueueSubscription: noop,
+ requestPromptQueuePump: noop,
+ requestPromptQueuePumpIfReady: noop,
+ clearPromptQueueRetryTimer: noop,
+ schedulePromptQueueTargetStatePoll: noop,
+ scheduleQueuedPromptDispatch: () => {
+ dispatchRetries += 1;
+ },
+ PROMPT_QUEUE_DISPATCH_RETRY_MS: 500,
+ PROMPT_QUEUE_INDEXING_RETRY_MS: 1,
+ deletePromptQueueRun: (run: Run) => runs.delete(run.id),
+ toast: { info: noop },
+ discardQueuedChatRunSettingsForThread: noop,
+ targetHasIndexingDocuments: () => indexing(),
+ appendQueuedPrompt: (_run: Run, item: Item) => {
+ appended.push(item.prompt);
+ item.dispatched = true;
+ },
+ };
+ const engine = new Function(
+ ...Object.keys(deps),
+ `${js}\nreturn {startPromptQueue, steerPromptQueueItem, dispatchQueuedPrompt, isPromptQueueRunReadyToDispatch, handlePromptQueueRunState, handlePromptQueueRunFailed, resumePromptQueueRun};`,
+ )(...Object.values(deps)) as {
+ handlePromptQueueRunFailed: (
+ threadId?: string,
+ localOnly?: boolean,
+ ) => void;
+ resumePromptQueueRun: (threadIds?: string[]) => void;
+ startPromptQueue: (
+ items: string[],
+ target: Target,
+ wait?: boolean,
+ behavior?: "queue" | "steer",
+ ) => void;
+ steerPromptQueueItem: (id: string) => boolean;
+ dispatchQueuedPrompt: (
+ run: Run,
+ item: Item,
+ generation?: number,
+ ) => Promise<void>;
+ isPromptQueueRunReadyToDispatch: (run: Run) => boolean;
+ handlePromptQueueRunState: (
+ run: Run,
+ runningByThreadId: Record<string, boolean>,
+ ) => void;
+ };
+ return {
+ ...engine,
+ runs,
+ appended,
+ scopedCancels,
+ setModelLoading: (loading: boolean) => {
+ modelLoading = loading;
+ },
+ dispatchRetries: () => dispatchRetries,
+ setIndexing: (probe: () => Promise<boolean>) => {
+ indexing = probe;
+ },
+ run: () => [...runs.values()][0]!,
+ };
+}
+
+test("steer interrupts the dispatched prompt, preserves later prompts and completed history", async () => {
+ const w = world();
+ const old = makeTarget("chat");
+ const fresh = makeTarget("chat");
+ const sibling = makeTarget("sibling");
+ w.startPromptQueue(["completed", "active", "later A", "later B"], old);
+ const run = w.run();
+ run.items[0].dispatched = true;
+ run.items[1].dispatched = true;
+ run.index = 1;
+ w.startPromptQueue(["sibling prompt"], sibling);
+ w.startPromptQueue([" urgent "], fresh, true, "steer");
+ assert.deepEqual(
+ run.items.map((i) => i.prompt),
+ ["completed", "urgent", "later A", "later B"],
+ );
+ assert.equal(run.index, 1);
+ assert.equal(run.paused, false);
+ assert.equal(run.generation, 1);
+ assert.equal(old.cancels, 1);
+ assert.equal(old.permanentCancels, 0);
+ assert.equal(fresh.cancels, 1);
+ assert.equal(sibling.cancels, 0);
+ assert.deepEqual(w.scopedCancels, [["chat"]]);
+ await w.dispatchQueuedPrompt(run, run.items[1]);
+ assert.deepEqual(w.appended, [], "wait for the actual response to stop");
+ fresh.running = false;
+ run.waitingForTargetIdle = false;
+ await w.dispatchQueuedPrompt(run, run.items[1]);
+ assert.deepEqual(w.appended, ["urgent"]);
+});
+
+test("steer starts before every pending item while a queue is waiting or paused", () => {
+ for (const paused of [true, false]) {
+ const w = world();
+ const target = makeTarget("chat");
+ w.startPromptQueue(["pending A", "pending B"], target, true);
+ const run = w.run();
+ run.paused = paused;
+ w.startPromptQueue(["urgent A", "urgent B"], target, true, "steer");
+ assert.deepEqual(
+ run.items.map((i) => i.prompt),
+ ["urgent A", "urgent B", "pending A", "pending B"],
+ );
+ assert.equal(run.index, 0);
+ assert.equal(run.paused, false);
+ assert.equal(w.isPromptQueueRunReadyToDispatch(run), true);
+ }
+});
+
+test("an in-flight indexing probe cannot dispatch the old item after a steer", async () => {
+ const w = world();
+ const target = makeTarget("chat", false);
+ w.startPromptQueue(["old first", "old second"], target);
+ const run = w.run();
+ const old = run.items[0];
+ let resolve!: (value: boolean) => void;
+ w.setIndexing(
+ () =>
+ new Promise((r) => {
+ resolve = r;
+ }),
+ );
+ const staleDispatch = w.dispatchQueuedPrompt(run, old);
+ w.startPromptQueue(["urgent"], target, false, "steer");
+ resolve(false);
+ await staleDispatch;
+ assert.deepEqual(w.appended, []);
+ assert.deepEqual(
+ run.items.map((i) => i.prompt),
+ ["urgent", "old first", "old second"],
+ );
+ w.setIndexing(async () => false);
+ await w.dispatchQueuedPrompt(run, run.items[0]);
+ assert.deepEqual(w.appended, ["urgent"]);
+});
+
+test("normal queue follow-ups append without interrupting", () => {
+ const w = world();
+ const target = makeTarget("chat");
+ w.startPromptQueue(["first"], target, true);
+ w.startPromptQueue(["second"], target, true, "queue");
+ assert.deepEqual(
+ w.run().items.map((i) => i.prompt),
+ ["first", "second"],
+ );
+ assert.equal(target.cancels, 0);
+ assert.deepEqual(w.scopedCancels, []);
+});
+
+test("row steer retains the selected item and history, cancelling its shared target once", async () => {
+ const w = world();
+ const target = makeTarget("chat");
+ const sibling = makeTarget("other chat");
+ w.startPromptQueue(["completed", "active", "later A", "later B"], target);
+ const run = w.run();
+ run.items[0].dispatched = true;
+ run.items[1].dispatched = true;
+ run.index = 1;
+ const selected = run.items[3];
+ w.startPromptQueue(["untouched"], sibling);
+
+ assert.equal(w.steerPromptQueueItem(selected.id), true);
+ assert.deepEqual(
+ run.items.map((item) => item.prompt),
+ ["completed", "later B", "later A"],
+ );
+ assert.equal(run.items[1], selected);
+ assert.equal(run.index, 1);
+ assert.equal(run.generation, 1);
+ assert.equal(target.cancels, 1);
+ assert.equal(target.permanentCancels, 0);
+ assert.equal(sibling.cancels, 0);
+ assert.deepEqual(w.scopedCancels, [["chat"]]);
+ await w.dispatchQueuedPrompt(run, selected);
+ assert.deepEqual(w.appended, []);
+ target.running = false;
+ w.handlePromptQueueRunState(run, {});
+ await w.dispatchQueuedPrompt(run, selected);
+ assert.deepEqual(w.appended, ["later B"]);
+ assert.equal(w.steerPromptQueueItem(selected.id), false);
+ assert.equal(target.cancels, 1);
+});
+
+test("row steer resumes paused and waiting queues with the chosen prompt first", () => {
+ for (const paused of [true, false]) {
+ for (const selectedIndex of [0, 2]) {
+ const w = world();
+ const target = makeTarget("chat");
+ w.startPromptQueue(["first", "second", "third"], target, true);
+ const run = w.run();
+ run.paused = paused;
+ const before = [...run.items];
+ const selected = before[selectedIndex];
+ assert.equal(w.steerPromptQueueItem(selected.id), true);
+ assert.deepEqual(run.items, [
+ selected,
+ ...before.filter((i) => i !== selected),
+ ]);
+ assert.equal(run.index, 0);
+ assert.equal(run.paused, false);
+ assert.equal(target.cancels, 1);
+ }
+ }
+});
+
+test("row steer handles a sole pending prompt without dropping or duplicating it", () => {
+ const w = world();
+ const target = makeTarget("chat", false);
+ w.startPromptQueue(["only prompt"], target);
+ const run = w.run();
+ const selected = run.items[0];
+ assert.equal(w.steerPromptQueueItem(selected.id), true);
+ assert.deepEqual(run.items, [selected]);
+ assert.equal(run.index, 0);
+ assert.equal(run.paused, false);
+});
+
+test("row steer rejects stale, dispatched, unavailable and active research prompts", () => {
+ const w = world();
+ const target = makeTarget("chat");
+ w.startPromptQueue(["active", "pending"], target);
+ const run = w.run();
+ run.items[0].dispatched = true;
+ const before = [...run.items];
+ assert.equal(w.steerPromptQueueItem("missing"), false);
+ assert.equal(w.steerPromptQueueItem(run.items[0].id), false);
+ target.researchStarted = () => true;
+ assert.equal(w.steerPromptQueueItem(run.items[1].id), false);
+ target.researchStarted = () => false;
+ target.getRunningThreadIds = () => [];
+ target.getDocumentThreadId = () => null;
+ assert.equal(w.steerPromptQueueItem(run.items[1].id), false);
+ assert.deepEqual(run.items, before);
+ assert.equal(target.cancels, 0);
+ assert.deepEqual(w.scopedCancels, []);
+});
+
+test("row steer invalidates an in-flight document probe and waits for model loading", async () => {
+ const w = world();
+ const target = makeTarget("chat", false);
+ w.startPromptQueue(["first", "second", "third"], target);
+ const run = w.run();
+ const selected = run.items[2];
+ let resolve!: (value: boolean) => void;
+ w.setIndexing(
+ () =>
+ new Promise((r) => {
+ resolve = r;
+ }),
+ );
+ const staleDispatch = w.dispatchQueuedPrompt(run, run.items[0]);
+ w.setModelLoading(true);
+ assert.equal(w.steerPromptQueueItem(selected.id), true);
+ resolve(false);
+ await staleDispatch;
+ assert.deepEqual(w.appended, []);
+ w.setIndexing(async () => false);
+ await w.dispatchQueuedPrompt(run, selected);
+ assert.deepEqual(w.appended, []);
+ assert.equal(selected.dispatched, false);
+ w.setModelLoading(false);
+ await w.dispatchQueuedPrompt(run, selected);
+ assert.equal(w.isPromptQueueRunReadyToDispatch(run), false);
+ assert.deepEqual(w.appended, ["third"]);
+ assert.deepEqual(
+ run.items.map((item) => item.prompt),
+ ["third", "first", "second"],
+ );
+});
+
+test("a new steering queue waits for cancellation and rejects an unidentified target", async () => {
+ const w = world();
+ const target = makeTarget("chat");
+ w.startPromptQueue(["urgent"], target, true, "steer");
+ assert.equal(w.run().index, 0);
+ assert.equal(target.cancels, 1);
+ await w.dispatchQueuedPrompt(w.run(), w.run().items[0]);
+ assert.deepEqual(w.appended, []);
+ assert.throws(
+ () => w.startPromptQueue(["wrong chat"], makeTarget(""), true, "steer"),
+ /no longer available/,
+ );
+ assert.equal(w.runs.size, 1);
+ assert.deepEqual(w.scopedCancels, [["chat"]]);
+});
+
+// Exercise the production queue factory with controlled settings hydration.
+function composerCallbackJs(name: string) {
+ let factory: ts.Expression | undefined;
+ function visit(node: ts.Node) {
+ if (
+ ts.isVariableDeclaration(node) &&
+ node.name.getText(source) === name &&
+ node.initializer &&
+ ts.isCallExpression(node.initializer)
+ ) {
+ factory = node.initializer.arguments[0];
+ }
+ ts.forEachChild(node, visit);
+ }
+ visit(source);
+ assert.ok(factory, `Missing production callback ${name}`);
+ return ts.transpileModule(`return (${factory.getText(source)});`, {
+ compilerOptions: {
+ target: ts.ScriptTarget.ES2022,
+ module: ts.ModuleKind.None,
+ },
+ }).outputText;
+}
+const factoryJs = composerCallbackJs("startHydratedPromptQueue");
+const targetFactoryJs = composerCallbackJs("createPromptQueueTarget");
+
+async function targetForSelection(
+ checkpoint: string,
+ modelLoading: boolean,
+ incoming: string | null,
+ selectionSuperseded = false,
+) {
+ let settings!: ReturnType<typeof snapshotQueuedChatRunSettings>;
+ const runtime = {
+ params: { checkpoint, temperature: 0.4 },
+ activeGgufVariant: "old-Q4.gguf",
+ loadingModelPick: incoming ? { id: incoming, selectionSuperseded } : null,
+ modelLoading,
+ permissionMode: "ask",
+ toolsEnabled: true,
+ ragEnabled: false,
+ incognito: false,
+ hydratePersistedSettings: async () => undefined,
+ };
+ const deps = {
+ aui: {
+ threads: () => ({}),
+ threadListItem: () => ({ getState: () => ({ id: "chat", remoteId: "chat" }) }),
+ },
+ referenceThreadId: "chat",
+ chatHistoryClearBoundary: { capture: () => 0 },
+ promptQueueTargetMountedRef: { current: true },
+ indexingActiveRef: { current: false },
+ useChatRuntimeStore: { getState: () => runtime },
+ compactIds: (ids: unknown[]) => [...new Set(ids.filter(Boolean))],
+ snapshotQueuedChatRunSettings: (...args: Parameters<typeof snapshotQueuedChatRunSettings>) => {
+ settings = snapshotQueuedChatRunSettings(...args);
+ return settings;
+ },
+ parseExternalModelId,
+ hasPreStreamRunReservation: () => false,
+ };
+ const create = new Function(...Object.keys(deps), targetFactoryJs)(
+ ...Object.values(deps),
+ ) as () => Promise<Target>;
+ return { target: Object.assign(makeTarget("chat", false), await create()), settings };
+}
+
+function hydratedFactory(
+ w: ReturnType<typeof world>,
+ target: Target,
+ hydrate = () => Promise.resolve(target),
+) {
+ const pending = new Map();
+ const deps = {
+ referenceThreadId: "chat",
+ promptQueueStartPendingRef: { current: pending },
+ pendingQueueStartIsStale: () => false,
+ useChatRuntimeStore: {
+ getState: () => ({
+ modelLoading: true,
+ queuedSettingsEpoch: 0,
+ incognito: false,
+ }),
+ },
+ localPromptQueueModelBoundary,
+ shouldAbortPendingQueueForModelBoundary,
+ shouldAbortPendingQueueForSettingsChange,
+ createPromptQueueTarget: hydrate,
+ startPromptQueue: w.startPromptQueue,
+ toast: { error: (message: string) => assert.fail(message) },
+ };
+ return new Function(...Object.keys(deps), factoryJs)(
+ ...Object.values(deps),
+ ) as (
+ prompts: string[],
+ wait: boolean,
+ onStarted?: () => void,
+ onAborted?: () => void,
+ capturedAt?: {
+ localModelBoundaryGeneration: number;
+ queuedSettingsEpoch: number;
+ temporary: boolean;
+ },
+ behavior?: "queue" | "steer",
+ ) => boolean;
+}
+
+for (const firstBehavior of ["queue", "steer"] as const) {
+ for (const latestBehavior of ["queue", "steer"] as const) {
+ for (const latestWait of [true, false]) {
+ test(`pending follow-up intent: ${firstBehavior} to ${latestBehavior}, wait=${latestWait}`, async () => {
+ const w = world();
+ const target = makeTarget("chat");
+ const resolves: ((target: Target) => void)[] = [];
+ const accept = hydratedFactory(
+ w,
+ target,
+ () => new Promise((resolve) => resolves.push(resolve)),
+ );
+ let cleared = 0;
+ const onStarted = () => {
+ cleared++;
+ };
+ accept(
+ ["same draft"],
+ true,
+ onStarted,
+ undefined,
+ undefined,
+ firstBehavior,
+ );
+ accept(
+ ["same draft"],
+ latestWait,
+ onStarted,
+ undefined,
+ undefined,
+ latestBehavior,
+ );
+ for (const resolve of resolves) resolve(target);
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ assert.deepEqual(
+ w.run().items.map((item) => item.prompt),
+ ["same draft"],
+ );
+ assert.equal(resolves.length, 1, "hydrate the same pending draft only once");
+ assert.equal(cleared, 1);
+ assert.equal(target.cancels, Number(latestBehavior === "steer"));
+ if (latestBehavior === "queue") {
+ assert.equal(w.run().index, latestWait ? -1 : 0);
+ }
+ });
+ }
+ }
+}
+
+test("pending follow-up intent preserves distinct drafts and later repeat submissions", async () => {
+ const w = world();
+ const target = makeTarget("chat");
+ const accept = hydratedFactory(w, target);
+ let cleared = 0;
+ const onStarted = () => {
+ cleared++;
+ };
+ accept(["first draft"], true, onStarted);
+ accept(["second draft"], true, onStarted);
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ assert.equal(accept(["first draft"], true, onStarted), true);
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ assert.deepEqual(
+ w.run().items.map((item) => item.prompt),
+ ["first draft", "second draft", "first draft"],
+ );
+ assert.equal(cleared, 3);
+});
+
+test("three follow-ups are accepted and reorderable during loading, then dispatch in order after the first response", async () => {
+ const w = world();
+ w.setModelLoading(true);
+ const target = makeTarget("chat");
+ const accept = hydratedFactory(w, target);
+ const cleared: string[] = [];
+ for (const text of ["second", "third", "fourth"]) {
+ assert.equal(
+ accept([text], true, () => cleared.push(text)),
+ true,
+ );
+ }
+ await Promise.resolve();
+ assert.deepEqual(
+ cleared,
+ ["second", "third", "fourth"],
+ "the composer clears each accepted prompt so another can be entered",
+ );
+ const run = w.run();
+ assert.deepEqual(
+ run.items.map((i) => i.prompt),
+ cleared,
+ );
+ assert.ok(run.items.every((i) => !i.dispatched));
+ assert.equal(run.index, -1);
+ run.items = reorderPromptQueueItems(run.items, 2, 0)!;
+ assert.deepEqual(
+ run.items.map((i) => i.prompt),
+ ["fourth", "second", "third"],
+ );
+ await w.dispatchQueuedPrompt(run, run.items[0]);
+ assert.deepEqual(w.appended, []);
+ assert.equal(w.dispatchRetries(), 1);
+ w.setModelLoading(false);
+ w.handlePromptQueueRunState(run, {});
+ assert.equal(
+ run.index,
+ -1,
+ "finishing the model load must not skip the first response",
+ );
+ target.running = false;
+ w.handlePromptQueueRunState(run, {});
+ assert.equal(run.index, 0);
+ for (const text of ["fourth", "second", "third"]) {
+ const item: Item = run.items[run.index];
+ assert.equal(item.prompt, text);
+ await w.dispatchQueuedPrompt(run, item);
+ target.running = true;
+ w.handlePromptQueueRunState(run, {});
+ target.running = false;
+ w.handlePromptQueueRunState(run, {});
+ }
+ assert.deepEqual(w.appended, ["fourth", "second", "third"]);
+ assert.equal(w.runs.size, 0);
+});
+
+test("model preparation keeps a follow-up draft until the final switch boundary", async () => {
+ const w = world();
+ const target = makeTarget("chat");
+ const lease = chatModelLifecycleGate.tryAcquire("preparing");
+ assert.notEqual(lease, null);
+ try {
+ const accept = hydratedFactory(w, target);
+ let cleared = false;
+ accept(["keep this draft"], true, () => {
+ cleared = true;
+ });
+ await Promise.resolve();
+ assert.equal(
+ cleared,
+ false,
+ "preflight must not clear a draft into a queue the switch will delete",
+ );
+ assert.equal(w.runs.size, 0);
+ localPromptQueueModelBoundary.advance();
+ localPromptQueueModelBoundary.advance();
+ chatModelLifecycleGate.markLoading(lease!);
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ accept(["keep this draft"], true, () => {
+ cleared = true;
+ });
+ await Promise.resolve();
+ assert.equal(cleared, true);
+ assert.deepEqual(
+ w.run().items.map((item) => item.prompt),
+ ["keep this draft"],
+ );
+ } finally {
+ chatModelLifecycleGate.release(lease!);
+ }
+});
+
+test("a failed initial load pauses accepted follow-ups for recovery", async () => {
+ for (const waitForInitial of [true, false]) {
+ const w = world();
+ const target = makeTarget("chat", false);
+ w.startPromptQueue(
+ ["recover first", "recover second"],
+ target,
+ waitForInitial,
+ );
+ const run = w.run();
+ const ids = run.items.map((item) => item.id);
+ w.handlePromptQueueRunFailed("chat");
+ assert.equal(w.runs.size, 1, "accepted prompts must survive a failed load");
+ assert.equal(run.paused, true);
+ assert.equal(w.isPromptQueueRunReadyToDispatch(run), false);
+ assert.deepEqual(
+ run.items.map((item) => item.id),
+ ids,
+ );
+ w.handlePromptQueueRunFailed("chat");
+ assert.deepEqual(
+ run.items.map((item) => item.id),
+ ids,
+ );
+ w.resumePromptQueueRun(["chat"]);
+ assert.equal(run.index, 0);
+ await w.dispatchQueuedPrompt(run, run.items[0]);
+ assert.deepEqual(w.appended, ["recover first"]);
+ }
+});
+
+test("a failed manual load cannot send queued local prompts on the rollback model", async () => {
+ const w = world();
+ const local = makeTarget("chat", false);
+ const external = makeTarget("external", false);
+ external.usesLocalModel = false;
+ w.startPromptQueue(["wait for chosen model"], local);
+ w.startPromptQueue(["external still works"], external);
+ const run = w.run();
+ w.handlePromptQueueRunFailed(undefined, true);
+ await w.dispatchQueuedPrompt(run, run.items[0]);
+ assert.deepEqual(
+ w.appended,
+ [],
+ "rollback must not silently change the queued model",
+ );
+ const sibling = [...w.runs.values()][1];
+ await w.dispatchQueuedPrompt(sibling, sibling.items[0]);
+ assert.deepEqual(w.appended, ["external still works"]);
+ w.resumePromptQueueRun(["chat"]);
+ await w.dispatchQueuedPrompt(run, run.items[0]);
+ assert.deepEqual(w.appended, [
+ "external still works",
+ "wait for chosen model",
+ ]);
+});
+
+test("a mixed queue finishes its external response before blocking the local follow-up", async () => {
+ const w = world();
+ const external = makeTarget("chat", false);
+ external.usesLocalModel = false;
+ const local = makeTarget("chat", false);
+ w.startPromptQueue(["external response"], external);
+ w.startPromptQueue(["local follow-up"], local);
+ const run = w.run();
+ await w.dispatchQueuedPrompt(run, run.items[0]);
+ external.running = true;
+ w.handlePromptQueueRunState(run, {});
+ w.handlePromptQueueRunFailed(undefined, true);
+ assert.equal(external.cancels, 0);
+ assert.equal(external.permanentCancels, 0);
+ external.running = false;
+ w.handlePromptQueueRunState(run, {});
+ assert.equal(run.index, 1);
+ assert.equal(w.isPromptQueueRunReadyToDispatch(run), false);
+ await w.dispatchQueuedPrompt(run, run.items[1]);
+ assert.deepEqual(w.appended, ["external response"]);
+ w.resumePromptQueueRun(["chat"]);
+ await w.dispatchQueuedPrompt(run, run.items[1]);
+ assert.deepEqual(w.appended, ["external response", "local follow-up"]);
+});
+
+test("resuming a blocked local follow-up preserves the pending external document check", async () => {
+ const w = world();
+ const external = makeTarget("chat", false);
+ external.usesLocalModel = false;
+ w.startPromptQueue(["external response"], external);
+ w.startPromptQueue(["local follow-up"], makeTarget("chat", false));
+ const run = w.run();
+ let resolve!: (indexing: boolean) => void;
+ w.setIndexing(
+ () =>
+ new Promise((r) => {
+ resolve = r;
+ }),
+ );
+ const pending = w.dispatchQueuedPrompt(run, run.items[0]);
+ w.handlePromptQueueRunFailed(undefined, true);
+ w.resumePromptQueueRun(["chat"]);
+ w.resumePromptQueueRun(["chat"]);
+ resolve(false);
+ await pending;
+ assert.deepEqual(w.appended, ["external response"]);
+ external.running = true;
+ w.handlePromptQueueRunState(run, {});
+ external.running = false;
+ w.handlePromptQueueRunState(run, {});
+ w.setIndexing(async () => false);
+ await w.dispatchQueuedPrompt(run, run.items[1]);
+ assert.deepEqual(w.appended, ["external response", "local follow-up"]);
+});
+
+test("load failure invalidates a local document probe without duplicate dispatch on resume", async () => {
+ const w = world();
+ const target = makeTarget("chat", false);
+ w.startPromptQueue(["pending"], target);
+ const run = w.run();
+ let resolve!: (indexing: boolean) => void;
+ w.setIndexing(
+ () =>
+ new Promise((r) => {
+ resolve = r;
+ }),
+ );
+ const pending = w.dispatchQueuedPrompt(run, run.items[0]);
+ w.handlePromptQueueRunFailed(undefined, true);
+ w.resumePromptQueueRun(["chat"]);
+ w.setIndexing(async () => false);
+ await w.dispatchQueuedPrompt(run, run.items[0]);
+ resolve(false);
+ await pending;
+ assert.deepEqual(w.appended, ["pending"]);
+});
+
+test("steering during loading leaves the queued prompt pending until loading finishes", async () => {
+ const w = world();
+ w.setModelLoading(true);
+ const target = makeTarget("chat", false);
+ w.startPromptQueue(["steer next"], target, false, "steer");
+ const run = w.run();
+ await w.dispatchQueuedPrompt(run, run.items[0]);
+ assert.deepEqual(w.appended, []);
+ assert.equal(run.items[0].dispatched, false);
+ w.setModelLoading(false);
+ await w.dispatchQueuedPrompt(run, run.items[0]);
+ assert.deepEqual(w.appended, ["steer next"]);
+});
+
+for (const phase of ["legacy", "preparing", "loading", "unloading"] as const) {
+ for (const local of [true, false]) {
+ for (const boundaryChanges of [0, 1, 2]) {
+ test(`hydration: ${phase}, local=${local}, boundaries=${boundaryChanges}`, async () => {
+ const w = world();
+ const target = makeTarget("chat");
+ target.usesLocalModel = local;
+ const lease = chatModelLifecycleGate.tryAcquire(
+ phase === "legacy" ? undefined : phase,
+ )!;
+ let resolve!: (target: Target) => void;
+ try {
+ const accept = hydratedFactory(
+ w,
+ target,
+ () =>
+ new Promise((r) => {
+ resolve = r;
+ }),
+ );
+ let started = 0;
+ let aborted = 0;
+ accept(
+ ["saved follow-up"],
+ true,
+ () => {
+ started++;
+ },
+ () => {
+ aborted++;
+ },
+ );
+ accept(
+ ["saved follow-up"],
+ true,
+ () => {
+ started++;
+ },
+ () => {
+ aborted++;
+ },
+ );
+ for (let n = 0; n < boundaryChanges; n++)
+ localPromptQueueModelBoundary.advance();
+ resolve(target);
+ await new Promise<void>((r) => setImmediate(r));
+ const accepted =
+ !local || (phase === "loading" && boundaryChanges === 0);
+ assert.equal(started, Number(accepted));
+ assert.equal(aborted, Number(!accepted));
+ assert.equal(w.runs.size, Number(accepted));
+ } finally {
+ chatModelLifecycleGate.release(lease);
+ }
+ });
+ }
+ }
+}
+
+test("an external queue still dispatches while the local model loads", async () => {
+ const w = world();
+ w.setModelLoading(true);
+ const target = makeTarget("external", false);
+ target.usesLocalModel = false;
+ w.startPromptQueue(["external prompt"], target);
+ await w.dispatchQueuedPrompt(w.run(), w.run().items[0]);
+ assert.deepEqual(w.appended, ["external prompt"]);
+ assert.equal(w.dispatchRetries(), 0);
+});
+
+test("a real model boundary still rejects a pending factory and preserves its draft", async () => {
+ const w = world();
+ const target = makeTarget("chat");
+ let resolve!: (target: Target) => void;
+ const accept = hydratedFactory(
+ w,
+ target,
+ () =>
+ new Promise((r) => {
+ resolve = r;
+ }),
+ );
+ let cleared = false;
+ let aborted = false;
+ accept(
+ ["old model"],
+ true,
+ () => {
+ cleared = true;
+ },
+ () => {
+ aborted = true;
+ },
+ );
+ localPromptQueueModelBoundary.advance();
+ resolve(target);
+ await Promise.resolve();
+ assert.equal(cleared, false);
+ assert.equal(aborted, true);
+ assert.equal(w.runs.size, 0);
+});
+
+test("loading defers model resolution while retaining queued sampling and permission preferences", () => {
+ const state = {
+ params: { checkpoint: "outgoing-model", temperature: 0.4 },
+ activeGgufVariant: "old-Q4.gguf",
+ permissionMode: "ask",
+ toolsEnabled: true,
+ };
+ const typed = state as unknown as Parameters<
+ typeof snapshotQueuedChatRunSettings
+ >[0];
+ const loading = snapshotQueuedChatRunSettings(typed, {
+ deferModelResolution: true,
+ });
+ assert.equal(loading.params.checkpoint, "");
+ assert.equal(loading.activeGgufVariant, null);
+ assert.equal(loading.params.temperature, 0.4);
+ assert.equal(loading.permissionMode, "ask");
+ assert.equal(loading.toolsEnabled, true);
+ assert.equal(state.params.checkpoint, "outgoing-model");
+ const ready = snapshotQueuedChatRunSettings(typed);
+ assert.equal(ready.params.checkpoint, "outgoing-model");
+ assert.equal(ready.activeGgufVariant, "old-Q4.gguf");
+});
+
+for (const behavior of ["queue", "steer"] as const) {
+ for (const failed of [false, true]) {
+ test(`external-to-local switch waits for the incoming model: ${behavior}, failed=${failed}`, async () => {
+ const w = world();
+ w.setModelLoading(true);
+ const { target, settings } = await targetForSelection(
+ "external::provider::hosted-model", true, "incoming-local",
+ );
+ w.startPromptQueue(["wait for the selected model"], target, false, behavior);
+ const run = w.run();
+ await w.dispatchQueuedPrompt(run, run.items[0]);
+ assert.deepEqual(w.appended, [], "never send to the outgoing hosted provider");
+ assert.equal(target.usesLocalModel, true);
+ assert.equal(settings.params.checkpoint, "");
+ assert.equal(settings.activeGgufVariant, null);
+ assert.equal(settings.params.temperature, 0.4);
+ assert.equal(settings.permissionMode, "ask");
+ assert.equal(settings.toolsEnabled, true);
+ if (failed) {
+ w.handlePromptQueueRunFailed(undefined, true);
+ w.setModelLoading(false);
+ await w.dispatchQueuedPrompt(run, run.items[0]);
+ assert.equal(w.isPromptQueueRunReadyToDispatch(run), false);
+ assert.deepEqual(w.appended, []);
+ assert.equal(run.items[0].prompt, "wait for the selected model");
+ } else {
+ w.setModelLoading(false);
+ await w.dispatchQueuedPrompt(run, run.items[0]);
+ assert.deepEqual(w.appended, ["wait for the selected model"]);
+ }
+ });
+ }
+}
+
+test("an external-to-local preparation keeps the follow-up in the composer", async () => {
+ const lease = chatModelLifecycleGate.tryAcquire("preparing")!;
+ try {
+ const w = world();
+ const { target } = await targetForSelection(
+ "external::provider::hosted-model", true, "incoming-local",
+ );
+ let cleared = false;
+ hydratedFactory(w, target)(["keep this draft"], false, () => { cleared = true; });
+ await Promise.resolve();
+ assert.equal(cleared, false);
+ assert.equal(w.runs.size, 0);
+ } finally {
+ chatModelLifecycleGate.release(lease);
+ }
+});
+
+test("external queues retain their provider across unrelated local loading and failure", async () => {
+ const outgoing = "external::provider::hosted-model";
+ const before = await targetForSelection(outgoing, false, null);
+ const unrelated = await targetForSelection(outgoing, true, null);
+ const stalePick = await targetForSelection(outgoing, false, "old-local-pick");
+ const incoming = await targetForSelection(outgoing, true, "incoming-local");
+ assert.equal(incoming.target.usesLocalModel, true);
+ for (const { target, settings } of [before, unrelated, stalePick]) {
+ assert.equal(target.usesLocalModel, false);
+ assert.equal(settings.params.checkpoint, outgoing);
+ const w = world();
+ w.setModelLoading(true);
+ w.startPromptQueue(["hosted follow-up"], target);
+ w.handlePromptQueueRunFailed(undefined, true);
+ const run = w.run();
+ assert.equal(run.paused, false);
+ await w.dispatchQueuedPrompt(run, run.items[0]);
+ assert.deepEqual(w.appended, ["hosted follow-up"]);
+ }
+});
+
+for (const checkpoint of ["outgoing-local", ""]) {
+ test(`local loading still defers model resolution: checkpoint=${checkpoint || "empty"}`, async () => {
+ for (const pick of ["incoming-local", null]) {
+ const { target, settings } = await targetForSelection(checkpoint, true, pick);
+ assert.equal(target.usesLocalModel, true);
+ assert.equal(settings.params.checkpoint, "");
+ assert.equal(settings.activeGgufVariant, null);
+ }
+ const ready = await targetForSelection(checkpoint, false, null);
+ assert.equal(ready.settings.params.checkpoint, checkpoint);
+ assert.equal(ready.settings.activeGgufVariant, "old-Q4.gguf");
+ });
+}
+
+test("a model load starting during the document probe defers the pending append", async () => {
+ const w = world();
+ const target = makeTarget("chat", false);
+ w.startPromptQueue(["wait for model"], target);
+ let resolve!: (value: boolean) => void;
+ w.setIndexing(
+ () =>
+ new Promise((r) => {
+ resolve = r;
+ }),
+ );
+ const pending = w.dispatchQueuedPrompt(w.run(), w.run().items[0]);
+ w.setModelLoading(true);
+ resolve(false);
+ await pending;
+ assert.deepEqual(w.appended, []);
+ assert.equal(w.run().items[0].dispatched, false);
+ assert.equal(w.dispatchRetries(), 1);
+});
+
+for (const behavior of ["queue", "steer"] as const) {
+ test(`an explicit hosted selection during a local load retains its provider: ${behavior}`, async () => {
+ const w = world();
+ w.setModelLoading(true);
+ const selected = "external::new-provider::selected-model";
+ const { target, settings } = await targetForSelection(
+ selected, true, "incoming-local", true,
+ );
+ assert.equal(target.usesLocalModel, false);
+ assert.equal(settings.params.checkpoint, selected);
+ w.startPromptQueue(["use the selected provider"], target, false, behavior);
+ w.handlePromptQueueRunFailed(undefined, true);
+ const run = w.run();
+ await w.dispatchQueuedPrompt(run, run.items[run.index]);
+ assert.deepEqual(w.appended, ["use the selected provider"]);
+ });
+}
diff --git a/studio/frontend/tests/composer-submit-path.test.ts b/studio/frontend/tests/composer-submit-path.test.ts
new file mode 100644
index 00000000000..f6d488dd9a3
--- /dev/null
+++ b/studio/frontend/tests/composer-submit-path.test.ts
@@ -0,0 +1,170 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import ts from "typescript";
+import { readSrc } from "./helpers/kit.ts";
+import { composerSubmitIntent } from "../src/features/chat/utils/composer-preferences.ts";
+
+const text = readSrc("components/assistant-ui/thread.tsx");
+const source = ts.createSourceFile(
+ "thread.tsx",
+ text,
+ ts.ScriptTarget.Latest,
+ true,
+ ts.ScriptKind.TSX,
+);
+function lift(predicate: (node: ts.Node) => boolean) {
+ const matches: ts.Node[] = [];
+ function visit(node: ts.Node) {
+ if (predicate(node)) matches.push(node);
+ ts.forEachChild(node, visit);
+ }
+ visit(source);
+ assert.equal(matches.length, 1);
+ return ts.transpileModule(`return (${matches[0].getText(source)});`, {
+ compilerOptions: {
+ target: ts.ScriptTarget.ES2022,
+ module: ts.ModuleKind.None,
+ },
+ }).outputText;
+}
+const keyCallback = lift(
+ (n) =>
+ ts.isArrowFunction(n) &&
+ n
+ .getText(source)
+ .startsWith("(e: KeyboardEvent<HTMLTextAreaElement>) =>") &&
+ n.getText(source).includes("composerSubmitIntent"),
+);
+const releaseCallback = lift(
+ (n) =>
+ ts.isArrowFunction(n) &&
+ n.getText(source).startsWith("() =>") &&
+ n
+ .getText(source)
+ .includes("const behavior = pendingFollowUpBehaviorRef.current;"),
+);
+function createCallback(
+ code: string,
+ deps: Record<string, unknown>,
+): () => void {
+ return new Function(...Object.keys(deps), code)(...Object.values(deps));
+}
+
+test("the shipped main composer key handler protects IME and mention selection", () => {
+ let submits = 0;
+ let prevented = 0;
+ const composingRef = { current: false };
+ const skipEnterRef = { current: false };
+ const deps = {
+ composerSubmitIntent,
+ sendShortcut: "mod-enter",
+ submitOnEnter: true,
+ skipEnterRef,
+ composingRef,
+ justSentRef: undefined,
+ refreshStuckTimer: () => undefined,
+ setCompositionState: (value: boolean) => {
+ composingRef.current = value;
+ },
+ onSubmitKey: () => {
+ submits += 1;
+ },
+ };
+ const onKey = createCallback(keyCallback, deps) as unknown as (
+ event: Record<string, unknown>,
+ ) => void;
+ const event = {
+ key: "Enter",
+ metaKey: true,
+ ctrlKey: false,
+ shiftKey: false,
+ altKey: false,
+ keyCode: 13,
+ nativeEvent: { isComposing: false },
+ preventDefault: () => {
+ prevented += 1;
+ },
+ };
+ onKey({ ...event, nativeEvent: { isComposing: true } });
+ onKey(event); // Candidate-confirming Enter can arrive with native isComposing=false.
+ assert.equal(submits, 0);
+ composingRef.current = false;
+ skipEnterRef.current = true;
+ onKey(event);
+ assert.equal(submits, 0);
+ skipEnterRef.current = false;
+ onKey({ ...event, metaKey: false });
+ assert.equal(submits, 0);
+ onKey(event);
+ assert.equal(submits, 1);
+ assert.ok(prevented > 0);
+});
+
+for (const active of ["runtime", "pre-stream", "queue", "idle"]) {
+ test(`parked send retains the submitted follow-up choice with ${active} state at release`, () => {
+ const calls: unknown[] = [];
+ const pendingFollowUpBehaviorRef = { current: "steer" };
+ const pendingSendRef = { current: true };
+ const deps = {
+ pendingSend: true,
+ pendingSendRef,
+ pendingFollowUpBehaviorRef,
+ indexingActive: false,
+ threadScopedSettingsPending: false,
+ hasMaterializingImageAttachments: false,
+ hasMaterializingAudioAttachments: false,
+ hasMaterializingVideoAttachments: false,
+ aui: {
+ composer: () => ({
+ getState: () => ({ text: "Follow up", attachments: [] }),
+ }),
+ thread: () => ({
+ getState: () => ({ isRunning: active === "runtime" }),
+ }),
+ },
+ setPendingSend: () => undefined,
+ dismissWaitToast: () => undefined,
+ hasPreStreamRunReservation: () => active === "pre-stream",
+ preStreamThreadIds: ["own-chat"],
+ isResearchActive: false,
+ findPromptQueueEntry: () => active === "queue",
+ usePromptQueueUI: { getState: () => ({}) },
+ disableQueue: false,
+ canQueueCurrentPrompt: true,
+ queueComposerText: (wait: boolean, behavior: string) =>
+ calls.push([wait, behavior]),
+ canQueuePastedTextPrompt: false,
+ overlay: false,
+ hasAttachments: false,
+ hasPendingAudio: false,
+ clearStoredDraft: () => calls.push("clear"),
+ sendReservedComposer: () => calls.push("send"),
+ };
+ const release = createCallback(releaseCallback, deps);
+ release();
+ release(); // An old render cannot release a cancelled/consumed send twice.
+ assert.deepEqual(
+ calls,
+ active === "idle" ? ["clear", "send"] : [[active !== "queue", "steer"]],
+ );
+ assert.equal(pendingSendRef.current, false);
+ });
+}
+
+test("main, edit and comparison composers use the setting and expose settings access", () => {
+ assert.match(text, /submitMode="none"/);
+ assert.match(
+ text,
+ /submitMode=\{sendShortcut === "mod-enter" \? "ctrlEnter" : "enter"\}/,
+ );
+ assert.match(
+ text,
+ /onQueueClick=\{\(\) => formRef.current\?\.requestSubmit\(\)\}/,
+ );
+ assert.match(text, /scrollTarget: "chat-composer"/);
+ const compare = readSrc("features/chat/shared-composer.tsx");
+ assert.match(compare, /composerSubmitIntent\(e, sendShortcut\)/);
+ assert.match(compare, /scrollTarget: "chat-composer"/);
+ const page = readSrc("features/chat/chat-page.tsx");
+ assert.match(page, /showContextWindowUsage &&\s*view.mode === "single"/);
+});
diff --git a/studio/frontend/tests/context-window-visible.test.ts b/studio/frontend/tests/context-window-visible.test.ts
index e44d6e872ac..bf46a3d2f8f 100644
--- a/studio/frontend/tests/context-window-visible.test.ts
+++ b/studio/frontend/tests/context-window-visible.test.ts
@@ -149,7 +149,7 @@ test("the header renders the bar on the window alone, with usage optional", () =
const page = readSrc("features/chat/chat-page.tsx");
assert.match(
page,
- /view\.mode === "single" && \(contextUsage \|\| contextWindowKnown\)/,
+ /showContextWindowUsage &&\s*view\.mode === "single" &&\s*\(contextUsage \|\| contextWindowKnown\)/,
);
assert.match(page, /used=\{contextUsage\?\.totalTokens \?\? null\}/);
});
diff --git a/studio/frontend/tests/loading-model-selection.test.ts b/studio/frontend/tests/loading-model-selection.test.ts
new file mode 100644
index 00000000000..256d79f3fc3
--- /dev/null
+++ b/studio/frontend/tests/loading-model-selection.test.ts
@@ -0,0 +1,43 @@
+// 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 assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+import { installLocalStorageFake } from "./helpers/kit.ts";
+
+installLocalStorageFake().store.set(
+ "unsloth_chat_settings_imported_to_studio_db",
+ "true",
+);
+register("./store-settings-resolver.mjs", import.meta.url);
+const { useChatRuntimeStore: store } = await import(
+ "../src/features/chat/stores/chat-runtime-store.ts"
+);
+
+const pick = { id: "incoming-local", ggufVariant: null, nativePathToken: null };
+const previous = "external::provider-a::model-a";
+const selected = "external::provider-b::model-b";
+
+test("a later hosted selection supersedes the local load even after returning to the original provider", () => {
+ store.getState().setCheckpoint(previous);
+ store.getState().setLoadingModelPick(pick);
+ assert.equal(store.getState().loadingModelPick?.selectionSuperseded, false);
+ store.getState().setCheckpoint(selected);
+ assert.equal(store.getState().loadingModelPick?.selectionSuperseded, true);
+ store.getState().setCheckpoint(previous);
+ assert.equal(store.getState().loadingModelPick?.selectionSuperseded, true);
+ assert.equal(store.getState().loadingModelPick?.id, pick.id);
+ store.getState().clearLoadingModelPick(pick);
+ assert.equal(store.getState().loadingModelPick, null);
+});
+
+test("sampling changes and repeated checkpoint reconciliation keep the incoming load selected", () => {
+ store.getState().setCheckpoint(previous);
+ store.getState().setLoadingModelPick(pick);
+ store.getState().setParams({ ...store.getState().params, temperature: 0.4 });
+ store.getState().setCheckpoint(previous);
+ assert.equal(store.getState().loadingModelPick?.selectionSuperseded, false);
+ store.getState().setLoadingModelPick(null);
+ assert.equal(store.getState().loadingModelPick, null);
+});
diff --git a/studio/frontend/tests/model-lifecycle-gate.test.ts b/studio/frontend/tests/model-lifecycle-gate.test.ts
index c341cfd6cac..b95d4a47e07 100644
--- a/studio/frontend/tests/model-lifecycle-gate.test.ts
+++ b/studio/frontend/tests/model-lifecycle-gate.test.ts
@@ -20,3 +20,57 @@ test("the model lifecycle has one owner and ignores stale releases", () => {
assert.notEqual(second, null);
assert.notEqual(second, first);
});
+
+test("queue acceptance follows the owning lifecycle phase", () => {
+ for (const phase of ["preparing", "loading", "unloading"] as const) {
+ const gate = new ModelLifecycleGate();
+ assert.equal(gate.canQueue(), true);
+ const lease = gate.tryAcquire(phase)!;
+ assert.equal(gate.canQueue(), phase === "loading");
+ assert.equal(gate.tryAcquire("loading"), null);
+ assert.equal(gate.markLoading(lease + 1), false);
+ assert.equal(gate.canQueue(), phase === "loading");
+ assert.equal(gate.markLoading(lease), phase === "preparing");
+ assert.equal(gate.canQueue(), phase !== "unloading");
+ assert.equal(gate.release(lease), true);
+ assert.equal(gate.canQueue(), true);
+ const next = gate.tryAcquire("preparing")!;
+ assert.equal(gate.markLoading(lease), false);
+ assert.equal(gate.release(lease), false);
+ assert.equal(gate.canQueue(), false);
+ assert.equal(gate.release(next), true);
+ }
+});
+
+test("legacy lifecycle callers keep drafts blocked until release or an explicit loading boundary", () => {
+ const gate = new ModelLifecycleGate();
+ const lease = gate.tryAcquire()!;
+ assert.equal(gate.canQueue(), false);
+ assert.equal(gate.markLoading(lease + 1), false);
+ assert.equal(gate.canQueue(), false);
+ assert.equal(gate.markLoading(lease), true);
+ assert.equal(gate.canQueue(), true);
+ gate.release(lease);
+
+ const next = gate.tryAcquire()!;
+ assert.equal(gate.canQueue(), false);
+ assert.equal(gate.markLoading(lease), false);
+ assert.equal(gate.canQueue(), false);
+ gate.release(next);
+ assert.equal(gate.canQueue(), true);
+});
+
+test("failure blocks new drafts throughout rollback and rejects stale callbacks", () => {
+ const gate = new ModelLifecycleGate();
+ const lease = gate.tryAcquire("loading")!;
+ assert.equal(gate.markFailed(lease + 1), false);
+ assert.equal(gate.canQueue(), true);
+ assert.equal(gate.markFailed(lease), true);
+ assert.equal(gate.canQueue(), false);
+ assert.equal(gate.markFailed(lease), false);
+ gate.release(lease);
+ const next = gate.tryAcquire("loading")!;
+ assert.equal(gate.markFailed(lease), false);
+ assert.equal(gate.canQueue(), true);
+ gate.release(next);
+});
diff --git a/studio/frontend/tests/pre-stream-run-reservation.test.ts b/studio/frontend/tests/pre-stream-run-reservation.test.ts
index 5ba16fc4261..ea381807842 100644
--- a/studio/frontend/tests/pre-stream-run-reservation.test.ts
+++ b/studio/frontend/tests/pre-stream-run-reservation.test.ts
@@ -4,6 +4,7 @@ import test from "node:test";
import {
adoptPreStreamRunReservation,
cancelPreStreamRunReservations,
+ cancelPreStreamRunForThreadIds,
claimPreStreamRunReservation,
findPreStreamRunReservation,
hasPreStreamRunReservation,
@@ -104,10 +105,7 @@ test("local reservations can be snapshotted and cancelled before streaming", ()
});
assert.ok(local);
assert.ok(external);
- assert.equal(
- adoptPreStreamRunReservation(local, ["remote-thread"]),
- true,
- );
+ assert.equal(adoptPreStreamRunReservation(local, ["remote-thread"]), true);
assert.deepEqual(listLocalPreStreamRunReservations(), [
{ token: local, threadIds: ["local-thread", "remote-thread"] },
]);
@@ -134,3 +132,31 @@ test("cancelling an unclaimed reservation releases it immediately", () => {
assert.equal(isPreStreamRunReservationCancelled(token), false);
assert.equal(releasePreStreamRunReservation(token), false);
});
+
+for (const usesLocalModel of [true, false]) {
+ test(`steering cancels only its own ${usesLocalModel ? "local" : "external"} pre-stream reservation`, () => {
+ let cancels = 0;
+ const own = reservePreStreamRun(["steer-local", "steer-remote"], {
+ usesLocalModel,
+ cancel: () => {
+ cancels += 1;
+ },
+ })!;
+ const sibling = reservePreStreamRun(["steer-sibling"])!;
+ const unresolved = reservePreStreamRun([])!;
+ claimPreStreamRunReservation(own);
+ if (!usesLocalModel) assert.equal(cancelPreStreamRunReservations([own]), 0);
+ assert.equal(cancelPreStreamRunForThreadIds([]), false);
+ assert.equal(cancelPreStreamRunForThreadIds(["steer-remote"]), true);
+ assert.equal(cancels, 1);
+ assert.equal(isPreStreamRunReservationCancelled(own), true);
+ assert.equal(hasPreStreamRunReservation(["steer-local"]), false);
+ assert.equal(hasPreStreamRunReservation(["steer-sibling"]), true);
+ assert.equal(hasPreStreamRunReservation([]), true);
+ const replacement = reservePreStreamRun(["steer-local"])!;
+ releasePreStreamRunReservation(own);
+ assert.equal(findPreStreamRunReservation(["steer-local"]), replacement);
+ for (const token of [sibling, unresolved, replacement])
+ releasePreStreamRunReservation(token);
+ });
+}
diff --git a/studio/frontend/tests/prompt-queue-model-boundary.test.ts b/studio/frontend/tests/prompt-queue-model-boundary.test.ts
index be3d19ea50e..5af3923a4c9 100644
--- a/studio/frontend/tests/prompt-queue-model-boundary.test.ts
+++ b/studio/frontend/tests/prompt-queue-model-boundary.test.ts
@@ -91,7 +91,6 @@ test("a local model boundary invalidates only pending local factories", () => {
shouldAbortPendingQueueForModelBoundary({
capturedGeneration,
usesLocalModel: true,
- modelLoading: false,
}),
true,
);
@@ -99,20 +98,18 @@ test("a local model boundary invalidates only pending local factories", () => {
shouldAbortPendingQueueForModelBoundary({
capturedGeneration,
usesLocalModel: false,
- modelLoading: false,
}),
false,
);
});
-test("a pending local factory cannot materialize during a model load", () => {
+test("a new local factory is accepted within the current model boundary", () => {
assert.equal(
shouldAbortPendingQueueForModelBoundary({
capturedGeneration: localPromptQueueModelBoundary.capture(),
usesLocalModel: true,
- modelLoading: true,
}),
- true,
+ false,
);
});
diff --git a/studio/frontend/tests/queued-model-lifecycle.test.ts b/studio/frontend/tests/queued-model-lifecycle.test.ts
new file mode 100644
index 00000000000..aa26464024f
--- /dev/null
+++ b/studio/frontend/tests/queued-model-lifecycle.test.ts
@@ -0,0 +1,72 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import ts from "typescript";
+import { readSrc } from "./helpers/kit.ts";
+import {
+ ModelLifecycleGate,
+ type ModelLifecyclePhase,
+} from "../src/features/chat/utils/model-lifecycle-gate.ts";
+
+const source = ts.createSourceFile(
+ "chat-adapter.ts",
+ readSrc("features/chat/api/chat-adapter.ts"),
+ ts.ScriptTarget.Latest,
+ true,
+);
+const loader = source.statements.find(
+ (node) => ts.isFunctionDeclaration(node) && node.name?.text === "resolveQueuedEmptyLocalModel",
+);
+assert.ok(loader);
+const js = ts.transpileModule(
+ `${loader.getText(source)}\nreturn resolveQueuedEmptyLocalModel;`,
+ { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.None } },
+).outputText;
+
+for (const busy of [false, true]) {
+ test(`chat auto-load admits follow-ups while waiting for the model, busy=${busy}`, async () => {
+ const gate = new ModelLifecycleGate();
+ const previous = busy ? gate.tryAcquire("preparing") : null;
+ const leases: number[] = [];
+ let finish!: (result: { loaded: boolean; blockedByTrustRemoteCode: boolean }) => void;
+ const loading = new Promise<{ loaded: boolean; blockedByTrustRemoteCode: boolean }>(
+ (resolve) => { finish = resolve; },
+ );
+ const deps = {
+ useChatRuntimeStore: {
+ getState: () => ({
+ params: { checkpoint: "" },
+ beginModelLoading: (phase?: ModelLifecyclePhase) => {
+ const lease = gate.tryAcquire(phase);
+ if (lease !== null) leases.push(lease);
+ return lease;
+ },
+ endModelLoading: (lease: number) => gate.release(lease),
+ }),
+ },
+ waitForModelReady: async () => {
+ assert.notEqual(previous, null);
+ gate.release(previous!);
+ },
+ isExternalModelId: () => false,
+ autoLoadSmallestModel: () => loading,
+ queuedResolvedModelFromStore: () => null,
+ };
+ const load = new Function(...Object.keys(deps), js)(...Object.values(deps)) as (
+ signal: AbortSignal,
+ ) => Promise<{ loaded: boolean }>;
+ const result = load(new AbortController().signal);
+ await Promise.resolve();
+ try {
+ assert.equal(leases.length, 1);
+ assert.equal(gate.tryAcquire(), null, "the load must still own the lifecycle");
+ assert.equal(gate.canQueue(), true, "follow-ups remain available during chat auto-load");
+ } finally {
+ finish({ loaded: true, blockedByTrustRemoteCode: false });
+ await result;
+ }
+ assert.equal(gate.canQueue(), true);
+ const next = gate.tryAcquire("unloading");
+ assert.notEqual(next, null, "the load releases its lifecycle");
+ gate.release(next!);
+ });
+}
diff --git a/tests/python/test_installer_differential_comparer.py b/tests/python/test_installer_differential_comparer.py
index 76934159d1f..f8827cb7104 100644
--- a/tests/python/test_installer_differential_comparer.py
+++ b/tests/python/test_installer_differential_comparer.py
@@ -1678,11 +1678,11 @@ def test_no_rev_parse_fallback_can_echo_its_argument() -> None:
`--verify --quiet` prints nothing on failure, so every rev-parse that has a fallback uses it.
"""
- body = (
- REPO / ".github" / "workflows" / "windows-installer-differential-ci.yml"
- ).read_text(encoding = "utf-8")
- step = body[body.index("name: Pick the two commits"):]
- step = step[:step.index("- name:", 10)]
+ body = (REPO / ".github" / "workflows" / "windows-installer-differential-ci.yml").read_text(
+ encoding = "utf-8"
+ )
+ step = body[body.index("name: Pick the two commits") :]
+ step = step[: step.index("- name:", 10)]
for line in step.splitlines():
if "rev-parse" not in line or "||" not in line:
continue
diff --git a/tests/studio/_prompt_queue_edge_cases.py b/tests/studio/_prompt_queue_edge_cases.py
new file mode 100644
index 00000000000..908bfac3619
--- /dev/null
+++ b/tests/studio/_prompt_queue_edge_cases.py
@@ -0,0 +1,191 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""Additional queue gesture and input regressions, shared by browser engines."""
+
+import re
+import json
+import time
+from playwright.sync_api import expect
+
+
+def check_edge_cases(page):
+ rows = page.locator("[data-queue-item-id]")
+ attempts = page.get_by_label("Move attempts", exact = True)
+
+ def reset():
+ page.get_by_role("button", name = "Reset fixture", exact = True).click()
+ expect(rows).to_have_count(3)
+ expect(rows.first).to_have_attribute("data-queue-item-id", "q0")
+ expect(attempts).to_have_text("0")
+ rows.evaluate_all(
+ "rows => Promise.all(rows.flatMap(row => row.getAnimations()).map(a => a.finished.catch(() => {})))"
+ )
+
+ def grab():
+ handle = rows.first.get_by_role("button", name = re.compile("^Reorder"))
+ box = handle.bounding_box()
+ x, y = box["x"] + box["width"] / 2, box["y"] + box["height"] / 2
+ page.mouse.move(x, y)
+ page.mouse.down()
+ page.mouse.move(x, y + 60, steps = 6)
+ expect(rows.first).to_have_attribute("data-queue-dragging", "true")
+ return handle
+
+ for cancel in ("blur", "resize", "lostcapture", "lock", "remove"):
+ reset()
+ handle = grab()
+ if cancel in ("blur", "resize"):
+ page.evaluate("name => window.dispatchEvent(new Event(name))", cancel)
+ elif cancel == "lostcapture":
+ handle.dispatch_event("lostpointercapture")
+ else:
+ name = "Lock prompts" if cancel == "lock" else "Dispatch first"
+ page.get_by_role("button", name = name, exact = True).evaluate("el => el.click()")
+ page.mouse.up()
+ expect(page.locator('[data-queue-dragging="true"]')).to_have_count(0)
+ expect(attempts).to_have_text("0")
+ assert rows.evaluate_all("rows => rows.every(row => !row.style.transform)")
+
+ # A short click and a secondary pointer must not reorder anything.
+ reset()
+ handle = rows.first.get_by_role("button", name = re.compile("^Reorder"))
+ handle.click()
+ handle.click(button = "right")
+ handle.dispatch_event("pointerdown", {"pointerId": 99, "isPrimary": False, "button": 0})
+ expect(attempts).to_have_text("0")
+ expect(page.locator('[data-queue-dragging="true"]')).to_have_count(0)
+
+ # Mixed keyboard and pointer input commits at most one move.
+ reset()
+ grab()
+ page.keyboard.press("End")
+ page.mouse.up()
+ expect(attempts).to_have_text("1")
+ expect(rows.last).to_have_attribute("data-queue-item-id", "q0")
+
+ # Some IMEs report legacy keyCode 229 after isComposing becomes false.
+ reset()
+ rows.first.get_by_role("button", name = re.compile("^More options")).click()
+ page.get_by_role("menuitem", name = "Edit message", exact = True).click()
+ editor = page.get_by_role("textbox", name = "Edit queued prompt 1", exact = True)
+ editor.fill("日本語の下書き")
+ editor.dispatch_event("keydown", {"key": "Enter", "ctrlKey": True, "keyCode": 229})
+ expect(editor).to_be_visible()
+ expect(editor).to_have_value("日本語の下書き")
+ editor.press("Escape")
+ expect(rows.first).to_contain_text("First prompt")
+
+ for direction in ("ltr", "rtl"):
+ for width, zoom in ((320, 1), (768, 0.8), (768, 1.25), (1440, 2)):
+ print(f"LAYOUT: direction={direction}, width={width}, zoom={zoom}", flush = True)
+ page.set_viewport_size({"width": width, "height": 1000})
+ page.evaluate(
+ "([dir, zoom]) => { document.documentElement.dir = dir; document.body.style.zoom = zoom; }",
+ [direction, zoom],
+ )
+ reset()
+ first = rows.first
+ handle = first.get_by_role("button", name = re.compile("^Reorder"))
+ box = handle.bounding_box()
+ before = first.bounding_box()["y"]
+ x, y = box["x"] + box["width"] / 2, box["y"] + box["height"] / 2
+ page.mouse.move(x, y)
+ page.mouse.down()
+ page.mouse.move(x, y + 14, steps = 4)
+ expect(first).to_have_attribute("data-queue-dragging", "true")
+ page.evaluate(
+ "() => new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)))"
+ )
+ displacement = first.bounding_box()["y"] - before
+ assert abs(displacement - 14) < 1, (direction, zoom, displacement)
+ target = rows.last.bounding_box()
+ page.mouse.move(x, target["y"] + target["height"] / 2, steps = 6)
+ expect(attempts).to_have_text("0")
+ page.mouse.up()
+ expect(attempts).to_have_text("1")
+ expect(rows.last).to_have_attribute("data-queue-item-id", "q0")
+ rows.evaluate_all(
+ "rows => Promise.all(rows.flatMap(row => row.getAnimations()).map(a => a.finished.catch(() => {})))"
+ )
+ assert abs(rows.last.bounding_box()["y"] - target["y"]) < 1
+ reset()
+ last = rows.last.get_by_role("button", name = re.compile("^Reorder"))
+ last.focus()
+ last.press("Home")
+ expect(rows.first).to_have_attribute("data-queue-item-id", "q2")
+ assert page.evaluate("document.documentElement.scrollWidth <= innerWidth"), (
+ direction,
+ width,
+ zoom,
+ )
+ rows.first.get_by_role("button", name = re.compile("^More options")).click()
+ expect(page.get_by_role("menu")).to_be_visible()
+ page.keyboard.press("Escape")
+ page.evaluate("document.documentElement.dir = 'ltr'; document.body.style.zoom = ''")
+ page.set_viewport_size({"width": 1100, "height": 800})
+ print(
+ "PASS: lifecycle cancellation, mixed inputs, IME, RTL, zoom and responsive queue layouts",
+ flush = True,
+ )
+
+
+def check_performance(browser, url):
+ for size in (3, 25, 100, 500):
+ page = browser.new_page(viewport = {"width": 1100, "height": 850})
+ try:
+ errors = []
+ page.on("pageerror", lambda error: errors.append(str(error)))
+ started = time.monotonic()
+ page.goto(f"{url}?size={size}")
+ rows = page.locator("[data-queue-item-id]")
+ # Cold Vite imports are outside the drag frame measurement.
+ expect(rows).to_have_count(size, timeout = 30000)
+ print(
+ f"MOUNT: rows={size}, cold_page_ms={round((time.monotonic() - started) * 1000)}",
+ flush = True,
+ )
+ handle = rows.first.get_by_role("button", name = re.compile("^Reorder"))
+ box = handle.bounding_box()
+ x, y = box["x"] + box["width"] / 2, box["y"] + box["height"] / 2
+ page.mouse.move(x, y)
+ page.mouse.down()
+ page.mouse.move(x, y + 60, steps = 6)
+ expect(rows.first).to_have_attribute("data-queue-dragging", "true")
+ frames = page.evaluate("""() => new Promise(resolve => {
+ const deltas = []; let previous;
+ const sample = time => {
+ if (previous !== undefined) deltas.push(time - previous);
+ previous = time;
+ if (deltas.length === 60) resolve(deltas);
+ else requestAnimationFrame(sample);
+ };
+ requestAnimationFrame(sample);
+ })""")
+ page.mouse.up()
+ expect(page.get_by_label("Move attempts", exact = True)).to_have_text("1")
+ rows.evaluate_all(
+ "rows => Promise.all(rows.flatMap(row => row.getAnimations()).map(a => a.finished.catch(() => {})))"
+ )
+ idle_mutations = page.evaluate("""() => new Promise(resolve => {
+ let count = 0;
+ const observer = new MutationObserver(records => {
+ count += records.filter(r => r.target.matches('[data-queue-item-id]') && r.attributeName === 'style').length;
+ });
+ observer.observe(document.querySelector('[aria-label="Queued prompts"]'), {subtree:true, attributes:true});
+ setTimeout(() => { observer.disconnect(); resolve(count); }, 300);
+ })""")
+ assert idle_mutations == 0, "idle queue continues updating row styles"
+ assert rows.evaluate_all("rows => rows.every(row => !row.style.transform)")
+ ordered = sorted(frames)
+ metrics = {
+ "rows": size,
+ "p95_frame_ms": round(ordered[int(len(ordered) * 0.95) - 1], 2),
+ "max_frame_ms": round(max(frames), 2),
+ "idle_style_updates": idle_mutations,
+ }
+ print("PERF: " + json.dumps(metrics), flush = True)
+ assert metrics["p95_frame_ms"] < 250, "drag stalls for more than 250ms per frame"
+ assert not errors, errors
+ finally:
+ page.close()
diff --git a/tests/studio/playwright_composer_settings.py b/tests/studio/playwright_composer_settings.py
new file mode 100644
index 00000000000..f79b6825d8f
--- /dev/null
+++ b/tests/studio/playwright_composer_settings.py
@@ -0,0 +1,159 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Production settings/preview and assistant-ui input smoke test; no inference required.
+Run: python tests/studio/playwright_composer_settings.py
+PW_ENGINE=webkit selects WebKit. PW_OUTPUT optionally saves screenshots.
+"""
+
+import json
+import os
+import re
+from pathlib import Path
+from playwright.sync_api import expect, sync_playwright
+from _playwright_robust import start_vite, stop_process, wait_for_smoke_page
+
+PAGE = "/smoke-composer-settings.html"
+ENTRY = "/smoke-composer-settings-main.tsx"
+
+
+def check_settings(page):
+ plain = page.get_by_role("switch", name = "Plain text composer", exact = True)
+ context = page.get_by_role("switch", name = "Show context window usage", exact = True)
+ select = page.get_by_role("combobox", name = "Send shortcut", exact = True)
+ editor = page.get_by_role("textbox", name = "Message", exact = True)
+ preview = page.get_by_role("region", name = "Formatted preview", exact = True)
+ submitted = page.get_by_label("Submitted messages")
+ expect(plain).to_be_checked()
+ expect(context).to_be_checked()
+ expect(page.get_by_role("button", name = "Queue", exact = True)).to_have_attribute(
+ "aria-pressed", "true"
+ )
+ editor.fill("**Keep this literal**")
+ expect(preview).to_have_count(0)
+ plain.click()
+ expect(preview.locator('[data-streamdown="strong"]')).to_have_text("Keep this literal")
+ expect(editor).to_have_value("**Keep this literal**")
+ requested = []
+ page.on(
+ "request",
+ lambda req: requested.append(req.url) if "draft-only.invalid" in req.url else None,
+ )
+ editor.fill(
+ "![private](https://draft-only.invalid/image.png)\n\n[private link](https://draft-only.invalid/)\n\n<script>alert(1)</script>"
+ )
+ expect(preview).to_contain_text("private link")
+ expect(preview.locator("img, a, script")).to_have_count(0)
+ assert not requested, requested
+ context.click()
+ page.get_by_role("button", name = "Steer", exact = True).click()
+ select.click()
+ option = page.get_by_role("option", name = re.compile(r"^(⌘|Ctrl\+)Enter$"))
+ modified_label = option.inner_text()
+ option.click()
+ editor.fill("First line")
+ editor.press("End")
+ editor.press("Enter")
+ editor.type("Second line")
+ expect(editor).to_have_value("First line\nSecond line")
+ expect(submitted).to_have_text("[]")
+ editor.press("Meta+Enter")
+ expect(editor).to_have_value("")
+ assert json.loads(submitted.text_content()) == [
+ {"text": "First line\nSecond line", "behavior": "steer"}
+ ]
+ editor.fill("Queue this once")
+ editor.press("Meta+Shift+Enter")
+ assert json.loads(submitted.text_content())[-1]["behavior"] == "queue"
+ page.reload()
+ expect(plain).not_to_be_checked()
+ expect(context).not_to_be_checked()
+ expect(select).to_contain_text(modified_label)
+ expect(page.get_by_role("button", name = "Steer", exact = True)).to_have_attribute(
+ "aria-pressed", "true"
+ )
+ select.click()
+ page.get_by_role("option", name = "Enter", exact = True).click()
+ editor.fill("Line one")
+ editor.press("End")
+ editor.press("Shift+Enter")
+ editor.type("Line two")
+ expect(editor).to_have_value("Line one\nLine two")
+ editor.press("Enter")
+ assert json.loads(submitted.text_content())[-1]["behavior"] == "steer"
+ editor.fill("Queue override")
+ editor.press("Control+Enter")
+ assert json.loads(submitted.text_content())[-1]["behavior"] == "queue"
+ editor.fill("Compose without sending")
+ editor.dispatch_event(
+ "keydown", {"key": "Enter", "code": "Enter", "isComposing": True, "keyCode": 229}
+ )
+ expect(editor).to_have_value("Compose without sending")
+ editor.fill(
+ "**Review the training results**\n\n- Compare accuracy and speed\n- Summarize the next steps"
+ )
+ expect(preview.locator('[data-streamdown="strong"]')).to_have_text(
+ "Review the training results"
+ )
+ expect(preview.locator("li")).to_have_count(2)
+ editor.blur()
+ output = os.environ.get("PW_OUTPUT")
+ if output:
+ dest = Path(output)
+ dest.mkdir(parents = True, exist_ok = True)
+ page.screenshot(path = str(dest / "composer-settings-light.png"), full_page = True)
+ page.evaluate("document.documentElement.classList.add('dark')")
+ page.wait_for_timeout(250) # Let the existing theme color transitions settle.
+ page.screenshot(path = str(dest / "composer-settings-dark.png"), full_page = True)
+ page.set_viewport_size({"width": 320, "height": 812})
+ expect(plain).to_be_visible()
+ assert page.evaluate(
+ "document.documentElement.scrollWidth <= innerWidth"
+ ), "mobile horizontal overflow"
+ if output:
+ page.screenshot(path = str(Path(output) / "composer-settings-mobile.png"), full_page = True)
+ print(
+ "PASS: settings, persistence, preview, raw draft, shortcuts, override, IME and 320px layout",
+ flush = True,
+ )
+
+
+def main():
+ server = None
+ try:
+ base = os.environ.get("BASE_URL")
+ if not base:
+ port = int(os.environ.get("PW_PORT", "5422"))
+ server = start_vite(port)
+ base = f"http://127.0.0.1:{port}"
+ wait_for_smoke_page(base + PAGE, ENTRY, proc = server)
+ with sync_playwright() as pw:
+ options = {"headless": True}
+ if os.environ.get("PW_EXECUTABLE"):
+ options["executable_path"] = os.environ["PW_EXECUTABLE"]
+ if os.environ.get("PW_CHANNEL"):
+ options["channel"] = os.environ["PW_CHANNEL"]
+ browser = getattr(pw, os.environ.get("PW_ENGINE", "chromium")).launch(**options)
+ print(
+ f"Browser: {os.environ.get('PW_CHANNEL', os.environ.get('PW_ENGINE', 'chromium'))} {browser.version}",
+ flush = True,
+ )
+ try:
+ page = browser.new_page(viewport = {"width": 1100, "height": 850})
+ errors = []
+ page.on("pageerror", lambda error: errors.append(str(error)))
+ page.goto(base + PAGE)
+ page.get_by_role("switch", name = "Plain text composer", exact = True).wait_for(
+ state = "visible", timeout = 60_000
+ )
+ check_settings(page)
+ assert not errors, errors
+ finally:
+ browser.close()
+ finally:
+ if server:
+ stop_process(server)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/studio/playwright_prompt_queue_actions.py b/tests/studio/playwright_prompt_queue_actions.py
new file mode 100644
index 00000000000..885b3ef1e4d
--- /dev/null
+++ b/tests/studio/playwright_prompt_queue_actions.py
@@ -0,0 +1,421 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Exercise the real queue view: menus, editing, ordering, drag, touch and file drops.
+
+Run after npm ci and Playwright browser installation:
+ python tests/studio/playwright_prompt_queue_actions.py
+PW_ENGINE=webkit selects WebKit. No backend or inference is required.
+"""
+
+import os
+import re
+from playwright.sync_api import expect, sync_playwright
+from _playwright_robust import start_vite, stop_process, wait_for_smoke_page
+
+PAGE = "/smoke-prompt-queue-actions.html"
+ENTRY = "/smoke-prompt-queue-actions-main.tsx"
+
+
+def check_form_actions(page):
+ controls = [
+ ("Reorder queued prompt 1 of 3", False),
+ ("Steer with queued prompt 1", False),
+ ("Remove queued prompt 1", False),
+ ("More options for queued prompt 1", False),
+ ("Steer with queued prompt 1", True),
+ ]
+ for name, reject in controls:
+ for keyboard in (False, True):
+ page.get_by_role("button", name = "Reset fixture", exact = True).click()
+ if reject:
+ page.get_by_role("button", name = "Simulate dispatch race", exact = True).click()
+ button = page.get_by_role("button", name = name, exact = True)
+ if keyboard:
+ button.focus()
+ button.press("Enter")
+ else:
+ button.click()
+ expect(page.get_by_label("Composer submissions", exact = True)).to_have_text("0")
+ expect(page.get_by_role("textbox", name = "Composer draft", exact = True)).to_have_value(
+ "Unsent composer draft"
+ )
+ page.keyboard.press("Escape")
+ print("PASS: queue controls preserve the unsent composer draft without submitting", flush = True)
+
+
+def check_actions(page):
+ rows = page.locator("[data-queue-item-id]")
+
+ def order(ids):
+ expect(rows).to_have_count(len(ids))
+ page.wait_for_function(
+ "ids => JSON.stringify([...document.querySelectorAll('[data-queue-item-id]')].map(e => e.dataset.queueItemId)) === JSON.stringify(ids)",
+ arg = ids,
+ )
+
+ def menu(position):
+ expect(page.get_by_role("menu")).to_have_count(0)
+ page.get_by_role(
+ "button", name = f"More options for queued prompt {position}", exact = True
+ ).click()
+ expect(page.get_by_role("menu")).to_be_visible()
+
+ def action(name):
+ page.get_by_role("menuitem", name = name, exact = True).click()
+ expect(page.get_by_role("menu")).to_have_count(0)
+
+ order(["q0", "q1", "q2"])
+ behavior = page.get_by_label("Follow-up behavior", exact = True)
+ expect(behavior).to_have_text("queue")
+ expect(page.get_by_role("button", name = re.compile(r"^Steer with queued prompt"))).to_have_count(
+ 3
+ )
+ menu(3)
+ expect(page.get_by_role("menuitem")).to_have_text(
+ ["Edit message", "Copy message", "Turn off queueing"]
+ )
+ expect(page.get_by_role("menuitem", name = re.compile(r"^Move"))).to_have_count(0)
+ page.keyboard.press("Escape")
+
+ menu(1)
+ action("Turn off queueing")
+ expect(behavior).to_have_text("steer")
+ order(["q0", "q1", "q2"])
+ expect(page.get_by_text("Paused", exact = True)).to_have_count(0)
+ expect(page.get_by_label("Steered prompt", exact = True)).to_be_empty()
+ page.reload()
+ expect(behavior).to_have_text("steer")
+ menu(2)
+ action("Turn on queueing")
+ expect(behavior).to_have_text("queue")
+ order(["q0", "q1", "q2"])
+ expect(page.get_by_text("Paused", exact = True)).to_have_count(0)
+ expect(page.get_by_label("Steered prompt", exact = True)).to_be_empty()
+
+ menu(2)
+ action("Edit message")
+ editor = page.get_by_role("textbox", name = "Edit queued prompt 2", exact = True)
+ expect(editor).to_be_focused()
+ editor.fill(" ")
+ expect(page.get_by_role("button", name = "Save", exact = True)).to_be_disabled()
+ editor.fill("Changed second prompt\nWith another line")
+ editor.press("Control+Enter")
+ expect(rows.nth(1)).to_contain_text("Changed second prompt")
+ edit_button = page.get_by_role("button", name = "More options for queued prompt 2", exact = True)
+ expect(edit_button).to_be_focused()
+ edit_button.click()
+ action("Edit message")
+ editor.fill("Discard this edit")
+ editor.press("Escape")
+ expect(rows.nth(1)).to_contain_text("Changed second prompt")
+ expect(edit_button).to_be_focused()
+
+ handle = page.get_by_role("button", name = "Reorder queued prompt 3 of 3", exact = True)
+ handle.focus()
+ page.keyboard.press("Home")
+ order(["q2", "q0", "q1"])
+ page.keyboard.press("ArrowDown")
+ order(["q0", "q2", "q1"])
+ page.keyboard.press("End")
+ order(["q0", "q1", "q2"])
+ source = handle.bounding_box()
+ target = rows.first.bounding_box()
+ page.mouse.move(source["x"] + source["width"] / 2, source["y"] + source["height"] / 2)
+ page.mouse.down()
+ page.mouse.move(target["x"] + target["width"] / 2, target["y"] + target["height"] / 2, steps = 5)
+ page.keyboard.press("Escape")
+ page.mouse.up()
+ order(["q0", "q1", "q2"])
+ handle.drag_to(rows.first)
+ order(["q2", "q0", "q1"])
+ expect(rows.first).not_to_have_class(re.compile(r"opacity-40"))
+
+ # Dragging a file must remain available to the outer attachment dropzone.
+ assert rows.first.evaluate("""row => {
+ const transfer = new DataTransfer();
+ transfer.items.add(new File(['file'], 'example.txt', {type:'text/plain'}));
+ const event = new DragEvent('dragover', {bubbles:true, cancelable:true, dataTransfer:transfer});
+ row.dispatchEvent(event);
+ return !event.defaultPrevented;
+ }""")
+
+ page.get_by_role("button", name = "Simulate paused queue", exact = True).click()
+ expect(page.get_by_text("Paused", exact = True)).to_be_visible()
+ menu(1)
+ action("Turn off queueing")
+ expect(behavior).to_have_text("steer")
+ expect(page.get_by_text("Paused", exact = True)).to_be_visible()
+ order(["q2", "q0", "q1"])
+ menu(1)
+ action("Resume queue")
+ expect(page.get_by_text("Paused", exact = True)).to_have_count(0)
+ expect(behavior).to_have_text("steer")
+ page.get_by_role("button", name = "Simulate dispatch race").click()
+ page.get_by_role("button", name = "Reorder queued prompt 3 of 3", exact = True).focus()
+ page.keyboard.press("Home")
+ order(["q2", "q0", "q1"])
+ expect(page.get_by_role("status").filter(has_text = "queue changed")).to_be_attached()
+ page.get_by_role("button", name = "Steer with queued prompt 3", exact = True).click()
+ order(["q2", "q0", "q1"])
+ expect(page.get_by_role("status").filter(has_text = "could not steer")).to_be_attached()
+ page.get_by_role("button", name = "Remove queued prompt 2", exact = True).click()
+ order(["q2", "q1"])
+ page.get_by_role("button", name = "Remove queued prompt 2", exact = True).click()
+ order(["q2"])
+ expect(
+ page.get_by_role("button", name = "Reorder queued prompt 1 of 1", exact = True)
+ ).to_be_disabled()
+ menu(1)
+ expect(page.get_by_role("menuitem", name = re.compile(r"^Move"))).to_have_count(0)
+ page.keyboard.press("Escape")
+ expect(
+ page.get_by_role("button", name = "More options for queued prompt 1", exact = True)
+ ).to_be_focused()
+ page.get_by_role("button", name = "Reset fixture", exact = True).click()
+ page.get_by_role("button", name = "Simulate paused queue", exact = True).click()
+ page.get_by_role("button", name = "Steer with queued prompt 2", exact = True).click()
+ order(["q0", "q2"])
+ expect(page.get_by_label("Steered prompt", exact = True)).to_have_text("Second prompt")
+ expect(page.get_by_text("Paused", exact = True)).to_have_count(0)
+ page.get_by_role("button", name = "Lock prompts", exact = True).click()
+ expect(
+ page.get_by_role("button", name = "Steer with queued prompt 1", exact = True)
+ ).to_be_disabled()
+ expect(
+ page.get_by_role("button", name = "Steer with queued prompt 2", exact = True)
+ ).to_be_disabled()
+ print(
+ "PASS: compact menu, persistent queueing preference, steer, edit, keyboard, mouse drag, file drop, resume, races and locked states",
+ flush = True,
+ )
+
+
+def check_motion(page, reduced = False):
+ rows = page.locator("[data-queue-item-id]")
+ queue = page.locator('[aria-label^="Prompt queue,"]')
+ attempts = page.get_by_label("Move attempts", exact = True)
+
+ def reset():
+ page.get_by_role("button", name = "Reset fixture", exact = True).click()
+ expect(rows).to_have_count(3)
+
+ def row(item):
+ return page.locator(f'[data-queue-item-id="{item}"]')
+
+ def order(ids):
+ assert rows.evaluate_all("rows => rows.map(row => row.dataset.queueItemId)") == ids
+
+ def settle():
+ rows.evaluate_all(
+ "rows => Promise.all(rows.flatMap(row => row.getAnimations()).map(animation => animation.finished.catch(() => {})))"
+ )
+
+ def grab(item):
+ handle = row(item).get_by_role("button", name = re.compile("^Reorder queued prompt"))
+ box = handle.bounding_box()
+ point = (box["x"] + box["width"] / 2, box["y"] + box["height"] / 2)
+ page.mouse.move(*point)
+ page.mouse.down()
+ return point
+
+ reset()
+ first = row("q0").bounding_box()
+ third = row("q2").bounding_box()
+ x, y = grab("q2")
+ page.mouse.move(x, y - 14, steps = 3)
+ expect(row("q2")).to_have_attribute("data-queue-dragging", "true")
+ page.wait_for_function(
+ "top => Math.abs(document.querySelector('[data-queue-item-id=\"q2\"]').getBoundingClientRect().top - top) < 1",
+ arg = third["y"] - 14,
+ )
+ order(["q0", "q1", "q2"])
+ expect(attempts).to_have_text("0")
+
+ page.mouse.move(x, first["y"] + first["height"] / 2 + 8, steps = 8)
+ page.wait_for_function(
+ "top => Math.abs(document.querySelector('[data-queue-item-id=\"q0\"]').getBoundingClientRect().top - top) < 1",
+ arg = first["y"] + third["height"],
+ )
+ if reduced:
+ assert row("q0").evaluate("row => row.style.transition") == "none"
+ order(["q0", "q1", "q2"])
+ expect(attempts).to_have_text("0")
+ page.mouse.up()
+ expect(attempts).to_have_text("1")
+ order(["q2", "q0", "q1"])
+ if reduced:
+ assert rows.evaluate_all(
+ "rows => rows.every(row => row.getAnimations().every(animation => animation.effect.getKeyframes().every(frame => frame.transform === undefined)))"
+ )
+ settle()
+ assert abs(row("q2").bounding_box()["y"] - first["y"]) < 1
+ expect(page.locator('[data-queue-dragging="true"]')).to_have_count(0)
+
+ if reduced:
+ print("PASS: reduced motion keeps direct dragging without settling animations", flush = True)
+ return
+
+ # Cancelled gestures never reach the queue engine.
+ for cancel in ("escape", "outside", "pointercancel"):
+ reset()
+ target = row("q2").bounding_box()
+ x, y = grab("q0")
+ page.mouse.move(x, target["y"] + target["height"] / 2, steps = 6)
+ expect(row("q0")).to_have_attribute("data-queue-dragging", "true")
+ if cancel == "escape":
+ page.keyboard.press("Escape")
+ elif cancel == "outside":
+ page.mouse.move(queue.bounding_box()["x"] - 30, y)
+ else:
+ row("q0").get_by_role(
+ "button", name = re.compile("^Reorder queued prompt")
+ ).dispatch_event("pointercancel")
+ page.mouse.up()
+ settle()
+ order(["q0", "q1", "q2"])
+ expect(attempts).to_have_text("0")
+ expect(page.locator('[data-queue-dragging="true"]')).to_have_count(0)
+
+ reset()
+ page.get_by_role("button", name = "Simulate dispatch race", exact = True).click()
+ target = row("q0").bounding_box()
+ x, y = grab("q2")
+ page.mouse.move(x, target["y"] + target["height"] / 2, steps = 6)
+ page.mouse.up()
+ expect(attempts).to_have_text("1")
+ settle()
+ order(["q0", "q1", "q2"])
+ assert abs(row("q0").bounding_box()["y"] - target["y"]) < 1
+ expect(page.get_by_role("status").filter(has_text = "queue changed")).to_be_attached()
+
+ reset()
+ x, y = grab("q0")
+ page.mouse.move(x, y + 60, steps = 5)
+ expect(row("q0")).to_have_attribute("data-queue-dragging", "true")
+ page.get_by_role("button", name = "Dispatch first", exact = True).evaluate(
+ "button => button.click()"
+ )
+ expect(row("q0")).to_have_count(0)
+ page.mouse.up()
+ order(["q1", "q2"])
+ expect(attempts).to_have_text("0")
+ expect(page.locator('[data-queue-dragging="true"]')).to_have_count(0)
+
+ # Holding at the edge scrolls without further pointer events.
+ reset()
+ page.get_by_role("button", name = "Long queue", exact = True).click()
+ expect(rows).to_have_count(12)
+ bounds = queue.bounding_box()
+ x, y = grab("long-0")
+ page.mouse.move(x, bounds["y"] + bounds["height"] - 5, steps = 10)
+ page.wait_for_function(
+ "() => { const list = document.querySelector('[aria-label^=\"Prompt queue,\"]'); return list.scrollTop >= list.scrollHeight - list.clientHeight - 1; }"
+ )
+ expect(attempts).to_have_text("0")
+ page.mouse.up()
+ expect(attempts).to_have_text("1")
+ settle()
+ order([f"long-{i}" for i in range(1, 12)] + ["long-0"])
+ print(
+ "PASS: continuous drag, sliding rows, deferred commit, cancellation, dispatch race and edge scrolling",
+ flush = True,
+ )
+
+
+def check_touch(browser, url):
+ context = browser.new_context(
+ viewport = {"width": 320, "height": 812}, is_mobile = True, has_touch = True
+ )
+ try:
+ page = context.new_page()
+ page.goto(url)
+ source = page.get_by_role("button", name = "Reorder queued prompt 3 of 3", exact = True)
+ expect(source).to_be_visible()
+ a = source.bounding_box()
+ b = page.get_by_role(
+ "button", name = "Reorder queued prompt 1 of 3", exact = True
+ ).bounding_box()
+ session = context.new_cdp_session(page)
+ x, y = a["x"] + a["width"] / 2, a["y"] + a["height"] / 2
+ session.send(
+ "Input.dispatchTouchEvent", {"type": "touchStart", "touchPoints": [{"x": x, "y": y}]}
+ )
+ for step in range(1, 7):
+ session.send(
+ "Input.dispatchTouchEvent",
+ {
+ "type": "touchMove",
+ "touchPoints": [{"x": x, "y": y + (b["y"] - a["y"]) * step / 6}],
+ },
+ )
+ session.send("Input.dispatchTouchEvent", {"type": "touchEnd", "touchPoints": []})
+ expect(page.locator("[data-queue-item-id]").first).to_have_attribute(
+ "data-queue-item-id", "q2"
+ )
+ page.get_by_role("button", name = "More options for queued prompt 1", exact = True).tap()
+ expect(page.get_by_role("menu")).to_be_visible()
+ page.get_by_role("menuitem", name = "Edit message", exact = True).tap()
+ expect(page.get_by_role("textbox", name = "Edit queued prompt 1", exact = True)).to_be_visible()
+ page.get_by_role("button", name = "Cancel", exact = True).tap()
+ assert page.evaluate("document.documentElement.scrollWidth <= innerWidth")
+ print("PASS: touch drag and menu editing at 320px", flush = True)
+ finally:
+ context.close()
+
+
+def main():
+ engine = os.environ.get("PW_ENGINE", "chromium")
+ port = int(os.environ.get("PW_PORT", "5421"))
+ server = None
+ base = os.environ.get("BASE_URL")
+ try:
+ if not base:
+ server = start_vite(port)
+ base = f"http://127.0.0.1:{port}"
+ url = base + PAGE
+ wait_for_smoke_page(url, ENTRY, proc = server)
+ with sync_playwright() as pw:
+ options = {"headless": True}
+ if os.environ.get("PW_EXECUTABLE"):
+ options["executable_path"] = os.environ["PW_EXECUTABLE"]
+ if os.environ.get("PW_CHANNEL"):
+ options["channel"] = os.environ["PW_CHANNEL"]
+ browser = getattr(pw, engine).launch(**options)
+ print(f"Browser: {os.environ.get('PW_CHANNEL', engine)} {browser.version}", flush = True)
+ try:
+ page = browser.new_page(viewport = {"width": 1100, "height": 800})
+ errors = []
+ page.on("pageerror", lambda error: errors.append(str(error)))
+ page.goto(url)
+ check_form_actions(page)
+ page.get_by_role("button", name = "Reset fixture", exact = True).click()
+ check_actions(page)
+ check_motion(page)
+ from _prompt_queue_edge_cases import check_edge_cases
+
+ check_edge_cases(page)
+ assert not errors, errors
+ reduced_context = browser.new_context(
+ reduced_motion = "reduce", viewport = {"width": 1100, "height": 800}
+ )
+ try:
+ reduced_page = reduced_context.new_page()
+ reduced_page.goto(url)
+ check_motion(reduced_page, reduced = True)
+ finally:
+ reduced_context.close()
+ if engine == "chromium":
+ check_touch(browser, url)
+ from _prompt_queue_edge_cases import check_performance
+
+ check_performance(browser, url)
+ finally:
+ browser.close()
+ finally:
+ if server:
+ stop_process(server)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/studio/run_composer_compatibility.py b/tests/studio/run_composer_compatibility.py
new file mode 100644
index 00000000000..04563058dac
--- /dev/null
+++ b/tests/studio/run_composer_compatibility.py
@@ -0,0 +1,76 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""Run every requested browser and retain individual verdicts under temp/."""
+
+import argparse
+import json
+import os
+import platform
+import subprocess
+import sys
+from pathlib import Path
+from _playwright_robust import stop_process
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument(
+ "--browsers", nargs = "+", default = ["chromium", "firefox", "webkit", "chrome", "msedge"]
+ )
+ parser.add_argument("--output", default = "temp/queue-validation/compatibility")
+ args = parser.parse_args()
+ root = Path(__file__).resolve().parents[2]
+ output = (root / args.output).resolve()
+ output.relative_to(root)
+ output.mkdir(parents = True, exist_ok = True)
+ temp = root / "temp/queue-validation/tmp"
+ temp.mkdir(parents = True, exist_ok = True)
+ env = {**os.environ, "TMPDIR": str(temp), "TMP": str(temp), "TEMP": str(temp)}
+ verdicts = []
+ for browser in args.browsers:
+ for script in ("playwright_prompt_queue_actions.py", "playwright_composer_settings.py"):
+ current = {
+ **env,
+ "PW_ENGINE": browser if browser in ("firefox", "webkit") else "chromium",
+ }
+ current.pop("PW_CHANNEL", None)
+ current.pop("PW_EXECUTABLE", None)
+ if browser in ("chrome", "msedge"):
+ current["PW_CHANNEL"] = browser
+ log = output / f"{browser}-{script.removesuffix('.py')}.log"
+ with log.open("w", encoding = "utf-8") as stream:
+ group = (
+ {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP}
+ if os.name == "nt"
+ else {"start_new_session": True}
+ )
+ process = subprocess.Popen(
+ [sys.executable, str(root / "tests/studio" / script)],
+ cwd = root,
+ env = current,
+ stdout = stream,
+ stderr = subprocess.STDOUT,
+ **group,
+ )
+ try:
+ code = process.wait(timeout = 180)
+ except subprocess.TimeoutExpired:
+ stop_process(process)
+ stream.write("FAIL: simulation exceeded 180 seconds\n")
+ code = 124
+ verdict = {
+ "os": platform.platform(),
+ "browser": browser,
+ "script": script,
+ "exit_code": code,
+ "log": str(log.relative_to(root)),
+ }
+ verdicts.append(verdict)
+ print(json.dumps(verdict), flush = True)
+ (output / "results.json").write_text(json.dumps(verdicts, indent = 2) + "\n", encoding = "utf-8")
+ return int(any(v["exit_code"] for v in verdicts))
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/studio/selenium_composer_safari.py b/tests/studio/selenium_composer_safari.py
new file mode 100644
index 00000000000..013f92f5184
--- /dev/null
+++ b/tests/studio/selenium_composer_safari.py
@@ -0,0 +1,170 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""Native Safari smoke test. Remote automation must already be enabled."""
+
+import json
+from pathlib import Path
+from selenium import webdriver
+from selenium.webdriver import ActionChains, Keys
+from selenium.webdriver.common.by import By
+from selenium.webdriver.support.ui import WebDriverWait
+from selenium.webdriver.support import expected_conditions as EC
+from _playwright_robust import start_vite, stop_process, wait_for_smoke_page
+
+
+def main():
+ output = Path("temp/queue-validation/compatibility")
+ output.mkdir(parents = True, exist_ok = True)
+ server = driver = None
+ report = {"browser": "native Safari", "passed": False}
+ try:
+ server = start_vite(5423)
+ base = "http://127.0.0.1:5423"
+ wait_for_smoke_page(
+ base + "/smoke-prompt-queue-actions.html",
+ "/smoke-prompt-queue-actions-main.tsx",
+ proc = server,
+ )
+ driver = webdriver.Safari()
+ driver.set_window_size(1100, 900)
+ report["version"] = driver.capabilities.get("browserVersion")
+ wait = WebDriverWait(driver, 10)
+
+ def label(name):
+ return wait.until(
+ EC.visibility_of_element_located((By.CSS_SELECTOR, f'[aria-label="{name}"]'))
+ )
+
+ def order(ids):
+ wait.until(
+ lambda d: d.execute_script(
+ "return [...document.querySelectorAll('[data-queue-item-id]')].map(row => row.dataset.queueItemId)"
+ )
+ == ids
+ )
+ driver.execute_async_script(
+ "const done = arguments[0]; Promise.all([...document.querySelectorAll('[data-queue-item-id]')].flatMap(row => row.getAnimations()).map(a => a.finished.catch(() => {}))).then(done)"
+ )
+
+ def text_button(name):
+ return wait.until(
+ lambda d: d.find_element(By.XPATH, f'//button[normalize-space(.)="{name}"]')
+ )
+
+ def command_enter(element):
+ element.click()
+ ActionChains(driver).key_down(Keys.COMMAND).send_keys(Keys.ENTER).key_up(
+ Keys.COMMAND
+ ).perform()
+
+ driver.get(base + "/smoke-prompt-queue-actions.html")
+ WebDriverWait(driver, 60).until(
+ EC.visibility_of_element_located((By.CSS_SELECTOR, "[data-queue-item-id]"))
+ )
+ order(["q0", "q1", "q2"])
+ label("Reorder queued prompt 3 of 3").send_keys(Keys.HOME)
+ order(["q2", "q0", "q1"])
+ label("More options for queued prompt 1").click()
+ wait.until(
+ EC.element_to_be_clickable(
+ (By.XPATH, '//*[@role="menuitem" and contains(.,"Edit message")]')
+ )
+ ).click()
+ editor = label("Edit queued prompt 1")
+ editor.clear()
+ editor.send_keys("Edited in Safari")
+ command_enter(editor)
+ wait.until(
+ lambda d: "Edited in Safari"
+ in d.find_element(By.CSS_SELECTOR, '[data-queue-item-id="q2"]').text
+ )
+ text_button("Reset fixture").click()
+ order(["q0", "q1", "q2"])
+ driver.execute_async_script(
+ "const done = arguments[0]; Promise.all([...document.getAnimations()].map(a => a.finished.catch(() => {}))).then(done)"
+ )
+ source = label("Reorder queued prompt 3 of 3")
+ target = label("Reorder queued prompt 1 of 3")
+ points = driver.execute_script(
+ "return [...arguments].map(el => { const r = el.getBoundingClientRect(); return {x: r.x + r.width / 2, y: r.y + r.height / 2}; })",
+ source,
+ target,
+ )
+ report["drag_points"] = points
+ driver.execute_script(
+ "window.queuePointerTrace = []; for (const type of ['pointerdown', 'pointermove', 'pointerup']) document.addEventListener(type, e => window.queuePointerTrace.push({type, x:e.clientX, y:e.clientY}), true)"
+ )
+ actions = ActionChains(driver)
+ pointer = actions.w3c_actions.pointer_action
+ pointer.move_to_location(round(points[0]["x"]), round(points[0]["y"]))
+ pointer.pointer_down()
+ pointer.move_to_location(round(points[1]["x"]), round(points[1]["y"]))
+ pointer.pause(0.1)
+ pointer.pointer_up()
+ actions.perform()
+ report["pointer_trace"] = driver.execute_script("return window.queuePointerTrace")
+ order(["q2", "q0", "q1"])
+ label("Steer with queued prompt 1").click()
+ order(["q0", "q1"])
+ assert label("Steered prompt").text == "Third prompt"
+ label("Remove queued prompt 2").click()
+ order(["q0"])
+ driver.get(base + "/smoke-composer-settings.html")
+ WebDriverWait(driver, 60).until(
+ EC.visibility_of_element_located((By.CSS_SELECTOR, '[aria-label="Message"]'))
+ )
+ label("Message")
+ driver.execute_script("localStorage.clear()")
+ driver.refresh()
+ label("Plain text composer").click()
+ editor = label("Message")
+ driver.execute_script(
+ "window.composerInputTrace = []; for (const type of ['keydown', 'keyup', 'input']) document.addEventListener(type, e => window.composerInputTrace.push({type, key:e.key, meta:e.metaKey, ctrl:e.ctrlKey, value:e.target.value, label:e.target.getAttribute('aria-label')}), true)"
+ )
+ editor.click()
+ editor.send_keys("**Safari preview**")
+ wait.until(lambda d: editor.get_attribute("value") == "**Safari preview**")
+ wait.until(lambda d: "Safari preview" in label("Formatted preview").text)
+ label("Show context window usage").click()
+ text_button("Steer").click()
+ editor.click()
+ editor.send_keys(Keys.ENTER)
+ wait.until(
+ lambda d: json.loads(label("Submitted messages").get_attribute("textContent"))
+ == [{"text": "**Safari preview**", "behavior": "steer"}]
+ )
+ editor.send_keys("Queue once")
+ command_enter(editor)
+ wait.until(
+ lambda d: json.loads(label("Submitted messages").get_attribute("textContent"))[-1][
+ "behavior"
+ ]
+ == "queue"
+ )
+ driver.refresh()
+ assert label("Plain text composer").get_attribute("aria-checked") == "false"
+ assert label("Show context window usage").get_attribute("aria-checked") == "false"
+ report["passed"] = True
+ print(
+ "PASS: native Safari queue controls, keyboard, pointer, preview, shortcuts and persistence",
+ flush = True,
+ )
+ except Exception as error:
+ report["error"] = str(error)
+ if driver:
+ report["input_trace"] = driver.execute_script("return window.composerInputTrace || []")
+ driver.save_screenshot(str(output / "native-safari-failure.png"))
+ raise
+ finally:
+ (output / "native-safari.json").write_text(
+ json.dumps(report, indent = 2) + "\n", encoding = "utf-8"
+ )
+ if driver:
+ driver.quit()
+ if server:
+ stop_process(server)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/studio/studiobench/scene/selftest/test_studiobench_queued_idle_live.py b/tests/studio/studiobench/scene/selftest/test_studiobench_queued_idle_live.py
index b8228e72a18..4c4df599b35 100644
--- a/tests/studio/studiobench/scene/selftest/test_studiobench_queued_idle_live.py
+++ b/tests/studio/studiobench/scene/selftest/test_studiobench_queued_idle_live.py
@@ -287,11 +287,13 @@ def test_the_shipped_composer_still_renders_the_two_queue_buttons():
if not _THREAD_TSX.exists():
pytest.skip(f"the shipped composer is not in this checkout: {_THREAD_TSX}")
src = _THREAD_TSX.read_text(encoding = "utf-8")
- assert src.count('aria-label="Queue message"') == 2, (
+ assert src.count("aria-label={followUpLabel}") == 2, (
"ComposerRightControls no longer renders the Queue button in exactly two places; "
"re-read which of them can appear on an idle thread"
)
- assert "aria-label={`Prompt queue, ${current} of ${total}`}" in src, (
+ assert 'followUpBehavior === "queue" ? "Queue message" : "Steer response"' in src
+ queue_src = (_THREAD_TSX.parent / "prompt-queue-list.tsx").read_text(encoding = "utf-8")
+ assert "aria-label={`Prompt queue, ${entry.current} of ${entry.total}`}" in queue_src, (
"PromptQueueStack no longer names itself, so dom.promptQueue() matches nothing and the "
"queued-idle interval is indistinguishable again"
)
diff --git a/tests/studio/test_multi_chat_prompt_queue_contract.py b/tests/studio/test_multi_chat_prompt_queue_contract.py
index f566f037895..6ac33a8ce5b 100644
--- a/tests/studio/test_multi_chat_prompt_queue_contract.py
+++ b/tests/studio/test_multi_chat_prompt_queue_contract.py
@@ -182,7 +182,10 @@ def test_composer_only_queues_behind_the_current_chat():
# share it. Assert the delegation here and the queueing there, rather than
# expecting the call inline, so this stays a contract on behaviour instead
# of on where the code happens to sit.
- assert "queueComposerText(liveThreadIsRunning || livePreStreamRunActive)" in submit
+ assert re.search(
+ r"queueComposerText\(\s*liveThreadIsRunning \|\| livePreStreamRunActive,\s*behavior,?\s*\)",
+ submit,
+ )
queue_composer_text = _between(
THREAD,
@@ -201,7 +204,10 @@ def test_composer_only_queues_behind_the_current_chat():
# Read out of the guard that actually dispatches, not out of the file: the
# abort and cleanup branches beside it hold the same comparison, so a
# whole-file search stays green while the dispatch alone regresses to `.has`.
- dispatch_guard = _guard_for(THREAD, "startPromptQueue(items, target, waitForCurrentRun);")
+ dispatch_guard = _guard_for(
+ THREAD,
+ "startPromptQueue(\n items,\n target,\n reservation.waitForCurrentRun,\n reservation.behavior,\n );",
+ )
assert "promptQueueStartPendingRef.current.get(reservationKey) ===" in dispatch_guard
assert "promptQueueStartPendingRef.current.has(" not in dispatch_guard
# The other two are load-bearing as well. Abort without the identity check reports the successor's start as this
@@ -339,9 +345,9 @@ def test_a_send_parked_on_the_settings_gate_queues_if_a_run_started_meanwhile():
# The gate on the queue branches, which is the fix itself: an active run governs the release, not the
# Cmd/Ctrl+Enter intent.
- running = code.index("if (waitForCurrentRun) {")
- branch = code[running : code.index("if (forceQueue && !disableQueue) {")]
- assert "queueComposerText(true);" in branch, (
+ running = code.index("if (waitForCurrentRun || queueAlreadyActive) {")
+ branch = code[running : code.index("clearStoredDraft();")]
+ assert "queueComposerText(waitForCurrentRun, behavior);" in branch, (
"the release no longer queues behind the run that started while the "
"send was parked, so the prompt goes back to being dropped silently"
)
@@ -380,12 +386,11 @@ def test_a_send_parked_on_the_settings_gate_queues_if_a_run_started_meanwhile():
# clears it from its own onStarted callback, so clearing it up front loses
# the text whenever the queue does not start -- a null target, an
# invalidated start -- and after the composer is replaced it is gone.
- assert code.index("clearStoredDraft();") > code.index("if (forceQueue && !disableQueue) {"), (
+ assert code.index("clearStoredDraft();") > running, (
"the stored draft is cleared before the queue and refusal paths, so a "
"prompt that is neither queued nor sent cannot be recovered"
)
- # Unchanged: with nothing running the chord still queues, and an ordinary send still sends. A fix that stopped
- # sending would strand that case.
+ # With nothing running, both shortcuts send normally.
assert "sendReservedComposer();" in code
@@ -398,11 +403,11 @@ def test_queued_settings_are_thread_scoped_without_cross_chat_fallback():
assert "await useChatRuntimeStore.getState().hydratePersistedSettings()" in target
assert target.index(
"await useChatRuntimeStore.getState().hydratePersistedSettings()"
- ) < target.index("snapshotQueuedChatRunSettings(chatStateAtQueueStart)")
+ ) < target.index("snapshotQueuedChatRunSettings(")
assert "!promptQueueTargetMountedRef.current" in target
assert "const currentState = aui.threadListItem().getState()" in target
assert "initialRunningThreadIds.includes(id)" in target
- assert "snapshotQueuedChatRunSettings(chatStateAtQueueStart)" in target
+ assert re.search(r"snapshotQueuedChatRunSettings\(\s*chatStateAtQueueStart,", target)
assert "registerQueuedChatRunSettings(" in target
assert "params: { ...runSettingsAtQueueStart.params }" in target
assert "runSettingsAtQueueStart.deepResearchEnabled = false" in target
@@ -510,7 +515,7 @@ def test_queued_settings_are_thread_scoped_without_cross_chat_fallback():
assert "await resolveQueuedEmptyLocalModel(transitionSignal)" in CHAT_ADAPTER
assert "await resolveQueuedEmptyLocalModel(abortSignal)" in CHAT_ADAPTER
assert "persist: !options?.preserveVisibleSettings" in CHAT_ADAPTER
- assert "beginModelLoading()" in CHAT_ADAPTER
+ assert 'beginModelLoading("loading")' in CHAT_ADAPTER
assert "endModelLoading(lifecycleLease)" in CHAT_ADAPTER
lifecycle = _between(
CHAT_ADAPTER,
@@ -520,7 +525,7 @@ def test_queued_settings_are_thread_scoped_without_cross_chat_fallback():
# The probe waits out an in-flight load rather than reading a status taken
# mid-replacement, which names the outgoing model alongside the incoming one.
probe = "await waitForSettledServerStatus({ abortSignal })"
- assert lifecycle.index("beginModelLoading()") < lifecycle.index(probe)
+ assert lifecycle.index('beginModelLoading("loading")') < lifecycle.index(probe)
assert lifecycle.index(probe) < lifecycle.index("await autoLoadSmallestModel(")
assert "getInferenceStatus().catch(() => null)" not in lifecycle
assert f"const settled = {probe};" in lifecycle
@@ -576,7 +581,7 @@ def test_queued_settings_are_thread_scoped_without_cross_chat_fallback():
)
assert "if (failedRun)" in queue_failure_handler
assert "retainPendingPromptQueueItemsAfterFailure(failedRun)" in queue_failure_handler
- assert "deletePromptQueueRun(failedRun);" in queue_failure_handler
+ assert "pausePromptQueueRun([threadId]);" in queue_failure_handler
retained_failure = _between(
THREAD,
"function retainPendingPromptQueueItemsAfterFailure(run: PromptQueueRun)",
@@ -625,14 +630,25 @@ def test_queued_settings_are_thread_scoped_without_cross_chat_fallback():
"const ejectModel = useCallback(",
)
assert (
- select_model.index("beginModelLoading()")
+ select_model.index('beginModelLoading("preparing")')
< select_model.index("await confirmStopRunningChatsIfNeeded(")
< select_model.index("cancelPreStreamRunReservations(stopDecision.preStreamRunTokens)")
< select_model.index("requestLocalPromptQueueStop(stopDecision.promptQueueThreadIds)")
)
- assert "beginModelLoading()" in eject
+ assert 'beginModelLoading("unloading")' in eject
assert "endModelLoading(lifecycleLease)" in eject
- assert "beginModelLoading()" in SHARED_COMPOSER
+ assert 'beginModelLoading("preparing")' in SHARED_COMPOSER
+ assert MODEL_RUNTIME.index(
+ "chatModelLifecycleGate.markLoading(lifecycleLease)"
+ ) > MODEL_RUNTIME.index("requestLocalPromptQueueStop();")
+ failure = MODEL_RUNTIME.split("notifyLocalPromptQueueLoadFailed(lifecycleLease);", 1)[1]
+ assert failure.index("if (abortCtrl.signal.aborted)") < failure.index(
+ "const rollbackResponse = await loadModel("
+ )
+ cancellation = MODEL_RUNTIME.split("const cancelLoading = useCallback(", 1)[1]
+ assert cancellation.index("notifyLocalPromptQueueLoadFailed(") < cancellation.index(
+ "loadAbortRef.current?.abort()"
+ )
assert "endModelLoading(compareLifecycleLease)" in SHARED_COMPOSER
assert SHARED_COMPOSER.count("releaseCompareModelLifecycle();") >= 3
compare_upgrade = _between(
@@ -683,7 +699,7 @@ def test_queued_settings_are_thread_scoped_without_cross_chat_fallback():
)
assert "requestLocalPromptQueueStop" in eject
assert (
- eject.index("beginModelLoading()")
+ eject.index('beginModelLoading("unloading")')
< eject.index("await confirmStopRunningChatsIfNeeded(")
< eject.index("cancelPreStreamRunReservations(stopDecision.preStreamRunTokens)")
< eject.index("requestLocalPromptQueueStop(stopDecision.promptQueueThreadIds)")
@@ -765,7 +781,7 @@ def test_queued_settings_are_thread_scoped_without_cross_chat_fallback():
gpu_discovery_index,
)
assert (
- send_flow.index("beginModelLoading()")
+ send_flow.index('beginModelLoading("preparing")')
< confirm_index
< first_draft_check
< gpu_discovery_index