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.

Support independent prompt queues across parallel chats (#7629)

Lee Jackson207cf4a2a00e
diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsx
index 4364554be94..db6583bf726 100644
--- a/studio/frontend/src/components/app-sidebar.tsx
+++ b/studio/frontend/src/components/app-sidebar.tsx
@@ -132,6 +132,7 @@ import {
usePinnedChatsStore,
usePinnedProjectsStore,
useChatPreferencesStore,
+ usePromptQueueUI,
type ProjectRecord,
type SidebarItem,
} from "@/features/chat";
@@ -387,6 +388,10 @@ function NavItem({
);
}
+function getSidebarItemThreadIds(item: SidebarItem) {
+ return item.threadIds?.length ? item.threadIds : [item.id];
+}
+
const WORKFLOW_UNAVAILABLE = "The loaded model cannot do this";
/** One workflow in the list under the Images row. */
@@ -750,12 +755,12 @@ export function AppSidebar() {
const storeThreadId = useChatRuntimeStore((s) => s.activeThreadId);
const setActiveThreadId = useChatRuntimeStore((s) => s.setActiveThreadId);
// The whole map, so each row can show its own spinner.
- const runningThreadIds = useChatRuntimeStore((s) => s.runningByThreadId);
+ const runningByThreadId = useChatRuntimeStore((s) => s.runningByThreadId);
// Rows, not raw thread ids: a compare conversation runs two pane threads but is one chat
// in the sidebar, so counting the map said "2 Chats" for a single compare row.
const runningChatCount = useMemo(() => {
const running = new Set(
- Object.entries(runningThreadIds)
+ Object.entries(runningByThreadId)
.filter(([, on]) => on)
.map(([id]) => id),
);
@@ -771,13 +776,13 @@ export function AppSidebar() {
}
// Anything left belongs to no known row (a first turn mid-persist); count it as one.
return rows + running.size;
- }, [runningThreadIds, allChatItems]);
+ }, [runningByThreadId, allChatItems]);
const anyChatRunning = runningChatCount > 0;
// Where "Return to Chat" lands: the newest running chat, not the empty draft New Chat left
// active (map insertion order is start order). A compare row runs pane threads that /chat
// cannot address, so resolve those back to the pair id the route expects.
const runningTarget = useMemo(() => {
- const ids = Object.entries(runningThreadIds)
+ const ids = Object.entries(runningByThreadId)
.filter(([, on]) => on)
.map(([id]) => id);
const id = ids.length > 0 ? ids[ids.length - 1] : null;
@@ -788,13 +793,73 @@ export function AppSidebar() {
return pair
? { id: pair.id, compare: true as const }
: { id, compare: false as const };
- }, [runningThreadIds, allChatItems]);
+ }, [runningByThreadId, allChatItems]);
const activeThreadId = isChatRoute
? (search.thread as string | undefined) ??
(search.compare as string | undefined) ??
storeThreadId ??
undefined
: undefined;
+ const queueByThreadId = usePromptQueueUI((s) => s.byThreadId);
+ const [unreadThreadIds, setUnreadThreadIds] = useState<Set<string>>(
+ () => new Set(),
+ );
+ const previousRunningByThreadIdRef = useRef<Record<string, boolean>>({});
+ const activeVisibleThreadIds = useMemo(() => {
+ if (!activeThreadId) {
+ return [];
+ }
+ const activeItem = allChatItems.find((item) => item.id === activeThreadId);
+ return activeItem ? getSidebarItemThreadIds(activeItem) : [activeThreadId];
+ }, [activeThreadId, allChatItems]);
+ const activeVisibleThreadIdKey = activeVisibleThreadIds.join("\n");
+
+ useEffect(() => {
+ const activeVisibleThreadIdSet = new Set(
+ activeVisibleThreadIdKey ? activeVisibleThreadIdKey.split("\n") : [],
+ );
+ const previousRunningByThreadId = previousRunningByThreadIdRef.current;
+ const completedThreadIds: string[] = [];
+
+ for (const [threadId, wasRunning] of Object.entries(
+ previousRunningByThreadId,
+ )) {
+ if (
+ wasRunning &&
+ !runningByThreadId[threadId] &&
+ !activeVisibleThreadIdSet.has(threadId)
+ ) {
+ completedThreadIds.push(threadId);
+ }
+ }
+
+ if (completedThreadIds.length > 0 || activeVisibleThreadIdSet.size > 0) {
+ queueMicrotask(() => {
+ setUnreadThreadIds((current) => {
+ let next: Set<string> | null = null;
+ const mutable = () => {
+ next ??= new Set(current);
+ return next;
+ };
+
+ for (const threadId of completedThreadIds) {
+ if (!current.has(threadId)) {
+ mutable().add(threadId);
+ }
+ }
+
+ for (const threadId of activeVisibleThreadIdSet) {
+ if (current.has(threadId)) {
+ mutable().delete(threadId);
+ }
+ }
+
+ return next ?? current;
+ });
+ });
+ }
+ previousRunningByThreadIdRef.current = runningByThreadId;
+ }, [activeVisibleThreadIdKey, runningByThreadId]);
// Training runs: surfaced as sidebar "Recents" on Train, Recipes, and Export,
// falling back to chat recents when there are no runs yet.
@@ -1306,17 +1371,45 @@ export function AppSidebar() {
}
}
+ function clearChatNotifications(item: SidebarItem) {
+ const threadIds = getSidebarItemThreadIds(item);
+ setUnreadThreadIds((current) => {
+ if (!threadIds.some((threadId) => current.has(threadId))) {
+ return current;
+ }
+ const next = new Set(current);
+ for (const threadId of threadIds) {
+ next.delete(threadId);
+ }
+ return next;
+ });
+ }
+
function renderChatSidebarItem(
item: SidebarItem,
variant: "project" | "recent",
) {
+ const threadIds = getSidebarItemThreadIds(item);
const isPinned = pinnedIdSet.has(item.id);
// A compare row's id is the pair id while runningByThreadId is keyed per pane thread,
// so aggregate its member threads instead.
const isGenerating =
item.type === "compare"
- ? (item.threadIds ?? []).some((id) => Boolean(runningThreadIds[id]))
- : Boolean(runningThreadIds[item.id]);
+ ? (item.threadIds ?? []).some((id) => Boolean(runningByThreadId[id]))
+ : Boolean(runningByThreadId[item.id]);
+ const hasQueuedActivity = threadIds.some((threadId) =>
+ Boolean(queueByThreadId[threadId]),
+ );
+ // Active generation and queued work share the established in-row spinner
+ // slot so their size and position cannot drift apart.
+ const showQueuedActivity = hasQueuedActivity && !isGenerating;
+ const showWorkSpinner = isGenerating || showQueuedActivity;
+ const hasUnreadActivity =
+ !isGenerating &&
+ !hasQueuedActivity &&
+ threadIds.some((threadId) => unreadThreadIds.has(threadId));
+ const hasSecondaryRowAction =
+ variant === "project" || (variant === "recent" && isPinned);
const itemClass =
variant === "project"
? "group/project-chat-item relative"
@@ -1332,21 +1425,32 @@ export function AppSidebar() {
variant === "project" ? "pl-[39px]" : "pl-3",
// Pinned chats carry a chat icon, so add the nav-item icon gap.
isPinned && variant !== "project" && "gap-[8.5px]",
+ showWorkSpinner
+ ? hasSecondaryRowAction
+ ? "pr-16"
+ : undefined
+ : hasUnreadActivity
+ ? "pr-7"
+ : undefined,
variant === "project"
- ? // Room for the hover pin quick-action plus the kebab.
- "group-hover/project-chat-item:pr-14 group-has-[.sidebar-row-action[data-state=open]]/project-chat-item:pr-8 [@media(pointer:coarse)]:pr-14"
+ ? showWorkSpinner
+ ? undefined
+ : // Room for the hover pin quick-action plus the kebab.
+ "group-hover/project-chat-item:pr-14 group-has-[.sidebar-row-action[data-state=open]]/project-chat-item:pr-8 [@media(pointer:coarse)]:pr-14"
: isPinned
- ? // Pinned rows show an extra unpin button on hover, so reserve more room
- // (pr-8 when the menu is open keeps the unpin button clear of the title).
- "group-hover/recent-item:pr-16 group-has-[.sidebar-row-action[data-state=open]]/recent-item:pr-8 [@media(pointer:coarse)]:pr-16"
- : isGenerating
+ ? showWorkSpinner
+ ? undefined
+ : // Pinned rows show an extra unpin button on hover, so reserve more room
+ // (pr-8 when the menu is open keeps the unpin button clear of the title).
+ "group-hover/recent-item:pr-16 group-has-[.sidebar-row-action[data-state=open]]/recent-item:pr-8 [@media(pointer:coarse)]:pr-16"
+ : showWorkSpinner
? // A spinner glyph cannot truncate, so clear the kebab's 30px inset (pr-1.5 + size-6).
"group-hover/recent-item:pr-8 group-has-[.sidebar-row-action[data-state=open]]/recent-item:pr-8 [@media(pointer:coarse)]:pr-10"
: // Hover room for the kebab only; title keeps one more character.
// Touch rows clear the full always-visible kebab hit area (pr-10).
"group-hover/recent-item:pr-6 group-has-[.sidebar-row-action[data-state=open]]/recent-item:pr-6 [@media(pointer:coarse)]:pr-10",
// A focused kebab is revealed without hover, so a spinner row reserves the same room.
- isGenerating &&
+ showWorkSpinner &&
(variant === "project"
? "group-has-[.sidebar-row-action:focus-visible]/project-chat-item:pr-14"
: isPinned
@@ -1391,6 +1495,7 @@ export function AppSidebar() {
isActive={activeThreadId === item.id}
className={buttonClass}
onClick={() => {
+ clearChatNotifications(item);
navigate({
to: "/chat",
search:
@@ -1413,15 +1518,32 @@ export function AppSidebar() {
<span className="truncate">
{pendingRename?.id === item.id ? pendingRename.title : item.title}
</span>
- {isGenerating && (
+ {showWorkSpinner && (
<Spinner
data-testid="chat-row-spinner"
// role="status" + label: announced, not motion-only.
- label={translate("shell.navigation.chatGenerating")}
+ label={
+ isGenerating
+ ? translate("shell.navigation.chatGenerating")
+ : "Queued"
+ }
className="ml-auto size-3.5 shrink-0 text-muted-foreground"
/>
)}
</SidebarMenuButton>
+ {hasUnreadActivity ? (
+ <span
+ className={cn(
+ "pointer-events-none absolute right-2 top-1/2 z-10 flex size-4 -translate-y-1/2 items-center justify-center text-muted-foreground transition-opacity",
+ variant === "project"
+ ? "group-hover/project-chat-item:opacity-0 group-has-[.sidebar-row-action[data-state=open]]/project-chat-item:opacity-0"
+ : "group-hover/recent-item:opacity-0 group-has-[.sidebar-row-action[data-state=open]]/recent-item:opacity-0",
+ )}
+ aria-hidden
+ >
+ <span className="size-2 rounded-full bg-[#d07a5f] dark:bg-[#df8a6f]" />
+ </span>
+ ) : null}
{variant === "project" && (
<button
type="button"
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index 6bd99be663c..616dca30236 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -99,18 +99,45 @@ import { BypassPermissionsMenuItem } from "@/features/chat/bypass-permissions-me
import { PermissionModeComposerPill } from "@/features/chat/permission-mode-select";
import { useChatRuntimeStore } from "@/features/chat/stores/chat-runtime-store";
import { useExternalProvidersStore } from "@/features/chat/stores/external-providers-store";
-import { PROMPT_QUEUE_STOP_EVENT } from "@/features/chat/utils/prompt-queue-boundary";
import {
PLUS_MENU_ORDER,
+ PROMPT_QUEUE_RUN_FAILED_EVENT,
+ PROMPT_QUEUE_STOP_EVENT,
+ addQueuedChatRunSettingsThreadIds,
+ adoptPreStreamRunReservation,
+ chatHistoryClearBoundary,
+ deleteStoredChatThreads,
+ discardQueuedChatRunSettings,
+ discardQueuedChatRunSettingsForThread,
+ hasPreStreamRunReservation,
+ localPromptQueueModelBoundary,
+ notifyPromptQueueRunFailed,
+ planLocalPromptQueueStop,
+ registerQueuedChatRunSettings,
+ releasePreStreamRunReservation,
+ reservePreStreamRun,
+ shouldAbortPendingQueueForModelBoundary,
+ shouldAbortPendingQueueForSettingsChange,
+ snapshotQueuedChatRunSettings,
composerDraftKey,
+ markThreadIncognito,
+ markChatThreadDeleted,
+ type PromptQueueRunFailedEventDetail,
+ type PromptQueueStopEventDetail,
dictationFailed,
dictationProducedTranscript,
readComposerDraft,
+ type PromptQueueUIEntry,
+ type PromptQueueUIItem,
+ type PromptQueueUIItemStatus,
+ type PromptQueueUIState,
+ usePromptQueueUI,
type PlusMenuItemId,
usePlusMenuPrefsStore,
writeComposerDraft,
} from "@/features/chat";
import { deleteThreadMessage } from "@/features/chat/utils/delete-thread-message";
+import { updateStoredChatThread } from "@/features/chat/utils/chat-history-storage";
import {
dictationSendBlocked,
shouldSubmitDictation,
@@ -183,7 +210,6 @@ import {
} from "lucide-react";
import {
type ChangeEvent,
- type ComponentProps,
type CompositionEvent,
type ClipboardEvent,
type FC,
@@ -199,7 +225,6 @@ import {
useRef,
useState,
} from "react";
-import { create } from "zustand";
import { extractTaggedText, updateThreadMessage } from "@/features/chat/utils/update-thread-message";
import { useIsMobile } from "@/hooks/use-mobile";
@@ -207,50 +232,23 @@ import { useIsMobile } from "@/hooks/use-mobile";
// can show its "Drop files here" affordance.
const PageDragContext = createContext(false);
-// Single-chat prompt queue. State lives at module level so it survives the
-// Composer remount when the first queued message creates a new thread, and
-// detection subscribes to runningByThreadId instead of aui.thread() so the
-// welcome-screen composer can queue safely before a thread is bound.
-type PromptQueueUIEntry = {
- current: number;
- total: number;
-};
-
-type PromptQueueUIItemStatus = "queued" | "next" | "waiting" | "running";
-
-type PromptQueueUIItem = {
- id: string;
- prompt: string;
- position: number;
- total: number;
- status: PromptQueueUIItemStatus;
- threadIds: string[];
- canEdit: boolean;
- canRemove: boolean;
-};
-
-interface PromptQueueUIState {
- byThreadId: Record<string, PromptQueueUIEntry>;
- current: number;
- total: number;
- items: PromptQueueUIItem[];
- isRunning: boolean;
-}
-
-const usePromptQueueUI = create<PromptQueueUIState>(() => ({
- byThreadId: {},
- current: 0,
- total: 0,
- items: [],
- isRunning: false,
-}));
-
+// Prompt queues live at module level so they survive Composer remounts,
+// including the first queued message that creates a new thread. Each chat gets
+// its own queue run; completion detection subscribes to runningByThreadId
+// instead of aui.thread() so queues can keep advancing in the background.
type PromptQueueTarget = {
getDocumentThreadId: () => string | null;
getRunningThreadIds: () => string[];
- append: (prompt: string) => void;
+ isRunning: () => boolean;
+ append: (prompt: string) => void | Promise<void>;
+ complete: () => void;
cancel: () => void;
isIndexing: () => boolean;
+ usesThreadDocuments: boolean;
+ usesLocalModel: boolean;
+ usesDeepResearch: boolean;
+ temporary: boolean;
+ consumeDeepResearch: () => void;
};
type PromptQueueItem = {
@@ -258,18 +256,32 @@ type PromptQueueItem = {
prompt: string;
target: PromptQueueTarget;
dispatched: boolean;
+ dispatchRetries: number;
};
-const PROMPT_QUEUE_INDEXING_RETRY_MS = 500;
+type PromptQueueRun = {
+ id: string;
+ items: PromptQueueItem[];
+ index: number;
+ generation: number;
+ prevStoreRunning: boolean;
+ waitingForTargetIdle: boolean;
+ retryTimer: ReturnType<typeof setTimeout> | null;
+ deepResearchConsumed: boolean;
+};
-let promptQueueItems: PromptQueueItem[] = [];
-let promptQueueIndex = 0;
-let promptQueueIsRunning = false;
-let promptQueueGeneration = 0;
-let promptQueuePrevStoreRunning = false;
-let promptQueueWaitingForTargetIdle = false;
+const PROMPT_QUEUE_INDEXING_RETRY_MS = 500;
+const PROMPT_QUEUE_DISPATCH_RETRY_MS = 500;
+const PROMPT_QUEUE_TARGET_STATE_POLL_MS = 50;
+const PROMPT_QUEUE_MAX_DISPATCH_RETRIES = 5;
+
+const promptQueueRuns = new Map<string, PromptQueueRun>();
+const promptQueueActiveRunIds = new Set<string>();
+const promptQueueDispatchingRunIds = new Set<string>();
+const promptQueueRunOrder: string[] = [];
let promptQueueStoreUnsub: (() => void) | null = null;
-let promptQueueRetryTimer: ReturnType<typeof setTimeout> | null = null;
+let promptQueuePumpTimer: ReturnType<typeof setTimeout> | null = null;
+let promptQueueRoundRobinCursor = 0;
function compactIds(ids: Array<string | null | undefined>) {
return Array.from(new Set(ids.filter((id): id is string => Boolean(id))));
@@ -279,49 +291,145 @@ function createPromptQueueItemId() {
return `prompt-queue-${crypto.randomUUID()}`;
}
-function stopPromptQueueSubscription({
- resetRunningState = true,
-}: {
- resetRunningState?: boolean;
-} = {}) {
+function createPromptQueueRunId() {
+ return `prompt-queue-run-${crypto.randomUUID()}`;
+}
+
+function stopPromptQueueSubscription() {
if (promptQueueStoreUnsub) {
promptQueueStoreUnsub();
promptQueueStoreUnsub = null;
}
- if (resetRunningState) {
- promptQueuePrevStoreRunning = false;
+}
+
+function clearPromptQueuePumpTimer() {
+ if (!promptQueuePumpTimer) {
+ return;
}
+ clearTimeout(promptQueuePumpTimer);
+ promptQueuePumpTimer = null;
}
-function resetPromptQueue() {
- promptQueueGeneration += 1;
- promptQueueIsRunning = false;
- promptQueueItems = [];
- promptQueueIndex = 0;
- promptQueueWaitingForTargetIdle = false;
- if (promptQueueRetryTimer) {
- clearTimeout(promptQueueRetryTimer);
- promptQueueRetryTimer = null;
+function clearPromptQueueRetryTimer(run: PromptQueueRun) {
+ if (!run.retryTimer) {
+ return;
}
+ clearTimeout(run.retryTimer);
+ run.retryTimer = null;
+}
+
+function deletePromptQueueRun(run: PromptQueueRun) {
+ run.generation += 1;
+ clearPromptQueueRetryTimer(run);
+ promptQueueActiveRunIds.delete(run.id);
+ promptQueueDispatchingRunIds.delete(run.id);
+ promptQueueRuns.delete(run.id);
+ const orderIndex = promptQueueRunOrder.indexOf(run.id);
+ if (orderIndex >= 0) {
+ promptQueueRunOrder.splice(orderIndex, 1);
+ if (promptQueueRoundRobinCursor > orderIndex) {
+ promptQueueRoundRobinCursor -= 1;
+ }
+ if (promptQueueRunOrder.length > 0) {
+ promptQueueRoundRobinCursor %= promptQueueRunOrder.length;
+ } else {
+ promptQueueRoundRobinCursor = 0;
+ }
+ }
+ if (promptQueueRuns.size === 0) {
+ clearPromptQueuePumpTimer();
+ stopPromptQueueSubscription();
+ }
+ syncPromptQueueUI();
+}
+
+function resetPromptQueues() {
+ for (const run of promptQueueRuns.values()) {
+ run.generation += 1;
+ clearPromptQueueRetryTimer(run);
+ }
+ promptQueueRuns.clear();
+ promptQueueActiveRunIds.clear();
+ promptQueueDispatchingRunIds.clear();
+ promptQueueRunOrder.length = 0;
+ promptQueueRoundRobinCursor = 0;
+ clearPromptQueuePumpTimer();
stopPromptQueueSubscription();
syncPromptQueueUI();
}
-function appendQueuedPrompt(item: PromptQueueItem) {
+function requestPromptQueuePumpIfReady(delay = 0) {
+ if (hasReadyPromptQueueRun()) {
+ requestPromptQueuePump(delay);
+ }
+}
+
+function handleQueuedPromptAppendFailure(
+ run: PromptQueueRun,
+ item: PromptQueueItem,
+ error: unknown,
+) {
+ if (!isActivePromptQueueItem(run, item, run.generation)) {
+ return;
+ }
+ item.dispatched = false;
+ promptQueueActiveRunIds.delete(run.id);
+ syncPromptQueueUI();
+ item.dispatchRetries += 1;
+ if (item.dispatchRetries > PROMPT_QUEUE_MAX_DISPATCH_RETRIES) {
+ console.error("Prompt queue dispatch failed permanently:", error);
+ try {
+ item.target.cancel();
+ } catch (cleanupError) {
+ console.error("Prompt queue cleanup failed:", cleanupError);
+ }
+ deletePromptQueueRun(run);
+ requestPromptQueuePumpIfReady();
+ return;
+ }
+ item.target.complete();
+ scheduleQueuedPromptDispatch(run, item, PROMPT_QUEUE_DISPATCH_RETRY_MS);
+}
+
+function consumePromptQueueDeepResearch(
+ run: PromptQueueRun,
+ item: PromptQueueItem,
+) {
+ if (run.deepResearchConsumed || !item.target.usesDeepResearch) {
+ return;
+ }
+ run.deepResearchConsumed = true;
+ for (const item of run.items) {
+ item.target.consumeDeepResearch();
+ }
+}
+
+function appendQueuedPrompt(run: PromptQueueRun, item: PromptQueueItem) {
item.dispatched = true;
+ promptQueueActiveRunIds.add(run.id);
syncPromptQueueUI();
- item.target.append(item.prompt);
+ try {
+ const result = item.target.append(item.prompt);
+ if (result && typeof result.catch === "function") {
+ void result
+ .then(() => consumePromptQueueDeepResearch(run, item))
+ .catch((error) => {
+ handleQueuedPromptAppendFailure(run, item, error);
+ });
+ } else {
+ consumePromptQueueDeepResearch(run, item);
+ }
+ } catch (error) {
+ handleQueuedPromptAppendFailure(run, item, error);
+ }
+ schedulePromptQueueTargetStatePoll(run);
}
async function targetHasIndexingDocuments(item: PromptQueueItem) {
if (item.target.isIndexing()) {
return true;
}
- const state = useChatRuntimeStore.getState();
- if (
- !state.ragEnabled ||
- state.ragSource.type !== "thread"
- ) {
+ if (!item.target.usesThreadDocuments) {
return false;
}
const threadId = item.target.getDocumentThreadId();
@@ -334,36 +442,118 @@ async function targetHasIndexingDocuments(item: PromptQueueItem) {
(doc) => doc.status === "pending" || doc.status === "running",
);
} catch {
- return item.target.isIndexing();
+ // A failed status probe cannot prove that this thread's documents are
+ // ready. Keep the queued send pending and retry instead of dispatching
+ // without the RAG documents it was explicitly waiting for.
+ return true;
}
}
-function isActivePromptQueueItem(item: PromptQueueItem, generation: number) {
- if (!promptQueueIsRunning || generation !== promptQueueGeneration) {
+function getActivePromptQueueItem(run: PromptQueueRun) {
+ return run.items[Math.max(run.index, 0)];
+}
+
+function isActivePromptQueueItem(
+ run: PromptQueueRun,
+ item: PromptQueueItem,
+ generation: number,
+) {
+ if (promptQueueRuns.get(run.id) !== run || generation !== run.generation) {
return false;
}
- return promptQueueItems[Math.max(promptQueueIndex, 0)] === item;
+ return getActivePromptQueueItem(run) === item;
}
function scheduleQueuedPromptDispatch(
+ run: PromptQueueRun,
item: PromptQueueItem,
delay: number,
- generation = promptQueueGeneration,
+ generation = run.generation,
) {
- if (promptQueueRetryTimer) {
- clearTimeout(promptQueueRetryTimer);
+ clearPromptQueueRetryTimer(run);
+ run.retryTimer = setTimeout(() => {
+ run.retryTimer = null;
+ if (isActivePromptQueueItem(run, item, generation)) {
+ requestPromptQueuePump();
+ }
+ }, delay);
+}
+
+function isPromptQueueRunReadyToDispatch(run: PromptQueueRun) {
+ const item = getActivePromptQueueItem(run);
+ return Boolean(
+ item &&
+ run.index >= 0 &&
+ !item.dispatched &&
+ !run.waitingForTargetIdle &&
+ !run.retryTimer &&
+ !promptQueueActiveRunIds.has(run.id) &&
+ !promptQueueDispatchingRunIds.has(run.id),
+ );
+}
+
+function getNextReadyPromptQueueRun() {
+ if (promptQueueRunOrder.length === 0) {
+ return null;
+ }
+ const size = promptQueueRunOrder.length;
+ for (let offset = 0; offset < size; offset += 1) {
+ const orderIndex = (promptQueueRoundRobinCursor + offset) % size;
+ const runId = promptQueueRunOrder[orderIndex];
+ const run = promptQueueRuns.get(runId);
+ if (!run || !isPromptQueueRunReadyToDispatch(run)) {
+ continue;
+ }
+ promptQueueRoundRobinCursor = (orderIndex + 1) % size;
+ return run;
+ }
+ return null;
+}
+
+function requestPromptQueuePump(delay = 0) {
+ if (promptQueuePumpTimer) {
+ return;
}
- promptQueueRetryTimer = setTimeout(() => {
- promptQueueRetryTimer = null;
- void dispatchQueuedPrompt(item, generation);
+ promptQueuePumpTimer = setTimeout(() => {
+ promptQueuePumpTimer = null;
+ pumpPromptQueues();
}, delay);
}
+function pumpPromptQueues() {
+ ensurePromptQueueSubscription();
+ // A queue is sequential within its own thread, but independent threads may
+ // dispatch together. The inference backend owns its actual concurrency cap
+ // and queues excess local generations.
+ while (true) {
+ const run = getNextReadyPromptQueueRun();
+ if (!run) {
+ return;
+ }
+ const item = getActivePromptQueueItem(run);
+ if (!item) {
+ deletePromptQueueRun(run);
+ continue;
+ }
+ promptQueueDispatchingRunIds.add(run.id);
+ dispatchQueuedPrompt(run, item, run.generation)
+ .catch(() => undefined)
+ .finally(() => {
+ promptQueueDispatchingRunIds.delete(run.id);
+ syncPromptQueueUI();
+ if (!promptQueueActiveRunIds.has(run.id)) {
+ requestPromptQueuePump();
+ }
+ });
+ }
+}
+
async function dispatchQueuedPrompt(
+ run: PromptQueueRun,
item: PromptQueueItem,
- generation = promptQueueGeneration,
+ generation = run.generation,
) {
- if (!isActivePromptQueueItem(item, generation)) {
+ if (!isActivePromptQueueItem(run, item, generation)) {
return;
}
if (
@@ -372,24 +562,31 @@ async function dispatchQueuedPrompt(
useChatRuntimeStore.getState().runningByThreadId,
)
) {
- promptQueueWaitingForTargetIdle = true;
- promptQueuePrevStoreRunning = true;
+ run.waitingForTargetIdle = true;
+ run.prevStoreRunning = true;
+ promptQueueActiveRunIds.delete(run.id);
syncPromptQueueUI();
- startPromptQueueSubscription();
+ ensurePromptQueueSubscription();
+ handlePromptQueueRunState(
+ run,
+ useChatRuntimeStore.getState().runningByThreadId,
+ );
+ schedulePromptQueueTargetStatePoll(run);
return;
}
const hasIndexingDocuments = await targetHasIndexingDocuments(item);
- if (!isActivePromptQueueItem(item, generation)) {
+ if (!isActivePromptQueueItem(run, item, generation)) {
return;
}
if (hasIndexingDocuments) {
- scheduleQueuedPromptDispatch(item, PROMPT_QUEUE_INDEXING_RETRY_MS);
+ promptQueueActiveRunIds.delete(run.id);
+ scheduleQueuedPromptDispatch(run, item, PROMPT_QUEUE_INDEXING_RETRY_MS);
return;
}
- if (!isActivePromptQueueItem(item, generation)) {
+ if (!isActivePromptQueueItem(run, item, generation)) {
return;
}
- appendQueuedPrompt(item);
+ appendQueuedPrompt(run, item);
}
function createQueuedPrompt(prompt: string, target: PromptQueueTarget) {
@@ -398,6 +595,7 @@ function createQueuedPrompt(prompt: string, target: PromptQueueTarget) {
prompt,
target,
dispatched: false,
+ dispatchRetries: 0,
};
}
@@ -416,6 +614,66 @@ function getPromptQueueTargetIds(target: PromptQueueTarget) {
]);
}
+function getPromptQueueRunTargetIds(run: PromptQueueRun) {
+ return compactIds(
+ run.items.flatMap((item) => getPromptQueueTargetIds(item.target)),
+ );
+}
+
+function promptQueueRunUsesLocalModel(run: PromptQueueRun) {
+ return run.items
+ .slice(Math.max(run.index, 0))
+ .some((item) => item.target.usesLocalModel);
+}
+
+function promptQueueRunIsTemporary(run: PromptQueueRun) {
+ return run.items
+ .slice(Math.max(run.index, 0))
+ .some((item) => item.target.temporary);
+}
+
+function promptQueueRunMatchesThreadIds(
+ run: PromptQueueRun,
+ threadIds: string[],
+) {
+ return getPromptQueueRunTargetIds(run).some((id) => threadIds.includes(id));
+}
+
+function findPromptQueueRunByTarget(target: PromptQueueTarget) {
+ const targetIds = getPromptQueueTargetIds(target);
+ if (targetIds.length === 0) {
+ return null;
+ }
+ for (const run of promptQueueRuns.values()) {
+ if (promptQueueRunMatchesThreadIds(run, targetIds)) {
+ return run;
+ }
+ }
+ return null;
+}
+
+function findPromptQueueRunByItemId(itemId: string) {
+ for (const run of promptQueueRuns.values()) {
+ const itemIndex = run.items.findIndex((item) => item.id === itemId);
+ if (itemIndex >= 0) {
+ return { run, itemIndex, item: run.items[itemIndex] };
+ }
+ }
+ return null;
+}
+
+function findPromptQueueRunByThreadIds(threadIds: string[]) {
+ if (threadIds.length === 0) {
+ return null;
+ }
+ for (const run of promptQueueRuns.values()) {
+ if (promptQueueRunMatchesThreadIds(run, threadIds)) {
+ return run;
+ }
+ }
+ return null;
+}
+
function findPromptQueueEntry(
state: PromptQueueUIState,
threadIds: string[],
@@ -437,15 +695,48 @@ function canRemovePromptQueueItem(item: PromptQueueItem) {
return !item.dispatched;
}
-function promptQueueItemMatchesThreadIds(
- item: PromptQueueUIItem,
- threadIds: string[],
-) {
- return item.threadIds.some((threadId) => threadIds.includes(threadId));
+function getPromptQueueRunProgress(run: PromptQueueRun) {
+ const activeItemIndex = Math.max(run.index, 0);
+ const total = run.items.length;
+ const current = run.index >= 0 ? Math.min(activeItemIndex + 1, total) : 0;
+ return { activeItemIndex, current, total };
+}
+
+function getPromptQueueItemStatus(
+ run: PromptQueueRun,
+ index: number,
+ activeItemIndex: number,
+): PromptQueueUIItemStatus {
+ if (run.index >= 0 && index === activeItemIndex) {
+ return run.waitingForTargetIdle ? "waiting" : "next";
+ }
+ return "queued";
+}
+
+function getPromptQueueUIItemsForRun(run: PromptQueueRun) {
+ const { activeItemIndex, total } = getPromptQueueRunProgress(run);
+ const items: PromptQueueUIItem[] = [];
+ for (const [index, item] of run.items.entries()) {
+ if (index < activeItemIndex || item.dispatched) {
+ continue;
+ }
+ items.push({
+ id: item.id,
+ runId: run.id,
+ prompt: item.prompt,
+ position: index + 1,
+ total,
+ status: getPromptQueueItemStatus(run, index, activeItemIndex),
+ threadIds: getPromptQueueTargetIds(item.target),
+ canEdit: canEditPromptQueueItem(item),
+ canRemove: canRemovePromptQueueItem(item),
+ });
+ }
+ return items;
}
function syncPromptQueueUI() {
- if (!promptQueueIsRunning || promptQueueItems.length === 0) {
+ if (promptQueueRuns.size === 0) {
usePromptQueueUI.setState({
byThreadId: {},
current: 0,
@@ -456,81 +747,33 @@ function syncPromptQueueUI() {
return;
}
- const activeItemIndex = Math.max(promptQueueIndex, 0);
- const total = promptQueueItems.length;
- const current = promptQueueIndex >= 0 ? Math.min(activeItemIndex + 1, total) : 0;
- const items = promptQueueItems
- .map((item, index): PromptQueueUIItem | null => {
- if (index < activeItemIndex || item.dispatched) {
- return null;
- }
- const threadIds = getPromptQueueTargetIds(item.target);
- const isActive = promptQueueIndex >= 0 && index === activeItemIndex;
- const status: PromptQueueUIItemStatus = item.dispatched
- ? "running"
- : isActive
- ? promptQueueWaitingForTargetIdle
- ? "waiting"
- : "next"
- : "queued";
- return {
- id: item.id,
- prompt: item.prompt,
- position: index + 1,
- total,
- status,
- threadIds,
- canEdit: canEditPromptQueueItem(item),
- canRemove: canRemovePromptQueueItem(item),
- };
- })
- .filter((item): item is PromptQueueUIItem => Boolean(item));
- const groups: Array<{
- ids: Set<string>;
- current: number;
- total: number;
- active: boolean;
- }> = [];
-
- for (const [index, item] of promptQueueItems.entries()) {
- const ids = getPromptQueueTargetIds(item.target);
- if (ids.length === 0) {
- continue;
- }
- let group = groups.find((candidate) =>
- ids.some((id) => candidate.ids.has(id)),
- );
- if (!group) {
- group = {
- ids: new Set<string>(),
- current: 0,
- total: 0,
- active: false,
- };
- groups.push(group);
- }
- ids.forEach((id) => group.ids.add(id));
- group.total += 1;
- if (promptQueueIndex >= 0 && index <= promptQueueIndex) {
- group.current += 1;
- }
- if (index === activeItemIndex) {
- group.active = true;
- }
- }
-
+ const items: PromptQueueUIItem[] = [];
const byThreadId: Record<string, PromptQueueUIEntry> = {};
- for (const group of groups) {
- if (!group.active && group.current >= group.total) {
+ let current = 0;
+ let total = 0;
+
+ for (const run of promptQueueRuns.values()) {
+ const { current: runCurrent, total: runTotal } =
+ getPromptQueueRunProgress(run);
+ current += runCurrent;
+ total += runTotal;
+ items.push(...getPromptQueueUIItemsForRun(run));
+
+ const ids = getPromptQueueRunTargetIds(run);
+ if (ids.length === 0) {
continue;
}
const entry = {
- current: Math.min(group.current, group.total),
- total: group.total,
+ runId: run.id,
+ current: runCurrent,
+ total: runTotal,
+ local: promptQueueRunUsesLocalModel(run),
+ temporary: promptQueueRunIsTemporary(run),
+ dispatched: Boolean(getActivePromptQueueItem(run)?.dispatched),
};
- group.ids.forEach((id) => {
+ for (const id of ids) {
byThreadId[id] = entry;
- });
+ }
}
usePromptQueueUI.setState({
@@ -547,13 +790,11 @@ function editPromptQueueItem(itemId: string, prompt: string) {
if (!nextPrompt) {
return false;
}
- const itemIndex = promptQueueItems.findIndex(
- (candidate) => candidate.id === itemId,
- );
- if (itemIndex < 0) {
+ const match = findPromptQueueRunByItemId(itemId);
+ if (!match) {
return false;
}
- const item = promptQueueItems[itemIndex];
+ const { item } = match;
if (!canEditPromptQueueItem(item)) {
return false;
}
@@ -562,48 +803,41 @@ function editPromptQueueItem(itemId: string, prompt: string) {
return true;
}
-function clearPromptQueueRetryTimer() {
- if (!promptQueueRetryTimer) {
- return;
- }
- clearTimeout(promptQueueRetryTimer);
- promptQueueRetryTimer = null;
-}
-
function removePromptQueueItem(itemId: string) {
- const itemIndex = promptQueueItems.findIndex((item) => item.id === itemId);
- if (itemIndex < 0) {
+ const match = findPromptQueueRunByItemId(itemId);
+ if (!match) {
return false;
}
- const item = promptQueueItems[itemIndex];
+ const { run, itemIndex, item } = match;
if (!canRemovePromptQueueItem(item)) {
return false;
}
- const wasActive =
- promptQueueIndex >= 0 && itemIndex === Math.max(promptQueueIndex, 0);
- promptQueueItems.splice(itemIndex, 1);
- if (promptQueueItems.length === 0) {
- resetPromptQueue();
+ const wasActive = itemIndex === Math.max(run.index, 0);
+ run.items.splice(itemIndex, 1);
+ if (run.items.length === 0) {
+ deletePromptQueueRun(run);
return true;
}
- if (itemIndex < promptQueueIndex) {
- promptQueueIndex -= 1;
+ if (itemIndex < run.index) {
+ run.index -= 1;
}
- if (wasActive && promptQueueIndex >= promptQueueItems.length) {
- resetPromptQueue();
+ if (wasActive && run.index >= run.items.length) {
+ deletePromptQueueRun(run);
return true;
}
syncPromptQueueUI();
if (wasActive) {
- clearPromptQueueRetryTimer();
- promptQueueWaitingForTargetIdle = false;
- promptQueuePrevStoreRunning = false;
- const next = promptQueueItems[promptQueueIndex];
+ clearPromptQueueRetryTimer(run);
+ if (run.index < 0 || run.waitingForTargetIdle) {
+ return true;
+ }
+ run.prevStoreRunning = false;
+ const next = run.items[run.index];
if (next) {
- scheduleQueuedPromptDispatch(next, 50);
+ scheduleQueuedPromptDispatch(run, next, 50);
}
}
return true;
@@ -613,6 +847,17 @@ function isPromptQueueTargetRunning(
target: PromptQueueTarget,
runningByThreadId: Record<string, boolean>,
) {
+ // assistant-ui marks a run synchronously when append starts, while the
+ // shared store is set later after model loading and request validation.
+ // Reading the target closes the rapid-submit window where another append
+ // would otherwise cancel the run that just started.
+ try {
+ if (target.isRunning()) {
+ return true;
+ }
+ } catch {
+ // Fall back to the shared store if the thread runtime is remounting.
+ }
const runningIds = Object.keys(runningByThreadId);
if (runningIds.length === 0) {
return false;
@@ -620,78 +865,138 @@ function isPromptQueueTargetRunning(
const targetIds = target.getRunningThreadIds();
if (targetIds.length === 0) {
- return runningIds.length > 0;
+ // Never borrow another chat's running state. A queue without a resolved
+ // target should retry its own dispatch instead of becoming globally gated.
+ return false;
}
return runningIds.some((threadId) => targetIds.includes(threadId));
}
-function isActivePromptQueueTargetRunning(
+function isPromptQueueRunTargetRunning(
+ run: PromptQueueRun,
runningByThreadId: Record<string, boolean>,
) {
- const activeItem = promptQueueItems[Math.max(promptQueueIndex, 0)];
+ const activeItem = getActivePromptQueueItem(run);
if (!activeItem) {
return false;
}
return isPromptQueueTargetRunning(activeItem.target, runningByThreadId);
}
-function advancePromptQueue() {
- const nextIndex = promptQueueIndex + 1;
- if (nextIndex >= promptQueueItems.length) {
- resetPromptQueue();
+function advancePromptQueue(run: PromptQueueRun) {
+ clearPromptQueueRetryTimer(run);
+ promptQueueActiveRunIds.delete(run.id);
+ getActivePromptQueueItem(run)?.target.complete();
+ const nextIndex = run.index + 1;
+ if (nextIndex >= run.items.length) {
+ deletePromptQueueRun(run);
return;
}
- promptQueueIndex = nextIndex;
+ run.index = nextIndex;
+ run.waitingForTargetIdle = false;
+ run.prevStoreRunning = false;
syncPromptQueueUI();
- const next = promptQueueItems[nextIndex];
- promptQueueWaitingForTargetIdle = false;
- promptQueuePrevStoreRunning = false;
- scheduleQueuedPromptDispatch(next, 100);
+ requestPromptQueuePump(100);
+}
+
+function shouldPollPromptQueueTargetState(run: PromptQueueRun) {
+ return (
+ run.waitingForTargetIdle ||
+ run.index < 0 ||
+ Boolean(getActivePromptQueueItem(run)?.dispatched)
+ );
}
-function startPromptQueueSubscription() {
- const wasWaitingForRun = promptQueuePrevStoreRunning;
- stopPromptQueueSubscription({ resetRunningState: false });
- promptQueuePrevStoreRunning = wasWaitingForRun;
+function schedulePromptQueueTargetStatePoll(run: PromptQueueRun) {
+ const isWaitingForTargetState = shouldPollPromptQueueTargetState(run);
+ if (run.retryTimer || !isWaitingForTargetState) {
+ return;
+ }
+ const generation = run.generation;
+ run.retryTimer = setTimeout(() => {
+ run.retryTimer = null;
+ if (
+ promptQueueRuns.get(run.id) !== run ||
+ generation !== run.generation ||
+ !shouldPollPromptQueueTargetState(run)
+ ) {
+ return;
+ }
+ handlePromptQueueRunState(
+ run,
+ useChatRuntimeStore.getState().runningByThreadId,
+ );
+ if (
+ promptQueueRuns.get(run.id) === run &&
+ shouldPollPromptQueueTargetState(run)
+ ) {
+ schedulePromptQueueTargetStatePoll(run);
+ }
+ }, PROMPT_QUEUE_TARGET_STATE_POLL_MS);
+}
+
+function getRunningThreadCount(runningByThreadId: Record<string, boolean>) {
+ return Object.values(runningByThreadId).filter(Boolean).length;
+}
+
+function hasReadyPromptQueueRun() {
+ return Array.from(promptQueueRuns.values()).some(
+ isPromptQueueRunReadyToDispatch,
+ );
+}
+
+function handlePromptQueueRunState(
+ run: PromptQueueRun,
+ runningByThreadId: Record<string, boolean>,
+) {
+ if (!promptQueueRuns.has(run.id)) {
+ return;
+ }
+ const isRunning = isPromptQueueRunTargetRunning(run, runningByThreadId);
+ const wasRunning = run.prevStoreRunning;
+ run.prevStoreRunning = isRunning;
+ if (!wasRunning || isRunning) {
+ return;
+ }
+ if (run.waitingForTargetIdle) {
+ clearPromptQueueRetryTimer(run);
+ run.waitingForTargetIdle = false;
+ const activeItem = run.items[run.index];
+ if (activeItem) {
+ requestPromptQueuePump(50);
+ }
+ return;
+ }
+ advancePromptQueue(run);
+ requestPromptQueuePump();
+}
+
+function ensurePromptQueueSubscription() {
+ if (promptQueueStoreUnsub) {
+ return;
+ }
// runningByThreadId tracks the actual thread (not aui.thread()), so detection
// survives navigation.
+ let previousRunningCount = getRunningThreadCount(
+ useChatRuntimeStore.getState().runningByThreadId,
+ );
+
promptQueueStoreUnsub = useChatRuntimeStore.subscribe((state) => {
- if (!promptQueueIsRunning) {
+ if (promptQueueRuns.size === 0) {
stopPromptQueueSubscription();
return;
}
- const isRunning = isActivePromptQueueTargetRunning(state.runningByThreadId);
- const wasRunning = promptQueuePrevStoreRunning;
- promptQueuePrevStoreRunning = isRunning;
- if (wasRunning && !isRunning) {
- if (promptQueueWaitingForTargetIdle) {
- promptQueueWaitingForTargetIdle = false;
- const activeItem = promptQueueItems[promptQueueIndex];
- if (activeItem) {
- scheduleQueuedPromptDispatch(activeItem, 50);
- }
- return;
- }
- advancePromptQueue();
+ const nextRunningCount = getRunningThreadCount(state.runningByThreadId);
+ for (const run of Array.from(promptQueueRuns.values())) {
+ handlePromptQueueRunState(run, state.runningByThreadId);
}
- });
- const isRunningNow = isActivePromptQueueTargetRunning(
- useChatRuntimeStore.getState().runningByThreadId,
- );
- if (promptQueuePrevStoreRunning && !isRunningNow) {
- promptQueuePrevStoreRunning = false;
- if (promptQueueWaitingForTargetIdle) {
- promptQueueWaitingForTargetIdle = false;
- const activeItem = promptQueueItems[promptQueueIndex];
- if (activeItem) {
- scheduleQueuedPromptDispatch(activeItem, 50);
- }
- return;
+ if (nextRunningCount < previousRunningCount && hasReadyPromptQueueRun()) {
+ requestPromptQueuePump();
}
- advancePromptQueue();
- }
+ previousRunningCount = nextRunningCount;
+ });
}
function startPromptQueue(
@@ -704,11 +1009,16 @@ function startPromptQueue(
return;
}
- if (promptQueueIsRunning) {
- promptQueueItems.push(
+ const existingRun = findPromptQueueRunByTarget(target);
+ if (existingRun) {
+ if (existingRun.deepResearchConsumed) {
+ target.consumeDeepResearch();
+ }
+ existingRun.items.push(
...filtered.map((prompt) => createQueuedPrompt(prompt, target)),
);
syncPromptQueueUI();
+ requestPromptQueuePump();
return;
}
@@ -716,52 +1026,263 @@ function startPromptQueue(
const shouldWaitForCurrentRun =
waitForCurrentRun &&
isPromptQueueTargetRunning(target, runningByThreadId);
- promptQueueGeneration += 1;
- promptQueueItems = filtered.map((prompt) =>
- createQueuedPrompt(prompt, target),
- );
- promptQueueIndex = shouldWaitForCurrentRun ? -1 : 0;
- promptQueueIsRunning = true;
- promptQueuePrevStoreRunning = shouldWaitForCurrentRun;
+ const run: PromptQueueRun = {
+ id: createPromptQueueRunId(),
+ items: filtered.map((prompt) => createQueuedPrompt(prompt, target)),
+ index: shouldWaitForCurrentRun ? -1 : 0,
+ generation: 0,
+ prevStoreRunning: shouldWaitForCurrentRun,
+ waitingForTargetIdle: false,
+ retryTimer: null,
+ deepResearchConsumed: false,
+ };
+ promptQueueRuns.set(run.id, run);
+ promptQueueRunOrder.push(run.id);
+ syncPromptQueueUI();
+ ensurePromptQueueSubscription();
+ if (shouldWaitForCurrentRun) {
+ handlePromptQueueRunState(
+ run,
+ useChatRuntimeStore.getState().runningByThreadId,
+ );
+ schedulePromptQueueTargetStatePoll(run);
+ } else {
+ requestPromptQueuePump(50);
+ }
+}
+
+function getPromptQueueRunsForThreadIds(threadIds?: string[]) {
+ if (!threadIds || threadIds.length === 0) {
+ return Array.from(promptQueueRuns.values());
+ }
+
+ const runs = new Set<PromptQueueRun>();
+ for (const id of compactIds(threadIds)) {
+ const run = findPromptQueueRunByThreadIds([id]);
+ if (run) {
+ runs.add(run);
+ }
+ }
+ return Array.from(runs);
+}
+
+function stopPromptQueueRun(threadIds?: string[]) {
+ for (const run of getPromptQueueRunsForThreadIds(threadIds)) {
+ const activeItem = getActivePromptQueueItem(run);
+ const activeTarget = activeItem?.target;
+ const shouldCancelActiveRun = Boolean(activeItem?.dispatched);
+ deletePromptQueueRun(run);
+ if (!shouldCancelActiveRun) {
+ continue;
+ }
+ try {
+ activeTarget?.cancel();
+ } catch {
+ // The active run may have already ended.
+ }
+ }
+ requestPromptQueuePumpIfReady();
+}
+
+function stopPromptQueueRunForThreadIds(threadIds: string[]) {
+ stopPromptQueueRun(threadIds);
+}
+
+function waitForPromptQueueTargetIdle(run: PromptQueueRun) {
+ clearPromptQueueRetryTimer(run);
+ promptQueueActiveRunIds.delete(run.id);
+ run.waitingForTargetIdle = true;
+ run.prevStoreRunning = true;
syncPromptQueueUI();
- startPromptQueueSubscription();
- if (!shouldWaitForCurrentRun) {
- const first = promptQueueItems[0];
- if (first) {
- scheduleQueuedPromptDispatch(first, 50);
+ ensurePromptQueueSubscription();
+}
+
+function refreshPromptQueueTargetIdleWait(run: PromptQueueRun) {
+ handlePromptQueueRunState(
+ run,
+ useChatRuntimeStore.getState().runningByThreadId,
+ );
+ schedulePromptQueueTargetStatePoll(run);
+}
+
+function stopLocalPromptQueueRun(run: PromptQueueRun) {
+ const activeItem = getActivePromptQueueItem(run);
+ const plan = planLocalPromptQueueStop(
+ run.items.map((item) => ({
+ usesLocalModel: item.target.usesLocalModel,
+ dispatched: item.dispatched,
+ })),
+ run.index,
+ );
+ if (plan.retainedItemIndexes.length === run.items.length) {
+ return;
+ }
+
+ run.items = plan.retainedItemIndexes.map((index) => run.items[index]);
+ if (!getActivePromptQueueItem(run)) {
+ deletePromptQueueRun(run);
+ if (!plan.cancelActiveItem) {
+ return;
+ }
+ try {
+ activeItem?.target.cancel();
+ } catch {
+ // The active local run may have already ended.
}
+ return;
+ }
+ if (plan.activeItemRemoved) {
+ clearPromptQueueRetryTimer(run);
+ }
+ if (plan.cancelActiveItem) {
+ waitForPromptQueueTargetIdle(run);
+ try {
+ activeItem?.target.cancel();
+ } catch {
+ // The active local run may have already ended.
+ }
+ refreshPromptQueueTargetIdleWait(run);
+ return;
+ }
+ syncPromptQueueUI();
+ if (plan.refreshTargetIdleWait) {
+ refreshPromptQueueTargetIdleWait(run);
+ return;
+ }
+ if (plan.activeItemRemoved && run.index >= 0 && !run.waitingForTargetIdle) {
+ requestPromptQueuePump(50);
}
}
-function stopPromptQueueRun(cancelActiveRun = true) {
- const activeItem = promptQueueItems[Math.max(promptQueueIndex, 0)];
- const activeTarget = activeItem?.target;
- const shouldCancelActiveRun = cancelActiveRun && Boolean(activeItem?.dispatched);
- resetPromptQueue();
- if (!shouldCancelActiveRun) {
+function stopLocalPromptQueueRunsForThreadIds(threadIds: string[]) {
+ if (threadIds.length === 0) {
return;
}
- try {
- activeTarget.cancel();
- } catch {
- // The active run may have already ended.
+ for (const run of getPromptQueueRunsForThreadIds(threadIds)) {
+ stopLocalPromptQueueRun(run);
}
+ requestPromptQueuePumpIfReady();
+}
+
+function retainPendingPromptQueueItemsAfterFailure(run: PromptQueueRun) {
+ const activeIndex = Math.max(run.index, 0);
+ const activeItem = run.items[activeIndex];
+ if (run.index < 0 || !activeItem?.dispatched) {
+ return false;
+ }
+
+ activeItem.target.complete();
+ run.items.splice(activeIndex, 1);
+ if (!getActivePromptQueueItem(run)) {
+ deletePromptQueueRun(run);
+ return true;
+ }
+ waitForPromptQueueTargetIdle(run);
+ refreshPromptQueueTargetIdleWait(run);
+ return true;
+}
+
+function cancelPendingPromptQueueFactoriesForStop<
+ T extends { temporary: boolean; cancelled: boolean },
+>(
+ pendingFactories: Map<string, T>,
+ aliases: string[],
+ detail: PromptQueueStopEventDetail,
+) {
+ const { threadIds, temporaryOnly, localOnly } = detail;
+ if (localOnly) {
+ // Advancing the model boundary invalidates local factories once hydrated.
+ // External factories must remain intact.
+ return;
+ }
+ if (
+ threadIds &&
+ threadIds.length > 0 &&
+ !threadIds.some((threadId) => aliases.includes(threadId))
+ ) {
+ return;
+ }
+ for (const [key, reservation] of pendingFactories) {
+ if (temporaryOnly && !reservation.temporary) {
+ continue;
+ }
+ reservation.cancelled = true;
+ pendingFactories.delete(key);
+ }
+}
+
+function stopAllPromptQueueRuns() {
+ const activeRuns = Array.from(promptQueueRuns.values()).map((run) => ({
+ activeItem: getActivePromptQueueItem(run),
+ }));
+ resetPromptQueues();
+ for (const { activeItem } of activeRuns) {
+ const activeTarget = activeItem?.target;
+ const shouldCancelActiveRun = Boolean(activeItem?.dispatched);
+ if (!shouldCancelActiveRun) {
+ continue;
+ }
+ try {
+ activeTarget?.cancel();
+ } catch {
+ // The active run may have already ended.
+ }
+ }
+}
+
+function handlePromptQueueRunFailed(threadId?: string | null) {
+ 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.
+ discardQueuedChatRunSettingsForThread(threadId);
+ deletePromptQueueRun(failedRun);
+ }
+ } else {
+ discardQueuedChatRunSettingsForThread(threadId);
+ }
+ }
+ // A queued adapter can fail validation before its running flag turns on.
+ // Pump every other ready queue even when no active run matches the event.
+ requestPromptQueuePumpIfReady();
}
if (typeof window !== "undefined") {
window.addEventListener(PROMPT_QUEUE_STOP_EVENT, (event) => {
- // Navigation leaves the dispatched prompt streaming; an explicit stop cancels it too.
- const detail = (event as CustomEvent<{ cancelActiveRun?: boolean }>).detail;
- stopPromptQueueRun(detail?.cancelActiveRun ?? true);
+ const { threadIds, temporaryOnly, localOnly } =
+ (event as CustomEvent<PromptQueueStopEventDetail>).detail ?? {};
+ if (localOnly) {
+ stopLocalPromptQueueRunsForThreadIds(threadIds ?? []);
+ return;
+ }
+ if (threadIds && threadIds.length > 0) {
+ stopPromptQueueRunForThreadIds(threadIds);
+ return;
+ }
+ if (temporaryOnly) {
+ return;
+ }
+ stopAllPromptQueueRuns();
+ });
+ window.addEventListener(PROMPT_QUEUE_RUN_FAILED_EVENT, (event) => {
+ const { threadId } =
+ (event as CustomEvent<PromptQueueRunFailedEventDetail>).detail ?? {};
+ handlePromptQueueRunFailed(threadId);
});
}
interface PromptQueueCallbacks {
- startQueue: (items: string[], waitForCurrentRun?: boolean) => void;
+ startQueue: (
+ items: string[],
+ waitForCurrentRun?: boolean,
+ onAborted?: () => void,
+ ) => boolean;
stopQueue: () => void;
}
const noopStartPromptQueue: PromptQueueCallbacks["startQueue"] = () =>
- undefined;
+ false;
const noopStopPromptQueue: PromptQueueCallbacks["stopQueue"] = () => undefined;
const PromptQueueContext = createContext<PromptQueueCallbacks>({
startQueue: noopStartPromptQueue,
@@ -1214,11 +1735,12 @@ const ThreadComposerDock: FC<{
activeThreadId,
]);
const queueVisible = usePromptQueueUI(
- (s) =>
- Boolean(findPromptQueueEntry(s, promptQueueThreadIds)) &&
- s.items.some((item) =>
- promptQueueItemMatchesThreadIds(item, promptQueueThreadIds),
- ),
+ (s) => {
+ const entry = findPromptQueueEntry(s, promptQueueThreadIds);
+ return Boolean(
+ entry && s.items.some((item) => item.runId === entry.runId),
+ );
+ },
);
const showModelDisclaimer = useChatPreferencesStore(
(s) => s.showModelDisclaimer,
@@ -1612,15 +2134,24 @@ const Composer: FC<{
threadListItemRemoteId,
threadId,
]);
- const promptQueueActive = usePromptQueueUI((s) =>
- Boolean(findPromptQueueEntry(s, promptQueueThreadIds)),
- );
+ const preStreamThreadIds = compactIds([
+ ...promptQueueThreadIds,
+ referenceThreadId,
+ ]);
+ const preStreamRunReservationRef = useRef<symbol | null>(null);
useEffect(() => {
- if (threadId != null || activeThreadId != null) {
+ const token = preStreamRunReservationRef.current;
+ if (!token) {
return;
}
- stopPromptQueueRun();
- }, [activeThreadId, threadId]);
+ adoptPreStreamRunReservation(token, preStreamThreadIds);
+ // Keep the reservation until the adapter consumes or fails it. React can
+ // expose isRunning before persistence and model preflight finish; releasing
+ // here would hide that accepted send from a concurrent model-change gate.
+ }, [preStreamThreadIds]);
+ const promptQueueActive = usePromptQueueUI((s) =>
+ Boolean(findPromptQueueEntry(s, promptQueueThreadIds)),
+ );
const hasSendableContent =
composerText.trim().length > 0 || hasAttachments || hasPendingAudio;
const canQueueCurrentPrompt =
@@ -1724,6 +2255,46 @@ const Composer: FC<{
// retrieval covers all of them.
const [indexingActive, setIndexingActive] = useState(false);
const indexingActiveRef = useRef(false);
+ const promptQueueTargetMountedRef = useRef(true);
+ const promptQueueStartPendingRef = useRef(
+ new Map<
+ string,
+ {
+ temporary: boolean;
+ cancelled: boolean;
+ localModelBoundaryGeneration: number;
+ queuedSettingsEpoch: number;
+ }
+ >(),
+ );
+ useEffect(() => {
+ promptQueueTargetMountedRef.current = true;
+ return () => {
+ promptQueueTargetMountedRef.current = false;
+ };
+ }, []);
+ useEffect(() => {
+ const cancelPendingQueueFactories = (event: Event) => {
+ const detail =
+ (event as CustomEvent<PromptQueueStopEventDetail>).detail ?? {};
+ const state = aui.threadListItem().getState();
+ cancelPendingPromptQueueFactoriesForStop(
+ promptQueueStartPendingRef.current,
+ compactIds([state.id, state.remoteId, referenceThreadId]),
+ detail,
+ );
+ };
+ window.addEventListener(
+ PROMPT_QUEUE_STOP_EVENT,
+ cancelPendingQueueFactories,
+ );
+ return () => {
+ window.removeEventListener(
+ PROMPT_QUEUE_STOP_EVENT,
+ cancelPendingQueueFactories,
+ );
+ };
+ }, [aui, referenceThreadId]);
const [pendingSend, setPendingSend] = useState(false);
const pendingSendRef = useRef(false);
const waitToastRef = useRef<string | number | null>(null);
@@ -1733,10 +2304,9 @@ const Composer: FC<{
setIndexingActive(active);
}, []);
- const createPromptQueueTarget = useCallback((): PromptQueueTarget => {
- const thread = aui.thread();
- const threadListItem = aui.threadListItem();
- const initialState = threadListItem.getState();
+ const createPromptQueueTarget = useCallback(async (): Promise<PromptQueueTarget | null> => {
+ const assistantRuntime = aui.threads().__internal_getAssistantRuntime?.();
+ const initialState = aui.threadListItem().getState();
const initialRunningThreadIds = [
initialState.id,
initialState.remoteId,
@@ -1744,32 +2314,315 @@ const Composer: FC<{
].filter((id): id is string => Boolean(id));
const initialDocumentThreadId =
initialState.remoteId ?? referenceThreadId ?? null;
+ const historyClearGeneration = chatHistoryClearBoundary.capture();
+ await useChatRuntimeStore.getState().hydratePersistedSettings();
+ if (
+ !promptQueueTargetMountedRef.current ||
+ chatHistoryClearBoundary.capture() !== historyClearGeneration
+ ) {
+ return null;
+ }
+ const currentState = aui.threadListItem().getState();
+ if (
+ !compactIds([currentState.id, currentState.remoteId]).some((id) =>
+ initialRunningThreadIds.includes(id),
+ )
+ ) {
+ return null;
+ }
+ const chatStateAtQueueStart = useChatRuntimeStore.getState();
+ const incognitoAtQueueStart = chatStateAtQueueStart.incognito;
+ const usesThreadDocumentsAtQueueStart =
+ chatStateAtQueueStart.ragEnabled &&
+ chatStateAtQueueStart.ragSource.type === "thread";
+ const runSettingsAtQueueStart =
+ snapshotQueuedChatRunSettings(chatStateAtQueueStart);
+ const getThreadListItemState = () => {
+ const runtime =
+ assistantRuntime ?? aui.threads().__internal_getAssistantRuntime?.();
+ if (!runtime) {
+ return null;
+ }
+ for (const id of initialRunningThreadIds) {
+ try {
+ return runtime.threads.getItemById(id).getState();
+ } catch {
+ // Try the next captured id.
+ }
+ }
+ return null;
+ };
+ const getQueueThreadIds = () => {
+ const state = getThreadListItemState();
+ return compactIds([
+ ...initialRunningThreadIds,
+ state?.id,
+ state?.remoteId,
+ ]);
+ };
+ const getThreadRuntime = () => {
+ const runtime =
+ assistantRuntime ?? aui.threads().__internal_getAssistantRuntime?.();
+ if (!runtime) {
+ return null;
+ }
+ for (const id of getQueueThreadIds()) {
+ try {
+ const thread = runtime.threads.getById(id);
+ thread.getState();
+ return thread;
+ } catch {
+ // Try the next captured id.
+ }
+ }
+ return null;
+ };
+ const isTargetCurrentThread = () => {
+ const state = aui.threadListItem().getState();
+ return compactIds([state.id, state.remoteId]).some((id) =>
+ initialRunningThreadIds.includes(id),
+ );
+ };
+ const pendingSettingsIds = new Set<number>();
+ let cancelled = false;
+ let shouldCorrectPersistedModel: boolean | null = null;
+ let initializedFreshThreadId: string | null = null;
+ let freshThreadAppendAccepted = false;
+ const removeFreshThreadPersistedAfterAbort = () => {
+ const historyWasCleared =
+ chatHistoryClearBoundary.capture() !== historyClearGeneration;
+ if (
+ !initializedFreshThreadId ||
+ freshThreadAppendAccepted ||
+ (!cancelled && !historyWasCleared)
+ ) {
+ return false;
+ }
+ // Tombstone synchronously so a late initializer cannot leave an empty
+ // record visible while backend cleanup completes.
+ markChatThreadDeleted(initializedFreshThreadId);
+ void deleteStoredChatThreads([initializedFreshThreadId]).catch(
+ () => undefined,
+ );
+ if (!historyWasCleared && isTargetCurrentThread()) {
+ void Promise.resolve(aui.threads().switchToNewThread()).catch(
+ () => undefined,
+ );
+ }
+ return true;
+ };
+ const discardOldestPendingSettings = () => {
+ const settingsId = pendingSettingsIds.values().next().value;
+ if (settingsId === undefined) {
+ return;
+ }
+ pendingSettingsIds.delete(settingsId);
+ discardQueuedChatRunSettings(settingsId);
+ };
return {
getDocumentThreadId: () => {
- const state = threadListItem.getState();
- return state.remoteId ?? referenceThreadId ?? initialDocumentThreadId;
+ const state = getThreadListItemState();
+ return state?.remoteId ?? referenceThreadId ?? initialDocumentThreadId;
},
getRunningThreadIds: () => {
- const state = threadListItem.getState();
- return Array.from(
- new Set(
- [
- ...initialRunningThreadIds,
- state.id,
- state.remoteId,
- referenceThreadId,
- ].filter((id): id is string => Boolean(id)),
- ),
+ return getQueueThreadIds();
+ },
+ isRunning: () =>
+ hasPreStreamRunReservation(getQueueThreadIds()) ||
+ Boolean(getThreadRuntime()?.getState().isRunning),
+ append: async (prompt) => {
+ const thread = getThreadRuntime();
+ if (!thread) {
+ throw new Error("Prompt queue thread runtime is unavailable");
+ }
+ if (incognitoAtQueueStart) {
+ for (const id of getQueueThreadIds()) {
+ markThreadIncognito(id);
+ }
+ }
+ const settingsId = registerQueuedChatRunSettings(
+ getQueueThreadIds(),
+ {
+ ...runSettingsAtQueueStart,
+ params: { ...runSettingsAtQueueStart.params },
+ },
);
+ pendingSettingsIds.add(settingsId);
+ try {
+ const runtime =
+ assistantRuntime ?? aui.threads().__internal_getAssistantRuntime?.();
+ const state = getThreadListItemState();
+ if (!runtime || !state) {
+ throw new Error("Prompt queue thread item is unavailable");
+ }
+ if (chatHistoryClearBoundary.capture() !== historyClearGeneration) {
+ return;
+ }
+ shouldCorrectPersistedModel ??= !state.remoteId;
+ const initializingFreshThread = !state.remoteId;
+ // A fresh chat receives its remote id during initialization. Await it
+ // before append so the adapter can match the queued settings using
+ // unstable_threadId on its first invocation.
+ const { remoteId } = await runtime.threads
+ .getItemById(state.id)
+ .initialize();
+ if (initializingFreshThread) {
+ initializedFreshThreadId = remoteId;
+ }
+ if (
+ removeFreshThreadPersistedAfterAbort() ||
+ cancelled ||
+ !pendingSettingsIds.has(settingsId)
+ ) {
+ return;
+ }
+ addQueuedChatRunSettingsThreadIds(settingsId, [
+ ...getQueueThreadIds(),
+ remoteId,
+ ]);
+ if (shouldCorrectPersistedModel) {
+ // initialize() persists a fresh thread using the live global model.
+ // Correct that metadata to the model captured for this queued run
+ // before any later navigation or compatibility check can observe it.
+ await updateStoredChatThread(remoteId, {
+ modelId: runSettingsAtQueueStart.params.checkpoint ?? "",
+ });
+ shouldCorrectPersistedModel = false;
+ if (
+ removeFreshThreadPersistedAfterAbort() ||
+ cancelled ||
+ !pendingSettingsIds.has(settingsId)
+ ) {
+ return;
+ }
+ }
+ // Initialization can replace a fresh thread's local id with a remote
+ // id. Refresh queue aliases before the run begins so stop dialogs
+ // deduplicate the two identities.
+ syncPromptQueueUI();
+ const appendResult = thread.append(
+ appendTextToThread(prompt),
+ ) as unknown;
+ freshThreadAppendAccepted = true;
+ // Calling append synchronously accepts the user turn; its promise
+ // follows the whole provider run. Do not turn a later paid/streaming
+ // failure into an automatic duplicate dispatch.
+ if (
+ appendResult &&
+ typeof (appendResult as Promise<void>).catch === "function"
+ ) {
+ void (appendResult as Promise<void>).catch(() => undefined);
+ }
+ } catch (error) {
+ // A setup failure is retryable. Keep the initialized record unless a
+ // concurrent stop or Clear all explicitly invalidated this queue.
+ removeFreshThreadPersistedAfterAbort();
+ pendingSettingsIds.delete(settingsId);
+ discardQueuedChatRunSettings(settingsId);
+ throw error;
+ }
+ },
+ complete: discardOldestPendingSettings,
+ cancel: () => {
+ cancelled = true;
+ removeFreshThreadPersistedAfterAbort();
+ for (const settingsId of pendingSettingsIds) {
+ discardQueuedChatRunSettings(settingsId);
+ }
+ pendingSettingsIds.clear();
+ getThreadRuntime()?.cancelRun();
},
- append: (prompt) => {
- thread.append(appendTextToThread(prompt));
+ isIndexing: () =>
+ promptQueueTargetMountedRef.current &&
+ isTargetCurrentThread() &&
+ indexingActiveRef.current,
+ usesThreadDocuments: usesThreadDocumentsAtQueueStart,
+ usesLocalModel:
+ parseExternalModelId(runSettingsAtQueueStart.params.checkpoint) === null,
+ usesDeepResearch: runSettingsAtQueueStart.deepResearchEnabled,
+ temporary: incognitoAtQueueStart,
+ consumeDeepResearch: () => {
+ runSettingsAtQueueStart.deepResearchEnabled = false;
},
- cancel: () => thread.cancelRun(),
- isIndexing: () => indexingActiveRef.current,
};
}, [aui, referenceThreadId]);
+ const startHydratedPromptQueue = useCallback(
+ (
+ items: string[],
+ waitForCurrentRun = false,
+ onStarted?: () => void,
+ onAborted?: () => void,
+ ) => {
+ const reservationKey = JSON.stringify([
+ referenceThreadId,
+ items,
+ waitForCurrentRun,
+ ]);
+ if (promptQueueStartPendingRef.current.has(reservationKey)) {
+ return false;
+ }
+ const reservation = {
+ temporary: useChatRuntimeStore.getState().incognito,
+ cancelled: false,
+ localModelBoundaryGeneration:
+ localPromptQueueModelBoundary.capture(),
+ queuedSettingsEpoch:
+ useChatRuntimeStore.getState().queuedSettingsEpoch,
+ };
+ promptQueueStartPendingRef.current.set(reservationKey, reservation);
+ void createPromptQueueTarget()
+ .then((target) => {
+ const currentQueueSettings = useChatRuntimeStore.getState();
+ const modelBoundaryInvalidated = target
+ ? shouldAbortPendingQueueForModelBoundary({
+ capturedGeneration:
+ reservation.localModelBoundaryGeneration,
+ usesLocalModel: target.usesLocalModel,
+ modelLoading: currentQueueSettings.modelLoading,
+ })
+ : false;
+ const settingsInvalidated =
+ shouldAbortPendingQueueForSettingsChange({
+ capturedEpoch: reservation.queuedSettingsEpoch,
+ currentEpoch: currentQueueSettings.queuedSettingsEpoch,
+ capturedTemporary: reservation.temporary,
+ currentTemporary: currentQueueSettings.incognito,
+ });
+ if (
+ target &&
+ !reservation.cancelled &&
+ !modelBoundaryInvalidated &&
+ !settingsInvalidated &&
+ promptQueueStartPendingRef.current.get(reservationKey) ===
+ reservation
+ ) {
+ startPromptQueue(items, target, waitForCurrentRun);
+ onStarted?.();
+ } else {
+ onAborted?.();
+ }
+ })
+ .catch((error) => {
+ toast.error("Could not start prompt queue", {
+ description:
+ error instanceof Error ? error.message : "Please try again.",
+ });
+ onAborted?.();
+ })
+ .finally(() => {
+ if (
+ promptQueueStartPendingRef.current.get(reservationKey) ===
+ reservation
+ ) {
+ promptQueueStartPendingRef.current.delete(reservationKey);
+ }
+ });
+ return true;
+ },
+ [createPromptQueueTarget, referenceThreadId],
+ );
+
const dismissWaitToast = useCallback(() => {
if (waitToastRef.current !== null) {
toast.dismiss(waitToastRef.current);
@@ -1801,6 +2654,48 @@ const Composer: FC<{
[hasPendingAttachments, hasSendableContent, isComposingRef],
);
+ const sendReservedComposer = useCallback(() => {
+ const assistantRuntime =
+ aui.threads().__internal_getAssistantRuntime?.();
+ let reservationToken: symbol | null = null;
+ reservationToken = reservePreStreamRun(preStreamThreadIds, {
+ usesLocalModel:
+ parseExternalModelId(
+ useChatRuntimeStore.getState().params.checkpoint,
+ ) === null,
+ cancel: (reservedThreadIds) => {
+ if (preStreamRunReservationRef.current === reservationToken) {
+ preStreamRunReservationRef.current = null;
+ }
+ for (const reservedThreadId of reservedThreadIds) {
+ try {
+ assistantRuntime?.threads.getById(reservedThreadId).cancelRun();
+ return;
+ } catch {
+ // Thread hydration can retire an alias; try the next captured id.
+ }
+ }
+ },
+ });
+ if (!reservationToken) {
+ toast.error("Wait for the current response to finish");
+ return;
+ }
+ preStreamRunReservationRef.current = reservationToken;
+ try {
+ aui.composer().send();
+ } catch (error) {
+ if (releasePreStreamRunReservation(reservationToken)) {
+ notifyPromptQueueRunFailed(referenceThreadId);
+ }
+ preStreamRunReservationRef.current = null;
+ toast.error("Could not prepare attachments", {
+ description:
+ error instanceof Error ? error.message : "Please retry the send.",
+ });
+ }
+ }, [aui, preStreamThreadIds, referenceThreadId]);
+
// Gate for both form submit and the Send button. Returns true when it handled
// the event (blocked or queued) so callers stop.
const interceptSend = useCallback(
@@ -1829,9 +2724,16 @@ const Composer: FC<{
dismissWaitToast();
if (text.trim().length > 0 || attachments.length > 0) {
clearStoredDraft();
- aui.composer().send();
+ sendReservedComposer();
}
- }, [pendingSend, indexingActive, aui, clearStoredDraft, dismissWaitToast]);
+ }, [
+ pendingSend,
+ indexingActive,
+ aui,
+ clearStoredDraft,
+ dismissWaitToast,
+ sendReservedComposer,
+ ]);
// Drop any queued send + toast on unmount (e.g. thread switch).
useEffect(
@@ -1931,7 +2833,10 @@ const Composer: FC<{
}, [isDictating, aui, composerIdentity, dictationBlocked, composerText]);
const handleSubmit = useCallback(
- (event: Parameters<NonNullable<ComponentProps<"form">["onSubmit"]>>[0]) => {
+ (event: {
+ preventDefault: () => void;
+ stopPropagation?: () => void;
+ }) => {
if (isResearchActive) {
event.preventDefault();
return;
@@ -1941,7 +2846,27 @@ const Composer: FC<{
return;
}
- if (threadIsRunning || promptQueueActive) {
+ // React may not have rendered threadIsRunning yet when several submits
+ // arrive immediately after a send. The imperative runtime is already
+ // current, so use it (and the live queue store) for this decision.
+ const liveThreadIsRunning =
+ threadIsRunning || aui.thread().getState().isRunning;
+ const livePromptQueueActive =
+ promptQueueActive ||
+ Boolean(
+ findPromptQueueEntry(
+ usePromptQueueUI.getState(),
+ promptQueueThreadIds,
+ ),
+ );
+ const livePreStreamRunActive =
+ hasPreStreamRunReservation(preStreamThreadIds);
+
+ if (
+ liveThreadIsRunning ||
+ livePromptQueueActive ||
+ livePreStreamRunActive
+ ) {
event.preventDefault();
// Project new-chat composer: never queue, just ask the user to wait.
if (disableQueue) {
@@ -1951,7 +2876,7 @@ const Composer: FC<{
if (!canQueueCurrentPrompt) {
if (overlay || hasAttachments || hasPendingAudio) {
toast.error(
- threadIsRunning
+ liveThreadIsRunning
? "Wait for the current response to finish"
: "Wait for the prompt queue to finish",
{
@@ -1963,14 +2888,18 @@ const Composer: FC<{
return;
}
const queuedPrompt = composerText.trim();
- flushResourcesSync(() => {
- aui.composer().setText("");
- });
- clearStoredDraft();
- startPromptQueue(
+ startHydratedPromptQueue(
[queuedPrompt],
- createPromptQueueTarget(),
- threadIsRunning,
+ liveThreadIsRunning || livePreStreamRunActive,
+ () => {
+ if (aui.composer().getState().text.trim() !== queuedPrompt) {
+ return;
+ }
+ flushResourcesSync(() => {
+ aui.composer().setText("");
+ });
+ clearStoredDraft();
+ },
);
return;
}
@@ -2018,10 +2947,20 @@ const Composer: FC<{
);
});
closeOverlay();
+ event.preventDefault();
+ sendReservedComposer();
return;
}
+ if (hasAttachments || hasPendingAudio) {
+ event.preventDefault();
+ clearStoredDraft();
+ sendReservedComposer();
+ return;
+ }
+ event.preventDefault();
clearStoredDraft();
+ sendReservedComposer();
},
[
aui,
@@ -2029,7 +2968,7 @@ const Composer: FC<{
clearStoredDraft,
closeOverlay,
composerText,
- createPromptQueueTarget,
+ startHydratedPromptQueue,
disabled,
disableQueue,
hasAttachments,
@@ -2038,26 +2977,39 @@ const Composer: FC<{
isResearchActive,
overlay,
promptQueueActive,
+ promptQueueThreadIds,
+ preStreamThreadIds,
referenceThreadId,
setImageToolsEnabled,
setPendingImageEditReference,
+ sendReservedComposer,
shouldBlockSend,
threadIsRunning,
],
);
const stopQueue = useCallback(() => {
- stopPromptQueueRun();
- }, []);
+ stopPromptQueueRunForThreadIds(promptQueueThreadIds);
+ }, [promptQueueThreadIds]);
const startQueue = useCallback(
- (items: string[], waitForCurrentRun = threadIsRunning) => {
+ (
+ items: string[],
+ waitForCurrentRun =
+ threadIsRunning || aui.thread().getState().isRunning,
+ onAborted?: () => void,
+ ) => {
// Saved-prompt Run-list calls this directly, so honour disableQueue here
// too: queuing from the project new-chat composer misbinds the thread.
- if (disableQueue) return;
- startPromptQueue(items, createPromptQueueTarget(), waitForCurrentRun);
+ if (disableQueue) return false;
+ return startHydratedPromptQueue(
+ items,
+ waitForCurrentRun,
+ undefined,
+ onAborted,
+ );
},
- [createPromptQueueTarget, threadIsRunning, disableQueue],
+ [aui, startHydratedPromptQueue, threadIsRunning, disableQueue],
);
const queueContextValue: PromptQueueCallbacks = { startQueue, stopQueue };
@@ -2162,13 +3114,25 @@ const Composer: FC<{
if (queuedPrompt.length === 0) {
return;
}
- flushResourcesSync(() => {
- aui.composer().setText("");
- });
- clearStoredDraft();
- startPromptQueue([queuedPrompt], createPromptQueueTarget(), true);
+ startHydratedPromptQueue(
+ [queuedPrompt],
+ true,
+ () => {
+ if (
+ aui.composer().getState().text.trim() !== queuedPrompt
+ ) {
+ return;
+ }
+ flushResourcesSync(() => {
+ aui.composer().setText("");
+ });
+ clearStoredDraft();
+ },
+ );
}}
- onSendClick={interceptSend}
+ // ComposerPrimitive.Send handles clicks itself rather than
+ // submitting the form, so run the complete queue/capacity path.
+ onSendClick={handleSubmit}
onStopClick={stopQueue}
pendingSend={pendingSend}
menuSide={effectiveMenuSide}
@@ -3319,8 +4283,15 @@ const ComposerToolsMenu: FC<{
aui.composer().setText(text);
}}
onRunList={(items) => {
- setPromptStorageOpen(false);
- startQueue(items);
+ const started = startQueue(items, undefined, () => {
+ setPromptStorageOpen(true);
+ toast.info("Saved list was not queued", {
+ description: "The chat changed before the queue was ready. Try again.",
+ });
+ });
+ if (started) {
+ setPromptStorageOpen(false);
+ }
}}
/>
<DropdownMenu
@@ -3501,11 +4472,10 @@ const PromptQueueStack: FC<{ queueThreadIds: string[] }> = ({
const [editingItemId, setEditingItemId] = useState<string | null>(null);
const [draftPrompt, setDraftPrompt] = useState("");
const editInputRef = useRef<HTMLTextAreaElement>(null);
- const visibleItems = items.filter((item) =>
- promptQueueItemMatchesThreadIds(item, queueThreadIds),
- );
+ const visibleItems = queueEntry
+ ? items.filter((item) => item.runId === queueEntry.runId)
+ : [];
const editingItem = visibleItems.find((item) => item.id === editingItemId);
- const editingItemCanEdit = editingItem?.canEdit ?? false;
const activeEditingItemId = editingItem ? editingItemId : null;
useEffect(() => {
@@ -3516,14 +4486,6 @@ const PromptQueueStack: FC<{ queueThreadIds: string[] }> = ({
editInputRef.current?.select();
}, [activeEditingItemId]);
- useEffect(() => {
- if (!editingItemId || editingItemCanEdit) {
- return;
- }
- setEditingItemId(null);
- setDraftPrompt("");
- }, [editingItemCanEdit, editingItemId]);
-
if (!queueEntry || visibleItems.length === 0) {
return null;
}
@@ -3790,19 +4752,32 @@ const ComposerRightControls: FC<{
</AuiIf>
{isQueueRunning && !isResearchActive ? (
<AuiIf condition={({ thread }) => !thread.isRunning}>
- <TooltipIconButton
- tooltip="Queue message"
- side="bottom"
- type="button"
- variant="default"
- size="icon"
- disabled={disabled || queueDisabled}
- onClick={onQueueClick}
- className="aui-composer-send ml-1.5 size-9 rounded-full"
- aria-label="Queue message"
- >
- <ArrowUpIcon className="unsloth-send-icon aui-composer-send-icon size-[21px] stroke-2" />
- </TooltipIconButton>
+ {queueEntry?.dispatched ? (
+ <Button
+ type="button"
+ variant="default"
+ size="icon"
+ className="aui-composer-cancel ml-1.5 size-9 rounded-full"
+ aria-label="Stop queued message"
+ onClick={stop}
+ >
+ <SquareIcon className="aui-composer-cancel-icon size-3 fill-current" />
+ </Button>
+ ) : (
+ <TooltipIconButton
+ tooltip="Queue message"
+ side="bottom"
+ type="button"
+ variant="default"
+ size="icon"
+ disabled={disabled || queueDisabled}
+ onClick={onQueueClick}
+ className="aui-composer-send ml-1.5 size-9 rounded-full"
+ aria-label="Queue message"
+ >
+ <ArrowUpIcon className="unsloth-send-icon aui-composer-send-icon size-[21px] stroke-2" />
+ </TooltipIconButton>
+ )}
</AuiIf>
) : null}
{isResearchActive ? (
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index e1d6ece5f12..fb0116e3234 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -8,12 +8,29 @@ import { projectHasSources } from "@/features/rag/api/rag-api";
import { apiUrl } from "@/lib/api-base";
import { parseParamCountB } from "@/lib/model-size";
import { createLoadingToastIcon, toast } from "@/lib/toast";
+import { notifyPromptQueueRunFailed } from "../utils/prompt-queue-boundary";
+import {
+ adoptPreStreamRunReservation,
+ findPreStreamRunReservation,
+ preStreamRunThreadIdsForAdapter,
+ releasePreStreamRunForThreadIds,
+ releasePreStreamRunReservation,
+} from "../utils/pre-stream-run-reservation";
+import {
+ consumeQueuedChatRunSettings,
+ snapshotQueuedChatRunSettings,
+} from "../utils/queued-chat-run-settings";
+import {
+ mergeQueuedModelCapabilities,
+ type QueuedModelCapabilities,
+} from "../utils/queued-model-capabilities";
import type { MessageTiming, ToolCallMessagePart } from "@assistant-ui/core";
import type { ChatModelAdapter } from "@assistant-ui/react";
import { parsePartialJsonObject } from "assistant-stream/utils";
import {
getExternalProviderApiKey,
isCustomProviderType,
+ isExternalModelId,
isPromptCacheTtl,
loadExternalProviders,
parseExternalModelId,
@@ -25,6 +42,7 @@ import {
import { pickFriendlyContainerName } from "../lib/friendly-names";
import {
reasoningCapsFromLoad,
+ resolveInferenceCheckpointId,
tryAdoptServerActiveModel,
} from "../lib/apply-inference-status-to-store";
import { syncModelCapabilities } from "../hooks/use-chat-model-runtime";
@@ -102,6 +120,7 @@ import {
generateAudio,
GenerationLengthError,
fetchGgufStagedMetadata,
+ getInferenceStatus,
listCachedGguf,
listCachedModels,
listGgufVariants,
@@ -1255,6 +1274,7 @@ export function messagesContainImage(messages: RunMessages): boolean {
export function findLatestUserAudioBase64(
messages: RunMessages,
+ includePendingAudio = true,
): string | undefined {
for (let i = messages.length - 1; i >= 0; i -= 1) {
const message = messages[i];
@@ -1285,7 +1305,9 @@ export function findLatestUserAudioBase64(
}
// Runtime store (main composer's audio upload).
- const pendingAudio = useChatRuntimeStore.getState().pendingAudioBase64;
+ const pendingAudio = includePendingAudio
+ ? useChatRuntimeStore.getState().pendingAudioBase64
+ : null;
return pendingAudio ?? undefined;
}
@@ -1661,6 +1683,174 @@ function isAutoLoadableGgufVariant(variant: GgufVariantDetail | null): boolean {
return !hasBigEndianGgufMarker(filename, variant.quant);
}
+type QueuedResolvedModelRuntime = {
+ checkpoint: string;
+ supportsTools: boolean;
+ supportsReasoning: boolean;
+ reasoningAlwaysOn: boolean;
+ reasoningStyle: ReturnType<typeof reasoningCapsFromLoad>["reasoningStyle"];
+ supportsReasoningOff: boolean;
+ reasoningEffortLevels: ReturnType<
+ typeof reasoningCapsFromLoad
+ >["reasoningEffortLevels"];
+ supportsPreserveThinking: boolean;
+ ggufContextLength: number | null;
+ loadedIsMultimodal: boolean;
+ modelCapabilities: QueuedModelCapabilities | null;
+};
+
+type ChatRuntimeState = ReturnType<typeof useChatRuntimeStore.getState>;
+
+// A background auto-load may enrich models[] with the loaded catalog entry,
+// but every field describing the model visible in the current chat must return
+// to its prior value after the queued run captures its private runtime.
+const VISIBLE_MODEL_RUNTIME_KEYS = [
+ "activeLoadId",
+ "activeGgufVariant",
+ "activeModelIsLocal",
+ "ggufContextLength",
+ "ggufMaxContextLength",
+ "ggufNativeContextLength",
+ "modelRequiresTrustRemoteCode",
+ "supportsReasoning",
+ "reasoningAlwaysOn",
+ "reasoningEnabled",
+ "reasoningStyle",
+ "supportsReasoningOff",
+ "reasoningEffortLevels",
+ "supportsPreserveThinking",
+ "supportsTools",
+ "toolsEnabled",
+ "codeToolsEnabled",
+ "kvCacheDtype",
+ "loadedKvCacheDtype",
+ "nParallel",
+ "loadedNParallel",
+ "tensorParallel",
+ "loadedTensorParallel",
+ "gpuMemoryMode",
+ "loadedGpuMemoryMode",
+ "gpuLayers",
+ "loadedGpuLayers",
+ "nCpuMoe",
+ "loadedNCpuMoe",
+ "splitRatio",
+ "loadedSplitRatio",
+ "ggufLayerCount",
+ "moeLayerCount",
+ "selectedGpuIds",
+ "selectedGpuIndexKind",
+ "loadedGpuIds",
+ "loadedGpuIndexKind",
+ "customContextLength",
+ "loadedCustomContextLength",
+ "defaultChatTemplate",
+ "chatTemplateOverride",
+ "loadedChatTemplateOverride",
+ "loadedIsMultimodal",
+ "loadedIsDiffusion",
+ "speculativeType",
+ "loadedSpeculativeType",
+ "specFallbackReason",
+ "specDraftNMax",
+ "loadedSpecDraftNMax",
+] as const satisfies readonly (keyof ChatRuntimeState)[];
+
+type VisibleModelRuntimeState = Pick<
+ ChatRuntimeState,
+ (typeof VISIBLE_MODEL_RUNTIME_KEYS)[number]
+>;
+
+type VisibleModelStateSnapshot = {
+ settings: ReturnType<typeof snapshotQueuedChatRunSettings>;
+ runtime: VisibleModelRuntimeState;
+};
+
+function snapshotVisibleModelState(
+ state: ChatRuntimeState,
+): VisibleModelStateSnapshot {
+ const runtime = {} as VisibleModelRuntimeState;
+ for (const key of VISIBLE_MODEL_RUNTIME_KEYS) {
+ Object.assign(runtime, { [key]: state[key] });
+ }
+ return {
+ settings: snapshotQueuedChatRunSettings(state),
+ runtime,
+ };
+}
+
+function restoreVisibleModelState(snapshot: VisibleModelStateSnapshot): void {
+ const liveUsage = useChatRuntimeStore.getState();
+ liveUsage
+ .setCheckpoint(snapshot.settings.params.checkpoint, undefined, {
+ trackQueuedSettings: false,
+ });
+ useChatRuntimeStore.setState({
+ ...snapshot.runtime,
+ ...snapshot.settings,
+ params: { ...snapshot.settings.params },
+ // A visible provider run can finish while the background model loads.
+ // Preserve those newer per-thread totals instead of restoring stale usage.
+ contextUsage: liveUsage.contextUsage,
+ contextUsageByThreadId: liveUsage.contextUsageByThreadId,
+ });
+}
+
+function queuedResolvedModelFromStore(
+ state: ChatRuntimeState,
+): QueuedResolvedModelRuntime {
+ const activeModel = state.models.find(
+ (model) => model.id === state.params.checkpoint,
+ );
+ return {
+ checkpoint: state.params.checkpoint,
+ supportsTools: state.supportsTools,
+ supportsReasoning: state.supportsReasoning,
+ reasoningAlwaysOn: state.reasoningAlwaysOn,
+ reasoningStyle: state.reasoningStyle,
+ supportsReasoningOff: state.supportsReasoningOff,
+ reasoningEffortLevels: state.reasoningEffortLevels,
+ supportsPreserveThinking: state.supportsPreserveThinking,
+ ggufContextLength: state.ggufContextLength,
+ loadedIsMultimodal: state.loadedIsMultimodal,
+ modelCapabilities: activeModel
+ ? {
+ isVision: activeModel.isVision,
+ isGguf: activeModel.isGguf,
+ isAudio: activeModel.isAudio,
+ audioType: activeModel.audioType,
+ hasAudioInput: activeModel.hasAudioInput,
+ }
+ : null,
+ };
+}
+
+type AutoLoadOptions = {
+ skipAdoptServerModel?: boolean;
+ preserveVisibleSettings?: boolean;
+ captureResolvedRuntime?: (runtime: QueuedResolvedModelRuntime) => void;
+ abortSignal?: AbortSignal;
+};
+
+function applyAutoLoadRuntimeState(
+ options: AutoLoadOptions | undefined,
+ apply: () => void,
+) {
+ const visibleState = options?.preserveVisibleSettings
+ ? snapshotVisibleModelState(useChatRuntimeStore.getState())
+ : null;
+ try {
+ apply();
+ options?.captureResolvedRuntime?.(
+ queuedResolvedModelFromStore(useChatRuntimeStore.getState()),
+ );
+ } finally {
+ if (visibleState) {
+ restoreVisibleModelState(visibleState);
+ }
+ }
+}
+
/** Whether a cache row is chattable. Both fields are optional so an older backend keeps trying. */
function isChattableCachedRepo(repo: {
partial?: boolean;
@@ -1669,14 +1859,19 @@ function isChattableCachedRepo(repo: {
return repo.partial !== true && repo.capabilities?.can_chat !== false;
}
-async function autoLoadSmallestModel(): Promise<{
+async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
loaded: boolean;
blockedByTrustRemoteCode: boolean;
/** A load failure was already toasted, so callers must not replace it with generic advice. */
loadFailureReported?: boolean;
}> {
- if (await tryAdoptServerActiveModel()) {
- return { loaded: true, blockedByTrustRemoteCode: false };
+ options?.abortSignal?.throwIfAborted();
+ if (!options?.skipAdoptServerModel) {
+ const adoptedServerModel = await tryAdoptServerActiveModel();
+ options?.abortSignal?.throwIfAborted();
+ if (adoptedServerModel) {
+ return { loaded: true, blockedByTrustRemoteCode: false };
+ }
}
const store = useChatRuntimeStore.getState();
@@ -1761,12 +1956,14 @@ async function autoLoadSmallestModel(): Promise<{
cache_type_kv?: string | null;
tensor_parallel?: boolean | null;
}): Promise<boolean> {
+ options?.abortSignal?.throwIfAborted();
const validation = await validateModel({
...payload,
hf_token: hfToken,
load_in_4bit: true,
trust_remote_code: trustRemoteCode,
});
+ options?.abortSignal?.throwIfAborted();
// Background auto-load never runs a repo's custom code or loads Hub-flagged unsafe
// files on its own; both are deferred to the explicit consent dialog instead.
if (
@@ -1937,6 +2134,7 @@ async function autoLoadSmallestModel(): Promise<{
return false;
}
loadAttempts += 1;
+ options?.abortSignal?.throwIfAborted();
const loadResp = await loadModel({
model_path: modelPath,
hf_token: hfToken,
@@ -1969,129 +2167,145 @@ async function autoLoadSmallestModel(): Promise<{
noteLoadFailure(failureLabel, error);
throw error;
});
- // Only persist the global preference when the value came from the global
- // settings. A per-model config's choice must stay load-local, or autoloading
- // a remembered model on startup would rewrite the global default.
- if (config.speculativeType == null) {
- saveSpeculativeType(effectiveSpeculativeType);
- }
- // Self-gates on is_gguf (skips diffusion), so persists only for a real GGUF load.
- persistGpuMemoryModeOnLoad(loadResp, effectiveGpuMemoryMode);
- const loadedModelId = loadResp.model || modelPath;
- // The identity stays the backend's, per the inactive-cache contract; the pin is recorded
- // alongside it so a later reload finds the same directory.
- useChatRuntimeStore.setState({
- activeLoadId: modelPath === candidate.id ? null : modelPath,
- });
- useChatRuntimeStore
- .getState()
- .setCheckpoint(loadedModelId, candidate.ggufVariant ?? undefined);
- const store = useChatRuntimeStore.getState();
- store.setModelRequiresTrustRemoteCode(
- loadResp.requires_trust_remote_code ?? false,
- );
- store.setParams({
- ...store.params,
- ...(candidate.kind === "gguf"
- ? {}
- : { maxSeqLength: effectiveMaxSeqLength }),
- maxTokens:
- candidate.kind === "gguf"
- ? loadResp.context_length ?? 131072
- : effectiveMaxSeqLength,
- });
- // Upsert: a pre-load catalog entry has no backend-derived audio
- // capability, and the load response is the authority on it.
- syncModelCapabilities(loadedModelId, {
- ...loadResp,
- display_name: loadResp.display_name ?? candidate.id,
- is_gguf: loadResp.is_gguf ?? candidate.kind === "gguf",
- });
- if (candidate.kind === "gguf") {
- // Keep an explicit Manual+Auto context pin the load just applied (so a
- // later Apply doesn't silently revert it to auto-fit sizing), mirroring
- // the interactive path's keepCustomCtx; other cases baseline on
- // ggufContextLength.
- const keepCustomCtx = resolveManualAutoCtxPin(
- effectiveGpuMemoryMode,
- effectiveGpuLayers,
- config.customContextLength ?? null,
- );
- // Slots this auto-load committed. Diffusion ignores --parallel, so a count
- // there would mint a phantom override a saved preset carries onto a GGUF.
- const committedSlots = (loadResp.is_diffusion ?? false)
- ? null
- : (config.nParallel ?? null);
- useChatRuntimeStore.setState({
- ggufContextLength: loadResp.context_length ?? 131072,
- ggufMaxContextLength:
- loadResp.max_context_length ?? loadResp.context_length ?? 131072,
- ggufNativeContextLength: loadResp.native_context_length ?? null,
- supportsReasoning: loadResp.supports_reasoning ?? false,
- reasoningAlwaysOn: loadResp.reasoning_always_on ?? false,
- reasoningEnabled: loadResp.supports_reasoning ?? false,
- ...reasoningCapsFromLoad(loadResp),
- supportsPreserveThinking: loadResp.supports_preserve_thinking ?? false,
- supportsTools: loadResp.supports_tools ?? false,
- ...resolveToolsEnabledOnLoad(loadResp.supports_tools ?? false),
- kvCacheDtype: loadResp.cache_type_kv ?? null,
- loadedKvCacheDtype: loadResp.cache_type_kv ?? null,
- // Click-time value, not the resolved backend echo (see performLoad).
- nParallel: committedSlots,
- loadedNParallel: committedSlots,
- tensorParallel: loadResp.tensor_parallel ?? false,
- loadedTensorParallel: loadResp.tensor_parallel ?? false,
- ...loadedGpuMemoryFields(loadResp),
- loadedCustomContextLength: keepCustomCtx,
- defaultChatTemplate: loadResp.chat_template ?? null,
- chatTemplateOverride: effectiveChatTemplateOverride,
- loadedChatTemplateOverride: effectiveChatTemplateOverride,
- // Retain the saved requested context so re-saving the config keeps the
- // override; null stays null (auto/VRAM-fit).
- customContextLength: config.customContextLength,
- loadedIsMultimodal: isMultimodalResponse(loadResp),
- loadedIsDiffusion: loadResp.is_diffusion ?? false,
- activeModelIsLocal: loadResp.is_local_model ?? false,
- ...resolveLoadedSpeculativeSettings(loadResp),
- });
- } else {
+ // Do not apply this load to the visible runtime after its queue was
+ // cancelled. We still await /load so the model lifecycle remains
+ // serialized before a foreground selection can begin.
+ options?.abortSignal?.throwIfAborted();
+ applyAutoLoadRuntimeState(options, () => {
+ // Only persist the global preference when the value came from the global
+ // settings. A per-model config's choice must stay load-local, or autoloading
+ // a remembered model on startup would rewrite the global default.
+ if (config.speculativeType == null) {
+ saveSpeculativeType(effectiveSpeculativeType);
+ }
+ // Self-gates on is_gguf (skips diffusion), so persists only for a real GGUF load.
+ persistGpuMemoryModeOnLoad(loadResp, effectiveGpuMemoryMode);
+ const loadedModelId = loadResp.model || modelPath;
+ // The identity stays the backend's, per the inactive-cache contract; the
+ // pin is recorded alongside it so a later reload finds the same directory.
useChatRuntimeStore.setState({
- supportsReasoning: loadResp.supports_reasoning ?? false,
- reasoningAlwaysOn: loadResp.reasoning_always_on ?? false,
- reasoningEnabled: loadResp.supports_reasoning ?? false,
- ...reasoningCapsFromLoad(loadResp),
- supportsPreserveThinking: loadResp.supports_preserve_thinking ?? false,
- supportsTools: loadResp.supports_tools ?? false,
- ...resolveToolsEnabledOnLoad(loadResp.supports_tools ?? false),
- kvCacheDtype: loadResp.cache_type_kv ?? null,
- loadedKvCacheDtype: loadResp.cache_type_kv ?? null,
- // GGUF-only and never sent here: a staged override would be saved for
- // a model that cannot use it.
- nParallel: null,
- loadedNParallel: null,
- tensorParallel: loadResp.tensor_parallel ?? false,
- loadedTensorParallel: loadResp.tensor_parallel ?? false,
- // Non-GGUF response: clears any stale GPU baseline a prior manual-GPU
- // GGUF load left, matching the interactive/status sibling load paths.
- ...loadedGpuMemoryFields(loadResp),
- defaultChatTemplate: loadResp.chat_template ?? null,
- chatTemplateOverride: effectiveChatTemplateOverride,
- loadedChatTemplateOverride: effectiveChatTemplateOverride,
- customContextLength: null,
- ...resolveLoadedSpeculativeSettings(loadResp),
- loadedIsMultimodal: isMultimodalResponse(loadResp),
- loadedIsDiffusion: loadResp.is_diffusion ?? false,
- activeModelIsLocal: loadResp.is_local_model ?? false,
+ activeLoadId: modelPath === candidate.id ? null : modelPath,
});
- }
- if (!(loadResp.is_lora ?? false)) {
- recordLastLocalModelLoad({
- id: candidate.id,
- kind: candidate.kind,
- ggufVariant: candidate.ggufVariant,
+ useChatRuntimeStore
+ .getState()
+ .setCheckpoint(loadedModelId, candidate.ggufVariant ?? undefined, {
+ trackQueuedSettings: !options?.preserveVisibleSettings,
+ });
+ const store = useChatRuntimeStore.getState();
+ store.setModelRequiresTrustRemoteCode(
+ loadResp.requires_trust_remote_code ?? false,
+ );
+ store.setParams(
+ {
+ ...store.params,
+ ...(candidate.kind === "gguf"
+ ? {}
+ : { maxSeqLength: effectiveMaxSeqLength }),
+ maxTokens:
+ candidate.kind === "gguf"
+ ? loadResp.context_length ?? 131072
+ : effectiveMaxSeqLength,
+ },
+ {
+ persist: !options?.preserveVisibleSettings,
+ trackQueuedSettings: !options?.preserveVisibleSettings,
+ },
+ );
+ // Upsert: a pre-load catalog entry has no backend-derived audio
+ // capability, and the load response is the authority on it.
+ syncModelCapabilities(loadedModelId, {
+ ...loadResp,
+ display_name: loadResp.display_name ?? candidate.id,
+ is_gguf: loadResp.is_gguf ?? candidate.kind === "gguf",
});
- }
- showAutoLoadSuccess(candidate.successLabel);
+ if (candidate.kind === "gguf") {
+ // Keep an explicit Manual+Auto context pin the load just applied (so a
+ // later Apply doesn't silently revert it to auto-fit sizing), mirroring
+ // the interactive path's keepCustomCtx; other cases baseline on
+ // ggufContextLength.
+ const keepCustomCtx = resolveManualAutoCtxPin(
+ effectiveGpuMemoryMode,
+ effectiveGpuLayers,
+ config.customContextLength ?? null,
+ );
+ // Slots this auto-load committed. Diffusion ignores --parallel, so a count
+ // there would mint a phantom override a saved preset carries onto a GGUF.
+ const committedSlots = (loadResp.is_diffusion ?? false)
+ ? null
+ : (config.nParallel ?? null);
+ useChatRuntimeStore.setState({
+ ggufContextLength: loadResp.context_length ?? 131072,
+ ggufMaxContextLength:
+ loadResp.max_context_length ?? loadResp.context_length ?? 131072,
+ ggufNativeContextLength: loadResp.native_context_length ?? null,
+ supportsReasoning: loadResp.supports_reasoning ?? false,
+ reasoningAlwaysOn: loadResp.reasoning_always_on ?? false,
+ reasoningEnabled: loadResp.supports_reasoning ?? false,
+ ...reasoningCapsFromLoad(loadResp),
+ supportsPreserveThinking:
+ loadResp.supports_preserve_thinking ?? false,
+ supportsTools: loadResp.supports_tools ?? false,
+ ...resolveToolsEnabledOnLoad(loadResp.supports_tools ?? false),
+ kvCacheDtype: loadResp.cache_type_kv ?? null,
+ loadedKvCacheDtype: loadResp.cache_type_kv ?? null,
+ // Click-time value, not the resolved backend echo (see performLoad).
+ nParallel: committedSlots,
+ loadedNParallel: committedSlots,
+ tensorParallel: loadResp.tensor_parallel ?? false,
+ loadedTensorParallel: loadResp.tensor_parallel ?? false,
+ ...loadedGpuMemoryFields(loadResp),
+ loadedCustomContextLength: keepCustomCtx,
+ defaultChatTemplate: loadResp.chat_template ?? null,
+ chatTemplateOverride: effectiveChatTemplateOverride,
+ loadedChatTemplateOverride: effectiveChatTemplateOverride,
+ // Retain the saved requested context so re-saving the config keeps the
+ // override; null stays null (auto/VRAM-fit).
+ customContextLength: config.customContextLength,
+ loadedIsMultimodal: isMultimodalResponse(loadResp),
+ loadedIsDiffusion: loadResp.is_diffusion ?? false,
+ activeModelIsLocal: loadResp.is_local_model ?? false,
+ ...resolveLoadedSpeculativeSettings(loadResp),
+ });
+ } else {
+ useChatRuntimeStore.setState({
+ supportsReasoning: loadResp.supports_reasoning ?? false,
+ reasoningAlwaysOn: loadResp.reasoning_always_on ?? false,
+ reasoningEnabled: loadResp.supports_reasoning ?? false,
+ ...reasoningCapsFromLoad(loadResp),
+ supportsPreserveThinking:
+ loadResp.supports_preserve_thinking ?? false,
+ supportsTools: loadResp.supports_tools ?? false,
+ ...resolveToolsEnabledOnLoad(loadResp.supports_tools ?? false),
+ kvCacheDtype: loadResp.cache_type_kv ?? null,
+ loadedKvCacheDtype: loadResp.cache_type_kv ?? null,
+ // GGUF-only and never sent here: a staged override would be saved for
+ // a model that cannot use it.
+ nParallel: null,
+ loadedNParallel: null,
+ tensorParallel: loadResp.tensor_parallel ?? false,
+ loadedTensorParallel: loadResp.tensor_parallel ?? false,
+ // Non-GGUF response: clears any stale GPU baseline a prior manual-GPU
+ // GGUF load left, matching the interactive/status sibling load paths.
+ ...loadedGpuMemoryFields(loadResp),
+ defaultChatTemplate: loadResp.chat_template ?? null,
+ chatTemplateOverride: effectiveChatTemplateOverride,
+ loadedChatTemplateOverride: effectiveChatTemplateOverride,
+ customContextLength: null,
+ ...resolveLoadedSpeculativeSettings(loadResp),
+ loadedIsMultimodal: isMultimodalResponse(loadResp),
+ loadedIsDiffusion: loadResp.is_diffusion ?? false,
+ activeModelIsLocal: loadResp.is_local_model ?? false,
+ });
+ }
+ if (!(loadResp.is_lora ?? false)) {
+ recordLastLocalModelLoad({
+ id: candidate.id,
+ kind: candidate.kind,
+ ggufVariant: candidate.ggufVariant,
+ });
+ }
+ showAutoLoadSuccess(candidate.successLabel);
+ });
return true;
}
try {
@@ -2099,6 +2313,7 @@ async function autoLoadSmallestModel(): Promise<{
listCachedGguf().catch(() => []),
listCachedModels().catch(() => []),
]);
+ options?.abortSignal?.throwIfAborted();
// Filtered once, so the last-used lookup sees the same set as the sweeps.
const ggufRepos = allGgufRepos.filter(isChattableCachedRepo);
const modelRepos = allModelRepos.filter(isChattableCachedRepo);
@@ -2138,6 +2353,7 @@ async function autoLoadSmallestModel(): Promise<{
}
}
} catch {
+ options?.abortSignal?.throwIfAborted();
hadNonTrustFailure = true;
skippedAutoLoadCandidates.add(
autoLoadCandidateKey("gguf", repo.repo_id, lastLoaded.ggufVariant),
@@ -2162,6 +2378,7 @@ async function autoLoadSmallestModel(): Promise<{
return { loaded: true, blockedByTrustRemoteCode: false };
}
} catch {
+ options?.abortSignal?.throwIfAborted();
hadNonTrustFailure = true;
skippedAutoLoadCandidates.add(
autoLoadCandidateKey("model", repo.repo_id),
@@ -2211,6 +2428,7 @@ async function autoLoadSmallestModel(): Promise<{
}
}
} catch {
+ options?.abortSignal?.throwIfAborted();
hadNonTrustFailure = true;
continue;
}
@@ -2245,6 +2463,7 @@ async function autoLoadSmallestModel(): Promise<{
return { loaded: true, blockedByTrustRemoteCode: false };
}
} catch {
+ options?.abortSignal?.throwIfAborted();
hadNonTrustFailure = true;
continue;
}
@@ -2309,6 +2528,7 @@ async function autoLoadSmallestModel(): Promise<{
return { loaded: false, blockedByTrustRemoteCode };
}
loadAttempts += 1;
+ options?.abortSignal?.throwIfAborted();
const loadResp = await loadModel({
model_path: "unsloth/Qwen3.5-4B-MTP-GGUF",
hf_token: hfToken,
@@ -2334,30 +2554,42 @@ async function autoLoadSmallestModel(): Promise<{
n_cpu_moe: 0,
gpu_ids: defaultGpuIds ?? undefined,
});
- saveSpeculativeType(specSettings.speculativeType);
- persistGpuMemoryModeOnLoad(loadResp, rt.gpuMemoryMode);
- useChatRuntimeStore
- .getState()
- .setCheckpoint("unsloth/Qwen3.5-4B-MTP-GGUF", "UD-Q4_K_XL");
- const store = useChatRuntimeStore.getState();
- store.setModelRequiresTrustRemoteCode(
- loadResp.requires_trust_remote_code ?? false,
- );
- store.setParams({
- ...store.params,
- maxTokens: loadResp.context_length ?? 131072,
- });
- const defaultModel: ChatModelSummary = {
- id: "unsloth/Qwen3.5-4B-MTP-GGUF",
- name: loadResp.display_name ?? "Qwen3.5-4B-MTP-GGUF",
- isVision: loadResp.is_vision ?? false,
- isLora: false,
- isGguf: true,
- };
- if (!store.models.some((m) => m.id === "unsloth/Qwen3.5-4B-MTP-GGUF")) {
- store.setModels([...store.models, defaultModel]);
- }
- useChatRuntimeStore.setState({
+ options?.abortSignal?.throwIfAborted();
+ applyAutoLoadRuntimeState(options, () => {
+ saveSpeculativeType(specSettings.speculativeType);
+ persistGpuMemoryModeOnLoad(loadResp, rt.gpuMemoryMode);
+ useChatRuntimeStore
+ .getState()
+ .setCheckpoint(
+ "unsloth/Qwen3.5-4B-MTP-GGUF",
+ "UD-Q4_K_XL",
+ { trackQueuedSettings: !options?.preserveVisibleSettings },
+ );
+ const store = useChatRuntimeStore.getState();
+ store.setModelRequiresTrustRemoteCode(
+ loadResp.requires_trust_remote_code ?? false,
+ );
+ store.setParams(
+ {
+ ...store.params,
+ maxTokens: loadResp.context_length ?? 131072,
+ },
+ {
+ persist: !options?.preserveVisibleSettings,
+ trackQueuedSettings: !options?.preserveVisibleSettings,
+ },
+ );
+ const defaultModel: ChatModelSummary = {
+ id: "unsloth/Qwen3.5-4B-MTP-GGUF",
+ name: loadResp.display_name ?? "Qwen3.5-4B-MTP-GGUF",
+ isVision: loadResp.is_vision ?? false,
+ isLora: false,
+ isGguf: true,
+ };
+ if (!store.models.some((m) => m.id === "unsloth/Qwen3.5-4B-MTP-GGUF")) {
+ store.setModels([...store.models, defaultModel]);
+ }
+ useChatRuntimeStore.setState({
ggufContextLength: loadResp.context_length ?? 131072,
ggufMaxContextLength:
loadResp.max_context_length ?? loadResp.context_length ?? 131072,
@@ -2385,15 +2617,17 @@ async function autoLoadSmallestModel(): Promise<{
loadedIsMultimodal: isMultimodalResponse(loadResp),
activeModelIsLocal: loadResp.is_local_model ?? false,
...resolveLoadedSpeculativeSettings(loadResp),
+ });
+ recordLastLocalModelLoad({
+ id: "unsloth/Qwen3.5-4B-MTP-GGUF",
+ kind: "gguf",
+ ggufVariant: "UD-Q4_K_XL",
+ });
+ showAutoLoadSuccess("Loaded Qwen3.5-4B-MTP (UD-Q4_K_XL)");
});
- recordLastLocalModelLoad({
- id: "unsloth/Qwen3.5-4B-MTP-GGUF",
- kind: "gguf",
- ggufVariant: "UD-Q4_K_XL",
- });
- showAutoLoadSuccess("Loaded Qwen3.5-4B-MTP (UD-Q4_K_XL)");
return { loaded: true, blockedByTrustRemoteCode: false };
} catch {
+ options?.abortSignal?.throwIfAborted();
toast.dismiss(toastId);
hadNonTrustFailure = true;
return {
@@ -2403,6 +2637,7 @@ async function autoLoadSmallestModel(): Promise<{
};
}
} catch {
+ options?.abortSignal?.throwIfAborted();
toast.dismiss(toastId);
hadNonTrustFailure = true;
return {
@@ -2412,10 +2647,119 @@ async function autoLoadSmallestModel(): Promise<{
}
}
+async function resolveQueuedEmptyLocalModel(
+ abortSignal: AbortSignal,
+): Promise<{
+ loaded: boolean;
+ blockedByTrustRemoteCode: boolean;
+ loadFailureReported?: boolean;
+ modelRuntime: QueuedResolvedModelRuntime | null;
+}> {
+ let lifecycleLease = useChatRuntimeStore.getState().beginModelLoading();
+ while (lifecycleLease === null) {
+ await waitForModelReady(abortSignal);
+ abortSignal.throwIfAborted();
+ lifecycleLease = useChatRuntimeStore.getState().beginModelLoading();
+ }
+
+ try {
+ abortSignal.throwIfAborted();
+ const visibleState = useChatRuntimeStore.getState();
+ if (isExternalModelId(visibleState.params.checkpoint)) {
+ // Hold the lifecycle lease across the probe. Its response cannot become
+ // stale behind a foreground or sibling queued load, and only this owner
+ // may clear modelLoading afterward.
+ // A failed probe is not evidence that the local server is empty. Fail
+ // closed so a transient status error cannot replace a valid resident
+ // model with the recorded/default auto-load candidate.
+ const status = await getInferenceStatus();
+ abortSignal.throwIfAborted();
+ const checkpoint = resolveInferenceCheckpointId(status);
+ if (checkpoint) {
+ return {
+ loaded: true,
+ blockedByTrustRemoteCode: false,
+ modelRuntime: {
+ checkpoint,
+ supportsTools: status.supports_tools ?? false,
+ supportsReasoning: status.supports_reasoning ?? false,
+ reasoningAlwaysOn: status.reasoning_always_on ?? false,
+ ...reasoningCapsFromLoad(status),
+ supportsPreserveThinking:
+ status.supports_preserve_thinking ?? false,
+ ggufContextLength: status.is_gguf
+ ? (status.context_length ?? null)
+ : null,
+ loadedIsMultimodal: isMultimodalResponse(status),
+ modelCapabilities: {
+ isVision: status.is_vision ?? false,
+ isGguf: status.is_gguf ?? false,
+ isAudio: status.is_audio ?? false,
+ audioType: status.audio_type ?? null,
+ hasAudioInput: status.has_audio_input ?? false,
+ },
+ },
+ };
+ }
+
+ const visibleExternalState = snapshotVisibleModelState(visibleState);
+ const visibleThreadEpoch = visibleState.activeThreadEpoch;
+ const visibleSettingsEpoch = visibleState.queuedSettingsEpoch;
+ const visibleRoute = window.location.href;
+ let result: Awaited<ReturnType<typeof autoLoadSmallestModel>>;
+ let modelRuntime: QueuedResolvedModelRuntime | null = null;
+ try {
+ result = await autoLoadSmallestModel({
+ skipAdoptServerModel: true,
+ preserveVisibleSettings: true,
+ captureResolvedRuntime: (runtime) => {
+ modelRuntime = runtime;
+ },
+ abortSignal,
+ });
+ if (result.loaded && !modelRuntime) {
+ modelRuntime = queuedResolvedModelFromStore(
+ useChatRuntimeStore.getState(),
+ );
+ }
+ } finally {
+ if (
+ useChatRuntimeStore.getState().activeThreadEpoch ===
+ visibleThreadEpoch &&
+ useChatRuntimeStore.getState().queuedSettingsEpoch ===
+ visibleSettingsEpoch &&
+ window.location.href === visibleRoute
+ ) {
+ restoreVisibleModelState(visibleExternalState);
+ }
+ }
+ return { ...result, modelRuntime };
+ }
+
+ if (visibleState.params.checkpoint) {
+ return {
+ loaded: true,
+ blockedByTrustRemoteCode: false,
+ modelRuntime: queuedResolvedModelFromStore(visibleState),
+ };
+ }
+
+ const result = await autoLoadSmallestModel({ abortSignal });
+ return {
+ ...result,
+ modelRuntime: result.loaded
+ ? queuedResolvedModelFromStore(useChatRuntimeStore.getState())
+ : null,
+ };
+ } finally {
+ useChatRuntimeStore.getState().endModelLoading(lifecycleLease);
+ }
+}
+
export function createOpenAIStreamAdapter(
options: OpenAIStreamAdapterOptions = {},
): ChatModelAdapter {
- return {
+ const adapter = {
async *run({
messages,
abortSignal,
@@ -2428,13 +2772,43 @@ export function createOpenAIStreamAdapter(
// switches chats while waiting for model load / auto-load.
const resolvedThreadId =
(unstable_threadId ?? runtime.activeThreadId) || undefined;
+ const releaseCurrentPreStreamRun = () =>
+ releasePreStreamRunForThreadIds([
+ unstable_threadId,
+ resolvedThreadId,
+ ]);
+ const queuedRunSettings =
+ consumeQueuedChatRunSettings(resolvedThreadId);
+ let queuedEmptyModelRuntime: QueuedResolvedModelRuntime | null = null;
+ const persistResolvedQueuedModel = async (modelId: string) => {
+ if (
+ !queuedRunSettings ||
+ queuedRunSettings.params.checkpoint ||
+ !resolvedThreadId ||
+ !modelId
+ ) {
+ return;
+ }
+ try {
+ await updateStoredChatThread(resolvedThreadId, { modelId });
+ } catch (error) {
+ throw error;
+ }
+ };
+ if (queuedRunSettings) {
+ runtime = { ...runtime, ...queuedRunSettings };
+ }
const threadAlreadyResearched = Boolean(
resolvedThreadId &&
useResearchRunStore.getState().claimedThreadIds[resolvedThreadId],
);
if (runtime.deepResearchEnabled && threadAlreadyResearched) {
- runtime.setDeepResearchEnabled(false);
- runtime = useChatRuntimeStore.getState();
+ if (queuedRunSettings) {
+ runtime = { ...runtime, deepResearchEnabled: false };
+ } else {
+ runtime.setDeepResearchEnabled(false);
+ runtime = useChatRuntimeStore.getState();
+ }
}
if (
runtime.deepResearchEnabled &&
@@ -2443,20 +2817,31 @@ export function createOpenAIStreamAdapter(
) {
if (runtime.modelLoading) {
toast.info("Waiting for model to finish loading…");
- await waitForModelReady(abortSignal);
+ try {
+ await waitForModelReady(abortSignal);
+ } catch (error) {
+ throw error;
+ }
}
- if (!useChatRuntimeStore.getState().params.checkpoint) {
- const { loaded, blockedByTrustRemoteCode, loadFailureReported } =
- await autoLoadSmallestModel();
- if (!loaded) {
+ if (!runtime.params.checkpoint) {
+ let resolution: Awaited<
+ ReturnType<typeof resolveQueuedEmptyLocalModel>
+ >;
+ try {
+ resolution = await resolveQueuedEmptyLocalModel(abortSignal);
+ } catch (error) {
+ throw error;
+ }
+ queuedEmptyModelRuntime = resolution.modelRuntime;
+ if (!resolution.loaded) {
// A reported failure already names the model; generic advice buries it.
- if (!loadFailureReported) {
+ if (!resolution.loadFailureReported) {
toast.error(
- blockedByTrustRemoteCode
+ resolution.blockedByTrustRemoteCode
? "This model needs custom code approval"
: "No model loaded",
{
- description: blockedByTrustRemoteCode
+ description: resolution.blockedByTrustRemoteCode
? "Select it from the top bar to review and approve its custom code, or pick another model."
: "Pick a model in the top bar, then retry.",
},
@@ -2465,7 +2850,51 @@ export function createOpenAIStreamAdapter(
throw new Error("Load a model first.");
}
}
- runtime = useChatRuntimeStore.getState();
+ const liveRuntime = useChatRuntimeStore.getState();
+ runtime = queuedRunSettings
+ ? queuedRunSettings.params.checkpoint
+ ? { ...liveRuntime, ...queuedRunSettings }
+ : {
+ ...liveRuntime,
+ ...queuedRunSettings,
+ params: {
+ ...queuedRunSettings.params,
+ checkpoint:
+ queuedEmptyModelRuntime?.checkpoint ??
+ liveRuntime.params.checkpoint,
+ },
+ supportsTools:
+ queuedEmptyModelRuntime?.supportsTools ??
+ liveRuntime.supportsTools,
+ supportsReasoning:
+ queuedEmptyModelRuntime?.supportsReasoning ??
+ liveRuntime.supportsReasoning,
+ reasoningAlwaysOn:
+ queuedEmptyModelRuntime?.reasoningAlwaysOn ??
+ liveRuntime.reasoningAlwaysOn,
+ reasoningStyle:
+ queuedEmptyModelRuntime?.reasoningStyle ??
+ liveRuntime.reasoningStyle,
+ supportsReasoningOff:
+ queuedEmptyModelRuntime?.supportsReasoningOff ??
+ liveRuntime.supportsReasoningOff,
+ reasoningEffortLevels:
+ queuedEmptyModelRuntime?.reasoningEffortLevels ??
+ liveRuntime.reasoningEffortLevels,
+ supportsPreserveThinking:
+ queuedEmptyModelRuntime?.supportsPreserveThinking ??
+ liveRuntime.supportsPreserveThinking,
+ ggufContextLength:
+ queuedEmptyModelRuntime !== null
+ ? queuedEmptyModelRuntime.ggufContextLength
+ : liveRuntime.ggufContextLength,
+ models: mergeQueuedModelCapabilities(
+ liveRuntime.models,
+ queuedEmptyModelRuntime?.checkpoint ?? "",
+ queuedEmptyModelRuntime?.modelCapabilities ?? null,
+ ),
+ }
+ : liveRuntime;
if (!resolvedThreadId) throw new Error("Research requires a saved chat.");
if (!unstable_assistantMessageId) {
throw new Error(
@@ -2478,6 +2907,7 @@ export function createOpenAIStreamAdapter(
const userMessageParentId =
userMessageIndex > 0 ? messages[userMessageIndex - 1]!.id : null;
const { params } = runtime;
+ await persistResolvedQueuedModel(params.checkpoint);
const model = params.checkpoint.trim();
if (!model || parseExternalModelId(model)) {
throw new Error("Deep research requires a selected local model.");
@@ -2572,6 +3002,7 @@ export function createOpenAIStreamAdapter(
}
};
runtime.registerThreadServerCancel(threadKey, researchServerCancel);
+ releaseCurrentPreStreamRun();
runtime.setThreadRunning(threadKey, true, { owner: researchServerCancel });
let report = "";
let releaseResearchFollow: (() => void) | null = null;
@@ -2623,7 +3054,13 @@ export function createOpenAIStreamAdapter(
createdRun,
detachResearchFollow,
);
- runtime.setDeepResearchEnabled(false);
+ if (
+ !queuedRunSettings ||
+ resolvedThreadId ===
+ useChatRuntimeStore.getState().activeThreadId
+ ) {
+ runtime.setDeepResearchEnabled(false);
+ }
if (abortSignal.aborted) {
const detached = Boolean(
(abortSignal.reason as { detach?: boolean } | undefined)?.detach,
@@ -2725,7 +3162,6 @@ export function createOpenAIStreamAdapter(
store.clearPendingImageEditReference();
}
};
-
// Wait for in-progress model load before inferring.
if (runtime.modelLoading) {
toast.info("Waiting for model to finish loading…");
@@ -2737,27 +3173,26 @@ export function createOpenAIStreamAdapter(
}
}
- if (!useChatRuntimeStore.getState().params.checkpoint) {
- // Prefer a model already loaded by the CLI/API before auto-loading.
- let loaded: boolean;
- let blockedByTrustRemoteCode: boolean;
- let loadFailureReported: boolean | undefined;
+ if (!runtime.params.checkpoint) {
+ let resolution: Awaited<
+ ReturnType<typeof resolveQueuedEmptyLocalModel>
+ >;
try {
- ({ loaded, blockedByTrustRemoteCode, loadFailureReported } =
- await autoLoadSmallestModel());
+ resolution = await resolveQueuedEmptyLocalModel(abortSignal);
} catch (error) {
clearSelectedImageEditReference();
throw error;
}
- if (!loaded) {
+ queuedEmptyModelRuntime = resolution.modelRuntime;
+ if (!resolution.loaded) {
// A reported failure already names the model; generic advice buries it.
- if (!loadFailureReported) {
+ if (!resolution.loadFailureReported) {
toast.error(
- blockedByTrustRemoteCode
+ resolution.blockedByTrustRemoteCode
? "This model needs custom code approval"
: "No model loaded",
{
- description: blockedByTrustRemoteCode
+ description: resolution.blockedByTrustRemoteCode
? "Select it from the top bar to review and approve its custom code, or pick another model."
: "Pick a model in the top bar, then retry.",
},
@@ -2769,8 +3204,56 @@ export function createOpenAIStreamAdapter(
}
// Re-read store after auto-load / model-ready wait.
- runtime = useChatRuntimeStore.getState();
+ const liveRuntime = useChatRuntimeStore.getState();
+ runtime = queuedRunSettings
+ ? queuedRunSettings.params.checkpoint
+ ? { ...liveRuntime, ...queuedRunSettings }
+ : {
+ ...liveRuntime,
+ ...queuedRunSettings,
+ params: {
+ ...queuedRunSettings.params,
+ checkpoint:
+ queuedEmptyModelRuntime?.checkpoint ??
+ liveRuntime.params.checkpoint,
+ },
+ supportsTools:
+ queuedEmptyModelRuntime?.supportsTools ??
+ liveRuntime.supportsTools,
+ supportsReasoning:
+ queuedEmptyModelRuntime?.supportsReasoning ??
+ liveRuntime.supportsReasoning,
+ reasoningAlwaysOn:
+ queuedEmptyModelRuntime?.reasoningAlwaysOn ??
+ liveRuntime.reasoningAlwaysOn,
+ reasoningStyle:
+ queuedEmptyModelRuntime?.reasoningStyle ??
+ liveRuntime.reasoningStyle,
+ supportsReasoningOff:
+ queuedEmptyModelRuntime?.supportsReasoningOff ??
+ liveRuntime.supportsReasoningOff,
+ reasoningEffortLevels:
+ queuedEmptyModelRuntime?.reasoningEffortLevels ??
+ liveRuntime.reasoningEffortLevels,
+ supportsPreserveThinking:
+ queuedEmptyModelRuntime?.supportsPreserveThinking ??
+ liveRuntime.supportsPreserveThinking,
+ ggufContextLength:
+ queuedEmptyModelRuntime !== null
+ ? queuedEmptyModelRuntime.ggufContextLength
+ : liveRuntime.ggufContextLength,
+ loadedIsMultimodal:
+ queuedEmptyModelRuntime?.loadedIsMultimodal ??
+ liveRuntime.loadedIsMultimodal,
+ models: mergeQueuedModelCapabilities(
+ liveRuntime.models,
+ queuedEmptyModelRuntime?.checkpoint ?? "",
+ queuedEmptyModelRuntime?.modelCapabilities ?? null,
+ ),
+ }
+ : liveRuntime;
const { params } = runtime;
+ await persistResolvedQueuedModel(params.checkpoint);
const {
supportsTools,
toolsEnabled,
@@ -3062,7 +3545,10 @@ export function createOpenAIStreamAdapter(
// Scan post-prune history so a refused user turn's image/audio
// doesn't gate or mis-attribute the next turn.
const imageBase64 = findLatestUserImageBase64(survivingMessages);
- const audioBase64 = findLatestUserAudioBase64(survivingMessages);
+ const audioBase64 = findLatestUserAudioBase64(
+ survivingMessages,
+ !queuedRunSettings,
+ );
const hasOutboundImage = Boolean(imageBase64);
// Keep render_html local-only and mirror the backend image-turn gate.
@@ -3121,7 +3607,7 @@ export function createOpenAIStreamAdapter(
}
}
// Clear pending audio from store after extracting (consumed on send).
- if (audioBase64) {
+ if (audioBase64 && !queuedRunSettings) {
const audioName = runtime.pendingAudioName;
if (audioName) {
const lastUserMsg = [...survivingMessages]
@@ -3170,6 +3656,7 @@ export function createOpenAIStreamAdapter(
if (activeModel?.isAudio && !activeModel?.hasAudioInput) {
const audioCancel = () => runAbort.abort();
runtime.registerThreadServerCancel(threadKey, audioCancel);
+ releaseCurrentPreStreamRun();
runtime.setThreadRunning(threadKey, true, { owner: audioCancel });
try {
yield {
@@ -3257,6 +3744,7 @@ export function createOpenAIStreamAdapter(
}, warmupDelayMs);
// Flagged local/external so the model-swap gate only counts the chats a reload ends; the
// backend leaves external-provider runs out of active_generations for the same reason.
+ releaseCurrentPreStreamRun();
runtime.setThreadRunning(threadKey, true, {
local: !isExternalRequest,
owner: serverCancel,
@@ -3907,13 +4395,11 @@ export function createOpenAIStreamAdapter(
},
}
: {}),
- auto_heal_tool_calls:
- useChatRuntimeStore.getState().autoHealToolCalls,
- nudge_tool_calls: useChatRuntimeStore.getState().nudgeToolCalls,
- max_tool_calls_per_message:
- useChatRuntimeStore.getState().maxToolCallsPerMessage,
+ auto_heal_tool_calls: runtime.autoHealToolCalls,
+ nudge_tool_calls: runtime.nudgeToolCalls,
+ max_tool_calls_per_message: runtime.maxToolCallsPerMessage,
tool_call_timeout: (() => {
- const mins = useChatRuntimeStore.getState().toolCallTimeout;
+ const mins = runtime.toolCallTimeout;
return mins >= 9999 ? 9999 : mins * 60;
})(),
}
@@ -4747,8 +5233,7 @@ export function createOpenAIStreamAdapter(
meta?.usage &&
typeof meta.usage.prompt_tokens === "number" &&
typeof meta.usage.completion_tokens === "number" &&
- typeof meta.usage.total_tokens === "number" &&
- useChatRuntimeStore.getState().params.checkpoint === params.checkpoint
+ typeof meta.usage.total_tokens === "number"
) {
const usage = {
promptTokens: meta.usage.prompt_tokens,
@@ -4764,7 +5249,10 @@ export function createOpenAIStreamAdapter(
.getState()
.setThreadContextUsage(usageThreadKey, usage);
}
- if (usageThreadIsVisible) {
+ if (
+ usageThreadIsVisible &&
+ useChatRuntimeStore.getState().params.checkpoint === params.checkpoint
+ ) {
useChatRuntimeStore.getState().setContextUsage(usage);
}
}
@@ -4920,5 +5408,35 @@ export function createOpenAIStreamAdapter(
runtime.clearThreadServerCancel(cleanupKey, serverCancel);
}
},
+ } satisfies ChatModelAdapter;
+ return {
+ async *run(args) {
+ const preStreamThreadIds = preStreamRunThreadIdsForAdapter(
+ args.unstable_threadId,
+ useChatRuntimeStore.getState().activeThreadId,
+ );
+ const reservationToken =
+ findPreStreamRunReservation(preStreamThreadIds);
+ if (reservationToken) {
+ adoptPreStreamRunReservation(reservationToken, preStreamThreadIds);
+ }
+ try {
+ yield* adapter.run(args);
+ } catch (error) {
+ if (!args.abortSignal.aborted) {
+ notifyPromptQueueRunFailed(
+ args.unstable_threadId ?? preStreamThreadIds[0] ?? null,
+ );
+ }
+ throw error;
+ } finally {
+ if (
+ reservationToken &&
+ releasePreStreamRunReservation(reservationToken)
+ ) {
+ notifyPromptQueueRunFailed(args.unstable_threadId ?? null);
+ }
+ }
+ },
};
}
diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsx
index 3c519937a88..758c7ef961e 100644
--- a/studio/frontend/src/features/chat/chat-page.tsx
+++ b/studio/frontend/src/features/chat/chat-page.tsx
@@ -194,6 +194,7 @@ import {
listStoredChatMessages,
listStoredChatThreads,
} from "./utils/chat-history-storage";
+import { requestTemporaryPromptQueueStop } from "./utils/prompt-queue-boundary";
import { isAssistantLocalThreadId } from "./utils/thread-ids";
import {
consumeProjectSourcesPending,
@@ -1817,6 +1818,7 @@ export function ChatPage({
: "Turn on temporary chat";
const toggleIncognito = useCallback(() => {
const store = useChatRuntimeStore.getState();
+ const wasIncognito = store.incognito;
store.setIncognito(!store.incognito);
// On an empty scratch chat there's nothing to abandon, so flip in
// place: navigating would remount the thread and bounce the composer
@@ -1828,6 +1830,9 @@ export function ChatPage({
!search.compare &&
!search.project &&
store.activeThreadId == null;
+ if (wasIncognito) {
+ requestTemporaryPromptQueueStop();
+ }
if (onEmptyScratchChat) return;
// setActiveThreadId already clears contextUsage.
store.setActiveThreadId(null);
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 2039e69ad06..7a5063f4c5d 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
@@ -31,6 +31,9 @@ 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 { cancelPreStreamRunReservations } from "../utils/pre-stream-run-reservation";
+import type { ModelLifecycleLease } from "../utils/model-lifecycle-gate";
import {
GPU_LAYERS_AUTO,
isLocalModelPath,
@@ -425,6 +428,7 @@ export function useChatModelRuntime() {
const loadAttemptRef = useRef(0);
const loadToastDismissedRef = useRef(false);
const cancelUnloadPendingRef = useRef(false);
+ const loadLifecycleLeaseRef = useRef<ModelLifecycleLease | null>(null);
const setLoadToastDismissedState = useCallback((dismissed: boolean) => {
loadToastDismissedRef.current = dismissed;
@@ -443,7 +447,11 @@ export function useChatModelRuntime() {
useChatRuntimeStore.getState().clearLoadingModelPick(pickOf(inFlight));
}
if (!cancelUnloadPendingRef.current) {
- useChatRuntimeStore.getState().setModelLoading(false);
+ const lease = loadLifecycleLeaseRef.current;
+ loadLifecycleLeaseRef.current = null;
+ if (lease !== null) {
+ useChatRuntimeStore.getState().endModelLoading(lease);
+ }
}
}, [setLoadToastDismissedState]);
@@ -490,7 +498,6 @@ export function useChatModelRuntime() {
: "The current download may still finish in the background.",
});
cancelUnloadPendingRef.current = true;
- useChatRuntimeStore.getState().setModelLoading(true);
void (async () => {
try {
// Unforced on purpose: a chat may stream on the PREVIOUS model and must not be killed by
@@ -504,7 +511,11 @@ export function useChatModelRuntime() {
} finally {
cancelUnloadPendingRef.current = false;
if (!loadingModelRef.current) {
- useChatRuntimeStore.getState().setModelLoading(false);
+ const lease = loadLifecycleLeaseRef.current;
+ loadLifecycleLeaseRef.current = null;
+ if (lease !== null) {
+ useChatRuntimeStore.getState().endModelLoading(lease);
+ }
}
}
})();
@@ -622,20 +633,59 @@ 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 user's confirmation.
+ const lifecycleLease = useChatRuntimeStore
+ .getState()
+ .beginModelLoading();
+ if (lifecycleLease === null) {
+ restorePreviousConfig();
+ toast.info("A model is loading", {
+ description: "Wait for it to finish or cancel it first.",
+ });
+ return;
+ }
+ loadLifecycleLeaseRef.current = lifecycleLease;
+ const releasePreflightLifecycleLease = () => {
+ if (loadLifecycleLeaseRef.current !== lifecycleLease) {
+ return;
+ }
+ loadLifecycleLeaseRef.current = null;
+ useChatRuntimeStore.getState().endModelLoading(lifecycleLease);
+ };
+
// Every chat decodes on the llama-server this load replaces, so ask first, then allow the
// cancel; the 409 gate stays armed for callers that never confirmed.
- const stopDecision = await confirmStopRunningChatsIfNeeded(
- forceReload ? "Applying these settings" : "Loading a different model",
- );
+ let stopDecision: Awaited<
+ ReturnType<typeof confirmStopRunningChatsIfNeeded>
+ >;
+ try {
+ stopDecision = await confirmStopRunningChatsIfNeeded(
+ forceReload ? "Applying these settings" : "Loading a different model",
+ );
+ } catch (error) {
+ releasePreflightLifecycleLease();
+ throw error;
+ }
if (!stopDecision.proceed) {
+ releasePreflightLifecycleLease();
if (typeof selection !== "string" && selection.previousConfig) {
applyPerModelConfigToRuntime(selection.previousConfig);
}
return;
}
- // Re-check: the confirm above awaits a GET, so a pick in that window would start a rival
- // load over the same refs. Nothing awaits before the reservation below.
- if (bailIfLoadInFlight()) return;
+ // Re-check the tracked picker for a load that was already starting when
+ // this lifecycle lease was acquired.
+ try {
+ if (bailIfLoadInFlight()) {
+ releasePreflightLifecycleLease();
+ return;
+ }
+ } catch (error) {
+ releasePreflightLifecycleLease();
+ throw error;
+ }
const forceCancelActive = stopDecision.forceCancelActive;
const explicitIsLora =
@@ -702,7 +752,6 @@ export function useChatModelRuntime() {
nativePathToken: nativePathToken ?? null,
};
setLoadingModel(loadInfo);
- useChatRuntimeStore.getState().setModelLoading(true);
useChatRuntimeStore.getState().setLoadingModelPick(pickOf(loadInfo));
setLoadProgress(
isDownloaded || isCachedLora
@@ -984,6 +1033,8 @@ export function useChatModelRuntime() {
? (await consumeNativePathToken(nativePathToken, "load-model")).nativePathLease
: undefined;
+ cancelPreStreamRunReservations(stopDecision.preStreamRunTokens);
+ requestLocalPromptQueueStop(stopDecision.promptQueueThreadIds);
if (currentCheckpoint) {
// With chats generating, skip this preliminary unload: it cancels them ahead of /load's
// preflight, so a rejected target truncates replies for a model that never loads
@@ -1089,6 +1140,10 @@ export function useChatModelRuntime() {
);
const effectiveChatTemplateOverride =
loadChatTemplateOverride?.trim() ? loadChatTemplateOverride : null;
+ // A queue can be created while the preliminary unload is pending.
+ // Stop a second time at the final boundary so no prompt captured
+ // against the outgoing checkpoint survives into the new backend.
+ requestLocalPromptQueueStop();
const loadResponse = await loadModel({
model_path: loadPath,
nativePathLease: loadNativePathLease,
@@ -1795,7 +1850,15 @@ export function useChatModelRuntime() {
await refresh();
return true;
}
+ let lifecycleLease: ModelLifecycleLease | null = null;
try {
+ // Block queue materialization before taking the confirmation snapshot.
+ // Otherwise a queue can appear while the dialog is open and be stopped
+ // by the unload even though the user never confirmed stopping it.
+ lifecycleLease = useChatRuntimeStore.getState().beginModelLoading();
+ if (lifecycleLease === null) {
+ return false;
+ }
// Ejecting tears down llama-server, so every chat stops. Same prompt, but it
// leaves no model loaded, so it must not be worded as a reload.
const stopDecision = await confirmStopRunningChatsIfNeeded(
@@ -1803,14 +1866,15 @@ export function useChatModelRuntime() {
"unload",
);
if (!stopDecision.proceed) return false;
- // Same window as selectModel: a load may have started during the confirm.
- if (bailIfLoading()) return false;
async function performUnload(): Promise<void> {
+ cancelPreStreamRunReservations(stopDecision.preStreamRunTokens);
+ requestLocalPromptQueueStop(stopDecision.promptQueueThreadIds);
await unloadModel({
model_path: params.checkpoint,
force_cancel_active: stopDecision.forceCancelActive,
});
+ requestLocalPromptQueueStop();
clearCheckpoint();
await refresh();
}
@@ -1830,6 +1894,10 @@ export function useChatModelRuntime() {
error instanceof Error ? error.message : "Failed to unload model";
setModelsError(message);
return false;
+ } finally {
+ if (lifecycleLease !== null) {
+ useChatRuntimeStore.getState().endModelLoading(lifecycleLease);
+ }
}
}, [clearCheckpoint, params.checkpoint, refresh, setModelsError]);
diff --git a/studio/frontend/src/features/chat/hooks/use-chat-sidebar-items.ts b/studio/frontend/src/features/chat/hooks/use-chat-sidebar-items.ts
index 651833102aa..fcc46580eae 100644
--- a/studio/frontend/src/features/chat/hooks/use-chat-sidebar-items.ts
+++ b/studio/frontend/src/features/chat/hooks/use-chat-sidebar-items.ts
@@ -6,8 +6,8 @@ import {
CHAT_HISTORY_UPDATED_EVENT,
notifyChatHistoryUpdated,
} from "../api/chat-api";
-import { useChatRuntimeStore } from "../stores/chat-runtime-store";
import { useChatArtifactsStore } from "../artifacts/store";
+import { useChatRuntimeStore } from "../stores/chat-runtime-store";
import type { ThreadRecord } from "../types";
import {
deleteStoredChatThreads,
@@ -22,6 +22,7 @@ import {
markChatThreadsDeleted,
removeChatThreadTombstones,
} from "../utils/chat-thread-tombstones";
+import { requestPromptQueueStop } from "../utils/prompt-queue-boundary";
export interface SidebarItem {
type: "single" | "compare";
@@ -58,6 +59,7 @@ export function groupThreads(
if (t.pairId) {
const existing = pairItems.get(t.pairId);
if (existing) {
+ existing.createdAt = Math.max(existing.createdAt, t.createdAt);
existing.updatedAt = Math.max(existing.updatedAt, lastActivityAt(t));
existing.threadIds?.push(t.id);
continue;
@@ -77,6 +79,7 @@ export function groupThreads(
items.push({
type: "single",
id: t.id,
+ threadIds: [t.id],
title: t.title,
createdAt: t.createdAt,
updatedAt: lastActivityAt(t),
@@ -207,7 +210,11 @@ export async function archiveChatItem(
})
).map((t) => t.id);
- for (const id of threadIds) cancelIfRunning(id);
+ requestPromptQueueStop(threadIds);
+
+ for (const id of threadIds) {
+ cancelIfRunning(id);
+ }
await Promise.all(
threadIds.map((id) => updateStoredChatThread(id, { archived: true })),
@@ -231,6 +238,7 @@ export async function archiveAllChatItems(
const toArchive = threads.filter((t) => !t.archived);
if (toArchive.length === 0) return 0;
+ requestPromptQueueStop(toArchive.map((thread) => thread.id));
for (const t of toArchive) cancelIfRunning(t.id);
await Promise.all(
@@ -283,9 +291,12 @@ export async function deleteChatItem(
? [item.id]
: (await listStoredChatThreads({ pairId: item.id })).map((t) => t.id);
- // Stop any in-flight streams before deleting, so the model doesn't keep
- // generating against a thread that no longer exists.
- for (const id of threadIds) cancelIfRunning(id);
+ // Stop queued prompts and in-flight streams before deleting.
+ requestPromptQueueStop(threadIds);
+
+ for (const id of threadIds) {
+ cancelIfRunning(id);
+ }
// Drop saved composer drafts so deleted threads leave no orphan keys.
for (const id of threadIds) clearComposerDraft(id);
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index 55ca654990f..e304fc397b5 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -72,6 +72,47 @@ export { useChatSearchStore } from "./stores/chat-search-store";
export { usePinnedChatsStore } from "./stores/pinned-chats-store";
export { usePinnedProjectsStore } from "./stores/pinned-projects-store";
export { useChatPreferencesStore } from "./stores/chat-preferences-store";
+export {
+ usePromptQueueUI,
+ type PromptQueueUIEntry,
+ type PromptQueueUIItem,
+ type PromptQueueUIItemStatus,
+ type PromptQueueUIState,
+} from "./stores/prompt-queue-ui-store";
+export {
+ notifyPromptQueueRunFailed,
+ PROMPT_QUEUE_RUN_FAILED_EVENT,
+ PROMPT_QUEUE_STOP_EVENT,
+ requestLocalPromptQueueStop,
+ type PromptQueueRunFailedEventDetail,
+ type PromptQueueStopEventDetail,
+} from "./utils/prompt-queue-boundary";
+export {
+ adoptPreStreamRunReservation,
+ findPreStreamRunReservation,
+ hasPreStreamRunReservation,
+ preStreamRunThreadIdsForAdapter,
+ preStreamRunThreadIdsForRuntime,
+ releasePreStreamRunForThreadIds,
+ releasePreStreamRunReservation,
+ reservePreStreamRun,
+} from "./utils/pre-stream-run-reservation";
+export {
+ localPromptQueueModelBoundary,
+ planLocalPromptQueueStop,
+ shouldAbortPendingQueueForModelBoundary,
+ shouldAbortPendingQueueForSettingsChange,
+} from "./utils/prompt-queue-model-boundary";
+export { chatHistoryClearBoundary } from "./utils/chat-history-clear-boundary";
+export {
+ addQueuedChatRunSettingsThreadIds,
+ consumeQueuedChatRunSettings,
+ discardQueuedChatRunSettings,
+ discardQueuedChatRunSettingsForThread,
+ registerQueuedChatRunSettings,
+ snapshotQueuedChatRunSettings,
+ type QueuedChatRunSettings,
+} from "./utils/queued-chat-run-settings";
export {
PLUS_MENU_ORDER,
usePlusMenuPrefsStore,
@@ -95,7 +136,12 @@ export { setTrainingCompareHandoff } from "./lib/training-compare-handoff";
export type { ProjectRecord } from "./types";
export { clearAllChats, countAllChats } from "./utils/clear-all-chats";
export { pasteClipboardFiles } from "./utils/clipboard-files";
-export { listStoredChatThreads } from "./utils/chat-history-storage";
+export {
+ deleteStoredChatThreads,
+ listStoredChatThreads,
+ markThreadIncognito,
+} from "./utils/chat-history-storage";
+export { markChatThreadDeleted } from "./utils/chat-thread-tombstones";
export { emitChatAttachmentDeleted } from "./utils/chat-attachment-events";
export { resolveReasoningGroupDuration } from "./utils/reasoning-duration";
export { ArtifactCard } from "./artifacts/artifact-card";
diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsx
index 823bd2dda69..d715f57e1b2 100644
--- a/studio/frontend/src/features/chat/runtime-provider.tsx
+++ b/studio/frontend/src/features/chat/runtime-provider.tsx
@@ -4,6 +4,7 @@
import { authFetch } from "@/features/auth";
import {
AssistantRuntimeProvider,
+ type Attachment,
type AttachmentAdapter,
type ChatModelAdapter,
type CompleteAttachment,
@@ -60,6 +61,19 @@ import {
import { AudioAttachmentAdapter } from "./audio-attachment-adapter";
import { useChatRuntimeStore } from "./stores/chat-runtime-store";
import { ToolPaneScopeContext, toolPaneScope } from "./tool-output-scope";
+import {
+ notifyPromptQueueRunFailed,
+ requestPromptQueueStop,
+ requestTemporaryPromptQueueStop,
+} from "./utils/prompt-queue-boundary";
+import {
+ adoptPreStreamRunReservation,
+ claimPreStreamRunReservation,
+ findPreStreamRunReservation,
+ isPreStreamRunReservationCancelled,
+ preStreamRunThreadIdsForRuntime,
+ releasePreStreamRunReservation,
+} from "./utils/pre-stream-run-reservation";
import type { MessageRecord, ModelType, ThreadRecord } from "./types";
import {
chatContentPartAttachmentIdFromSignature,
@@ -82,10 +96,13 @@ import {
saveStoredChatThread,
updateStoredChatThread,
} from "./utils/chat-history-storage";
-import { isChatThreadDeleted } from "./utils/chat-thread-tombstones";
+import {
+ isChatThreadDeleted,
+ markChatThreadDeleted,
+} from "./utils/chat-thread-tombstones";
+import { chatHistoryClearBoundary } from "./utils/chat-history-clear-boundary";
import { syncExportedRepositoryToBackend } from "./utils/delete-thread-message";
import { getImageInputUnavailableReason } from "./utils/image-input-support";
-import { requestPromptQueueStop } from "./utils/prompt-queue-boundary";
import { isAssistantLocalThreadId } from "./utils/thread-ids";
const pendingHistoryAppendByMessageId = new Map<string, Promise<void>>();
@@ -94,6 +111,7 @@ const pendingRunStartReadyByMessageId = new Map<
string,
Promise<string | undefined>
>();
+const pendingRunStartThreadIdsByMessageId = new Map<string, string[]>();
type TitleResponse = {
choices?: Array<{
@@ -104,6 +122,47 @@ type TitleResponse = {
}>;
};
+class PreStreamAwareAttachmentAdapter implements AttachmentAdapter {
+ private readonly delegate: AttachmentAdapter;
+ private readonly getThreadIds: () => Array<string | null | undefined>;
+
+ constructor(
+ delegate: AttachmentAdapter,
+ getThreadIds: () => Array<string | null | undefined>,
+ ) {
+ this.delegate = delegate;
+ this.getThreadIds = getThreadIds;
+ }
+
+ get accept(): string {
+ return this.delegate.accept;
+ }
+
+ add(state: { file: File }) {
+ return this.delegate.add(state);
+ }
+
+ remove(attachment: Attachment): Promise<void> {
+ return this.delegate.remove(attachment);
+ }
+
+ async send(attachment: PendingAttachment): Promise<CompleteAttachment> {
+ const threadIds = this.getThreadIds();
+ const reservationToken = findPreStreamRunReservation(threadIds);
+ try {
+ return await this.delegate.send(attachment);
+ } catch (error) {
+ if (
+ reservationToken &&
+ releasePreStreamRunReservation(reservationToken)
+ ) {
+ notifyPromptQueueRunFailed(threadIds.find(Boolean) ?? null);
+ }
+ throw error;
+ }
+ }
+}
+
class VisionImageAdapter implements AttachmentAdapter {
accept = "image/jpeg,image/png,image/webp,image/gif";
@@ -848,12 +907,28 @@ function trackHistoryAppend(
function trackRunStartReady(
messageId: string,
ready: Promise<string | undefined>,
+ localThreadId: string,
): Promise<string | undefined> {
pendingRunStartReadyByMessageId.set(messageId, ready);
+ pendingRunStartThreadIdsByMessageId.set(messageId, [localThreadId]);
+ ready.then(
+ (remoteId) => {
+ if (
+ remoteId &&
+ pendingRunStartReadyByMessageId.get(messageId) === ready
+ ) {
+ pendingRunStartThreadIdsByMessageId.set(messageId, [
+ ...new Set([localThreadId, remoteId]),
+ ]);
+ }
+ },
+ () => undefined,
+ );
const cleanup = () => {
setTimeout(() => {
if (pendingRunStartReadyByMessageId.get(messageId) === ready) {
pendingRunStartReadyByMessageId.delete(messageId);
+ pendingRunStartThreadIdsByMessageId.delete(messageId);
}
}, 30_000);
};
@@ -861,6 +936,17 @@ function trackRunStartReady(
return ready;
}
+function runStartThreadIdsForMessages(
+ messages: Parameters<ChatModelAdapter["run"]>[0]["messages"],
+): string[] {
+ const userMessage = [...messages]
+ .reverse()
+ .find((message) => message.role === "user");
+ return userMessage
+ ? (pendingRunStartThreadIdsByMessageId.get(userMessage.id) ?? [])
+ : [];
+}
+
async function waitForRunStartHistoryAppend(
messages: Parameters<ChatModelAdapter["run"]>[0]["messages"],
): Promise<string | undefined> {
@@ -892,6 +978,7 @@ async function waitForRunStartHistoryAppend(
pendingRunStartReadyByMessageId.get(userMessage.id) === runStartReady
) {
pendingRunStartReadyByMessageId.delete(userMessage.id);
+ pendingRunStartThreadIdsByMessageId.delete(userMessage.id);
}
}
return adoptedThreadId;
@@ -901,7 +988,59 @@ function createPersistedRunAdapter(adapter: ChatModelAdapter): ChatModelAdapter
return {
...adapter,
async *run(options) {
- const adoptedThreadId = await waitForRunStartHistoryAppend(options.messages);
+ const trackedRunStartThreadIds = runStartThreadIdsForMessages(
+ options.messages,
+ );
+ const reservationThreadIds = preStreamRunThreadIdsForRuntime(
+ [options.unstable_threadId, ...trackedRunStartThreadIds],
+ useChatRuntimeStore.getState().activeThreadId,
+ );
+ const reservationToken =
+ findPreStreamRunReservation(reservationThreadIds);
+ if (reservationToken) {
+ claimPreStreamRunReservation(reservationToken);
+ }
+ const throwIfReservationCancelled = () => {
+ if (
+ reservationToken &&
+ isPreStreamRunReservationCancelled(reservationToken)
+ ) {
+ releasePreStreamRunReservation(reservationToken);
+ throw new DOMException("The send was cancelled", "AbortError");
+ }
+ };
+ throwIfReservationCancelled();
+ const persistedRunThreadIds = preStreamRunThreadIdsForRuntime(
+ [
+ ...reservationThreadIds,
+ ...trackedRunStartThreadIds,
+ ],
+ undefined,
+ );
+ let adoptedThreadId: string | undefined;
+ try {
+ adoptedThreadId = await waitForRunStartHistoryAppend(options.messages);
+ throwIfReservationCancelled();
+ } catch (error) {
+ if (reservationToken) {
+ releasePreStreamRunReservation(reservationToken);
+ }
+ // Queued runs do not carry a direct-send reservation. Their persisted
+ // preflight can still fail before the model adapter consumes the queued
+ // settings. Stop matching pending/waiting work as well as an already
+ // dispatched item so a rapid follow-up cannot run after persistence failed.
+ requestPromptQueueStop(persistedRunThreadIds);
+ notifyPromptQueueRunFailed(
+ options.unstable_threadId ?? persistedRunThreadIds[0] ?? null,
+ );
+ throw error;
+ }
+ if (reservationToken && adoptedThreadId) {
+ adoptPreStreamRunReservation(reservationToken, [
+ ...reservationThreadIds,
+ adoptedThreadId,
+ ]);
+ }
// The thread has an id by the time that resolves, but assistant-ui bound unstable_threadId
// before the await. Hand the run its real id so a first turn never files its handles
// under the unresolved key that concurrent runs share.
@@ -1217,10 +1356,29 @@ function useStudioRuntimeAdapters(
},
append({ parentId, message }: ExportedMessageRepositoryItem) {
- const initializeThread = aui.threadListItem().initialize();
+ const localThreadId = aui.threadListItem().getState().id;
+ const historyClearGeneration = chatHistoryClearBoundary.capture();
+ const throwIfHistoryWasCleared = async (remoteId: string) => {
+ if (
+ chatHistoryClearBoundary.capture() === historyClearGeneration
+ ) {
+ return;
+ }
+ markChatThreadDeleted(remoteId);
+ await deleteStoredChatThreads([remoteId]);
+ throw new DOMException("Chat history was cleared", "AbortError");
+ };
+ const initializeThread = aui
+ .threadListItem()
+ .initialize()
+ .then(async (initialized) => {
+ await throwIfHistoryWasCleared(initialized.remoteId);
+ return initialized;
+ });
trackRunStartReady(
message.id,
initializeThread.then(({ remoteId }) => remoteId),
+ localThreadId,
);
const write = (async () => {
const { remoteId } = await initializeThread;
@@ -1232,17 +1390,29 @@ function useStudioRuntimeAdapters(
// persisted. Compare panes intentionally don't write global activeThreadId.
if (modelType === "base" && !pairId) {
const store = useChatRuntimeStore.getState();
- if (store.activeThreadId !== remoteId) {
+ const visibleThreadId = aui.threads().getState().mainThreadId;
+ if (
+ (visibleThreadId === localThreadId ||
+ visibleThreadId === remoteId) &&
+ store.activeThreadId !== remoteId
+ ) {
store.setActiveThreadId(remoteId);
}
}
const thread = await getStoredChatThread(remoteId);
+ await throwIfHistoryWasCleared(remoteId);
if (thread) {
await ensureStoredChatThread(remoteId, thread);
+ await throwIfHistoryWasCleared(remoteId);
}
if (thread?.modelType === "base" && !thread.pairId) {
const store = useChatRuntimeStore.getState();
- if (store.activeThreadId !== remoteId) {
+ const visibleThreadId = aui.threads().getState().mainThreadId;
+ if (
+ (visibleThreadId === localThreadId ||
+ visibleThreadId === remoteId) &&
+ store.activeThreadId !== remoteId
+ ) {
store.setActiveThreadId(remoteId);
}
}
@@ -1250,7 +1420,9 @@ function useStudioRuntimeAdapters(
const attachments =
message.role === "user" ? cloneAttachments(message.attachments) : [];
const custom = message.metadata?.custom;
- const existingMessage = (await listStoredChatMessages(remoteId)).find(
+ const storedMessages = await listStoredChatMessages(remoteId);
+ await throwIfHistoryWasCleared(remoteId);
+ const existingMessage = storedMessages.find(
(storedMessage) => storedMessage.id === message.id,
);
const createdAt =
@@ -1290,8 +1462,12 @@ function useStudioRuntimeAdapters(
...(metadata && { metadata }),
createdAt,
});
+ await throwIfHistoryWasCleared(remoteId);
})();
- return trackHistoryAppend(message.id, write);
+ return trackHistoryAppend(
+ message.id,
+ chatHistoryClearBoundary.trackPending(write),
+ );
},
}),
[aui, modelType, pairId],
@@ -1310,16 +1486,25 @@ function useStudioRuntimeAdapters(
);
const attachments = useMemo(
() =>
- new CompositeAttachmentAdapter([
- new VisionImageAdapter(),
- new AudioAttachmentAdapter(),
- new TextAttachmentAdapter(),
- new HtmlAttachmentAdapter(),
- new PDFAttachmentAdapter(),
- new DocxAttachmentAdapter(),
- new OpenDocumentAttachmentAdapter(),
- ]),
- [],
+ new PreStreamAwareAttachmentAdapter(
+ new CompositeAttachmentAdapter([
+ new VisionImageAdapter(),
+ new AudioAttachmentAdapter(),
+ new TextAttachmentAdapter(),
+ new HtmlAttachmentAdapter(),
+ new PDFAttachmentAdapter(),
+ new DocxAttachmentAdapter(),
+ new OpenDocumentAttachmentAdapter(),
+ ]),
+ () => {
+ const state = aui.threadListItem().getState();
+ return preStreamRunThreadIdsForRuntime(
+ [state.remoteId, state.id],
+ useChatRuntimeStore.getState().activeThreadId,
+ );
+ },
+ ),
+ [aui],
);
const adapters = useMemo(
() => ({ history, dictation, speech, attachments }),
@@ -1363,11 +1548,9 @@ function ThreadAutoSwitch({
useEffect(() => {
if (!isLoading && mainThreadId !== threadId) {
- if (syncActiveThreadId) {
- // Stop queueing prompts to the outgoing thread but leave its run alone: its runtime
- // stays mounted and keeps streaming. Only an explicit Stop cancels one.
- requestPromptQueueStop({ cancelActiveRun: false });
- }
+ // Saved chats keep running in the background, but a temporary chat is
+ // unreachable after this switch and must not retain an active queue.
+ requestTemporaryPromptQueueStop();
const switchResult = aui.threads().switchToThread(threadId) as unknown;
if (
switchResult &&
@@ -1409,9 +1592,10 @@ function ThreadNewChatSwitch({
if (isLoading) {
return;
}
- // New Chat leaves the previous conversation generating: its runtime stays mounted and
- // the sidebar spins. Stopping it is its own Stop button's job.
- requestPromptQueueStop({ cancelActiveRun: false });
+ // Saved chats keep running in the background. A temporary chat is never
+ // persisted, so abandoning it must also discard its otherwise unreachable
+ // queue. Queue provenance remains reliable even if incognito was cleared first.
+ requestTemporaryPromptQueueStop();
// Switch to a fresh local thread without persisting it yet; persistence
// still happens on first message append.
void aui.threads().switchToNewThread();
@@ -1531,29 +1715,67 @@ function ThreadContextUsageRecount({
}
// Exposes the current thread's cancelRun() via the shared store so external
-// surfaces (e.g. the sidebar trash button) can stop an in-flight stream before
-// deleting the thread, mirroring the Stop -> Trash sequence.
+// surfaces can stop an in-flight stream before deleting the thread.
function CancelRegistrar(): ReactElement | null {
const aui = useAui();
const mainThreadId = useAuiState(({ threads }) => threads.mainThreadId);
- const isRunning = useChatRuntimeStore((s) =>
- mainThreadId ? Boolean(s.runningByThreadId[mainThreadId]) : false,
+ const remoteThreadId = useAuiState(
+ ({ threadListItem }) => threadListItem.remoteId,
);
useEffect(() => {
- if (!mainThreadId || !isRunning) return;
+ if (!mainThreadId) return;
+ const runtime = aui.threads().__internal_getAssistantRuntime?.();
+ const threadIds = Array.from(
+ new Set([mainThreadId, remoteThreadId].filter((id): id is string => Boolean(id))),
+ );
const cancel = () => {
- try {
- aui.thread().cancelRun();
- } catch {
- // Run may have already ended between the caller's read and this call.
+ for (const threadId of threadIds) {
+ try {
+ runtime?.threads.getById(threadId).cancelRun();
+ return;
+ } catch {
+ // Try the other alias; the run may also have ended between reads.
+ }
}
};
- useChatRuntimeStore.getState().registerThreadCancel(mainThreadId, cancel);
+ for (const threadId of threadIds) {
+ useChatRuntimeStore.getState().registerThreadCancel(threadId, cancel);
+ }
return () => {
- useChatRuntimeStore.getState().clearThreadCancel(mainThreadId);
+ const store = useChatRuntimeStore.getState();
+ let thread = null;
+ for (const threadId of threadIds) {
+ try {
+ thread = runtime?.threads.getById(threadId) ?? null;
+ if (thread) break;
+ } catch {
+ // Try the other alias.
+ }
+ }
+ if (!thread?.getState().isRunning) {
+ for (const threadId of threadIds) {
+ store.clearThreadCancel(threadId, cancel);
+ }
+ return;
+ }
+ // assistant-ui enters its running state before adapter preflight turns
+ // on runningByThreadId. Keep the only cancel handle after navigation,
+ // then release it when assistant-ui reports that the run actually ended.
+ let unsubscribe = () => {};
+ unsubscribe = thread.subscribe(() => {
+ if (thread.getState().isRunning) {
+ return;
+ }
+ for (const threadId of threadIds) {
+ useChatRuntimeStore
+ .getState()
+ .clearThreadCancel(threadId, cancel);
+ }
+ unsubscribe();
+ });
};
- }, [aui, mainThreadId, isRunning]);
+ }, [aui, mainThreadId, remoteThreadId]);
return null;
}
diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsx
index b1c1e8973bd..c74fe948c87 100644
--- a/studio/frontend/src/features/chat/shared-composer.tsx
+++ b/studio/frontend/src/features/chat/shared-composer.tsx
@@ -36,6 +36,10 @@ import { isDownloadCancelled } from "@/lib/native-files";
import { isMultimodalResponse } from "./types/api";
import { getImageInputUnavailableReason } from "./utils/image-input-support";
import { pasteClipboardFiles } from "./utils/clipboard-files";
+import { confirmStopRunningChatsIfNeeded } from "./utils/confirm-stop-running-chats";
+import { requestLocalPromptQueueStop } from "./utils/prompt-queue-boundary";
+import { cancelPreStreamRunReservations } from "./utils/pre-stream-run-reservation";
+import type { ModelLifecycleLease } from "./utils/model-lifecycle-gate";
import { useAui } from "@assistant-ui/react";
import {
ArrowUpIcon,
@@ -376,13 +380,37 @@ export function RegisterCompareHandle({
cancel: () => aui.thread().cancelRun(),
isRunning: () => aui.thread().getState().isRunning,
waitForRunEnd: () =>
- new Promise<void>((resolve) => {
- let wasRunning = false;
- const unsub = useChatRuntimeStore.subscribe((state) => {
- const anyRunning = Object.keys(state.runningByThreadId).length > 0;
- if (anyRunning) wasRunning = true;
- if (wasRunning && !anyRunning) {
- unsub();
+ new Promise<void>((resolve, reject) => {
+ const runtime =
+ aui.threads().__internal_getAssistantRuntime?.();
+ const itemState = aui.threadListItem().getState();
+ const threadIds = Array.from(
+ new Set(
+ [itemState.id, itemState.remoteId].filter(
+ (id): id is string => Boolean(id),
+ ),
+ ),
+ );
+ let thread = null;
+ for (const threadId of threadIds) {
+ try {
+ thread = runtime?.threads.getById(threadId) ?? null;
+ if (thread) break;
+ } catch {
+ // Thread hydration can retire an alias; try the next one.
+ }
+ }
+ if (!thread) {
+ reject(new Error("Comparison thread is unavailable"));
+ return;
+ }
+ let wasRunning = thread.getState().isRunning;
+ let unsubscribe = () => {};
+ unsubscribe = thread.subscribe(() => {
+ const isRunning = thread.getState().isRunning;
+ if (isRunning) wasRunning = true;
+ if (wasRunning && !isRunning) {
+ unsubscribe();
resolve();
}
});
@@ -494,6 +522,14 @@ export function SharedComposer({
base64: string;
contentType: string;
} | null>(null);
+ const textRef = useRef(text);
+ const pendingImagesRef = useRef(pendingImages);
+ const pendingAudioRef = useRef(pendingAudio);
+ useEffect(() => {
+ textRef.current = text;
+ pendingImagesRef.current = pendingImages;
+ pendingAudioRef.current = pendingAudio;
+ }, [text, pendingImages, pendingAudio]);
const [dragging, setDragging] = useState(false);
const [isComposing, setIsComposing] = useState(false);
const [newProjectOpen, setNewProjectOpen] = useState(false);
@@ -780,14 +816,21 @@ export function SharedComposer({
return () => clearInterval(id);
}, [handlesRef]);
+ function resetPromptQueue() {
+ if (!isQueueRunningRef.current && queueRef.current.length === 0) {
+ return;
+ }
+ isQueueRunningRef.current = false;
+ setIsQueueRunning(false);
+ queueRef.current = [];
+ queueIndexRef.current = 0;
+ setQueueProgress({ current: 0, total: 0 });
+ }
+
function advanceQueue() {
const nextIndex = queueIndexRef.current + 1;
if (nextIndex >= queueRef.current.length) {
- isQueueRunningRef.current = false;
- setIsQueueRunning(false);
- queueRef.current = [];
- queueIndexRef.current = 0;
- setQueueProgress({ current: 0, total: 0 });
+ resetPromptQueue();
toast.success("Prompt queue complete");
return;
}
@@ -808,11 +851,7 @@ export function SharedComposer({
prevComparingRef.current = comparing;
if (!isQueueRunningRef.current || !wasComparing || comparing) return;
if (!compareStepSucceededRef.current) {
- isQueueRunningRef.current = false;
- setIsQueueRunning(false);
- queueRef.current = [];
- queueIndexRef.current = 0;
- setQueueProgress({ current: 0, total: 0 });
+ resetPromptQueue();
toast.error("Prompt queue stopped", {
description: "A compare step failed; remaining prompts were not sent.",
});
@@ -941,9 +980,18 @@ export function SharedComposer({
useEffect(() => () => clearStuckImeTimer(), []);
async function send() {
- if (composingRef.current) return;
- const msg = text.trim();
- if (!msg && pendingImages.length === 0 && !pendingAudio) return;
+ if (composingRef.current) {
+ resetPromptQueue();
+ return;
+ }
+ const submittedText = text;
+ const submittedImages = pendingImages;
+ const submittedAudio = pendingAudio;
+ const msg = submittedText.trim();
+ if (!msg && submittedImages.length === 0 && !submittedAudio) {
+ resetPromptQueue();
+ return;
+ }
const hasCompareHandles = Boolean(
handlesRef.current["model1"] || handlesRef.current["model2"],
@@ -961,11 +1009,12 @@ export function SharedComposer({
description:
"Use the model dropdown above each pane, then send your prompt.",
});
+ resetPromptQueue();
return;
}
if (
- pendingImages.length > 0 &&
+ submittedImages.length > 0 &&
!isGeneralizedCompare &&
imageUnavailableReason
) {
@@ -974,11 +1023,12 @@ export function SharedComposer({
// for its side, and the chat-adapter's pre-stream gate runs per-side
// against that fresh state.
toast.error(imageUnavailableReason);
+ resetPromptQueue();
return;
}
const content: CompareMessagePart[] = [];
- for (const { file } of pendingImages) {
+ for (const { file } of submittedImages) {
try {
const image = await fileToBase64DataURL(file);
content.push({ type: "image", image });
@@ -986,23 +1036,98 @@ export function SharedComposer({
// skip failed image
}
}
- if (pendingAudio) {
+ if (submittedAudio) {
content.push({
type: "audio",
- name: pendingAudio.name,
- audio: `data:${pendingAudio.contentType};base64,${pendingAudio.base64}`,
+ name: submittedAudio.name,
+ audio: `data:${submittedAudio.contentType};base64,${submittedAudio.base64}`,
});
}
if (msg) {
content.push({ type: "text", text: msg });
}
- if (content.length === 0) return;
+ if (content.length === 0) {
+ resetPromptQueue();
+ return;
+ }
- setText("");
- setPendingImages([]);
- setPendingAudio(null);
- clearPendingAudioStore();
- textareaRef.current?.focus();
+ let compareLifecycleLease: ModelLifecycleLease | null = null;
+ if (isGeneralizedCompare) {
+ compareLifecycleLease = useChatRuntimeStore
+ .getState()
+ .beginModelLoading();
+ if (compareLifecycleLease === null) {
+ toast.info("A model is loading", {
+ description: "Wait for it to finish or cancel it first.",
+ });
+ resetPromptQueue();
+ return;
+ }
+ }
+ const releaseCompareModelLifecycle = () => {
+ if (compareLifecycleLease === null) {
+ return;
+ }
+ useChatRuntimeStore.getState().endModelLoading(compareLifecycleLease);
+ compareLifecycleLease = null;
+ };
+ const acquireCompareModelLifecycle = () => {
+ if (compareLifecycleLease !== null) {
+ return;
+ }
+ compareLifecycleLease = useChatRuntimeStore
+ .getState()
+ .beginModelLoading();
+ if (compareLifecycleLease === null) {
+ throw new Error("Another model load started during comparison");
+ }
+ };
+ const submittedDraftIsCurrent = () =>
+ textRef.current === submittedText &&
+ pendingImagesRef.current === submittedImages &&
+ pendingAudioRef.current === submittedAudio;
+ const keepChangedDraft = () => {
+ releaseCompareModelLifecycle();
+ resetPromptQueue();
+ toast.info("Message changed while preparing", {
+ description: "Your updated draft was kept. Send it again when ready.",
+ });
+ };
+ const clearSubmittedDraft = () => {
+ setText("");
+ setPendingImages([]);
+ setPendingAudio(null);
+ clearPendingAudioStore();
+ textareaRef.current?.focus();
+ };
+
+ let compareStopDecision: Awaited<
+ ReturnType<typeof confirmStopRunningChatsIfNeeded>
+ > | null = null;
+ if (isGeneralizedCompare) {
+ try {
+ compareStopDecision = await confirmStopRunningChatsIfNeeded(
+ "Loading models for comparison",
+ "reload",
+ );
+ } catch (error) {
+ releaseCompareModelLifecycle();
+ resetPromptQueue();
+ toast.error("Compare failed", {
+ description: error instanceof Error ? error.message : "Unknown error",
+ });
+ return;
+ }
+ if (!compareStopDecision.proceed) {
+ releaseCompareModelLifecycle();
+ resetPromptQueue();
+ return;
+ }
+ }
+ if (!submittedDraftIsCurrent()) {
+ keepChangedDraft();
+ return;
+ }
// Generalized compare: load each model before dispatching to its side
if (isGeneralizedCompare) {
@@ -1021,8 +1146,17 @@ export function SharedComposer({
// Warm the device cache before the snapshot below reconciles the GPU
// pick: on a cold cache the reconcile passes a stale pick through.
- if (store.selectedGpuIds != null) {
- await ensureGpuDeviceCache();
+ try {
+ if (store.selectedGpuIds != null) {
+ await ensureGpuDeviceCache();
+ }
+ } catch (error) {
+ releaseCompareModelLifecycle();
+ resetPromptQueue();
+ toast.error("Compare failed", {
+ description: error instanceof Error ? error.message : "Unknown error",
+ });
+ return;
}
// The GPU/offload knobs both compare loads must use, snapshotted at Send.
// ensureModelLoaded runs sequentially and the first load's response echo
@@ -1038,9 +1172,28 @@ export function SharedComposer({
selectedGpuIds: store.selectedGpuIds,
selectedGpuIndexKind: store.selectedGpuIndexKind,
};
+ if (!submittedDraftIsCurrent()) {
+ keepChangedDraft();
+ return;
+ }
+ clearSubmittedDraft();
// Set when an accepted transformers install unloaded the active model
// server-side; a later failure must then clear the stale checkpoint.
let upgradeUnloadedActive = false;
+ const compareSelectionNeedsLoad = (sel: CompareModelSelection) => {
+ const currentStore = useChatRuntimeStore.getState();
+ const isAlreadyActive =
+ currentStore.params.checkpoint === sel.id &&
+ (currentStore.activeGgufVariant ?? null) ===
+ (sel.ggufVariant ?? null);
+ return !isAlreadyActive || sel.config != null || loadedFromConfig;
+ };
+ const applyCompareStopDecision = () => {
+ cancelPreStreamRunReservations(
+ compareStopDecision?.preStreamRunTokens ?? [],
+ );
+ requestLocalPromptQueueStop(compareStopDecision?.promptQueueThreadIds);
+ };
// Helper: load a model and update store checkpoint
async function ensureModelLoaded(
sel: CompareModelSelection,
@@ -1061,6 +1214,7 @@ export function SharedComposer({
(currentStore.activeGgufVariant ?? null) ===
(sel.ggufVariant ?? null);
if (isAlreadyActive && !config && !loadedFromConfig) {
+ applyCompareStopDecision();
return "ready";
}
const targetIsGguf =
@@ -1199,6 +1353,8 @@ export function SharedComposer({
upgrade: validation.transformers_upgrade,
// No installable release: custom-code models may fall back to the trust_remote_code gate below.
trustRemoteCodeFallback: validation.requires_trust_remote_code,
+ forceCancelActive:
+ compareStopDecision?.forceCancelActive ?? false,
});
// The install unloads the active model before the swap (even when the
// swap then fails); if a later gate cancels or the load fails, the UI
@@ -1236,6 +1392,7 @@ export function SharedComposer({
);
}
}
+ applyCompareStopDecision();
const resp = await loadModel({
model_path: sel.id,
hf_token: useChatRuntimeStore.getState().hfToken || null,
@@ -1250,6 +1407,8 @@ export function SharedComposer({
speculative_type: effectiveSpeculativeType,
spec_draft_n_max: effectiveSpecDraftNMax,
tensor_parallel: effectiveTensorParallel,
+ force_cancel_active:
+ compareStopDecision?.forceCancelActive ?? false,
...(targetIsGguf
? {
gpu_memory_mode: effectiveGpuMemoryMode,
@@ -1402,6 +1561,7 @@ export function SharedComposer({
duration: Infinity,
});
const status1 = await ensureModelLoaded(model1);
+ releaseCompareModelLifecycle();
toast("Generating with Model 1…", {
id: toastId,
description: `${name1} (${status1})`,
@@ -1414,10 +1574,18 @@ export function SharedComposer({
// Side 2: load → generate → wait
if (handle2 && model2?.id) {
- const needsLoad =
- model2.id.toLowerCase() !== (model1?.id || "").toLowerCase() ||
- (model2.ggufVariant ?? "") !== (model1?.ggufVariant ?? "");
+ acquireCompareModelLifecycle();
+ const needsLoad = compareSelectionNeedsLoad(model2);
if (needsLoad) {
+ const currentStopDecision =
+ await confirmStopRunningChatsIfNeeded(
+ "Loading the second model for comparison",
+ "reload",
+ );
+ if (!currentStopDecision.proceed) {
+ throw new Error("Second comparison model load cancelled.");
+ }
+ compareStopDecision = currentStopDecision;
toast("Loading Model 2…", {
id: toastId,
description: name2,
@@ -1425,6 +1593,7 @@ export function SharedComposer({
});
}
const status2 = await ensureModelLoaded(model2);
+ releaseCompareModelLifecycle();
toast("Generating with Model 2…", {
id: toastId,
description: `${name2} (${status2})`,
@@ -1439,6 +1608,7 @@ export function SharedComposer({
toast.success("Compare complete", { id: toastId, duration: 2000 });
} catch (err) {
compareStepSucceededRef.current = false;
+ resetPromptQueue();
// The install already unloaded the previously active model; drop the
// checkpoint so the UI does not keep pointing at an unloaded model.
if (upgradeUnloadedActive) {
@@ -1450,10 +1620,12 @@ export function SharedComposer({
duration: 4000,
});
} finally {
+ releaseCompareModelLifecycle();
setComparing(false);
}
} else {
// Original behavior: fire all handles simultaneously
+ clearSubmittedDraft();
for (const handle of Object.values(handlesRef.current)) {
handle.append(content);
}
@@ -2327,11 +2499,7 @@ export function SharedComposer({
<button
type="button"
onClick={() => {
- isQueueRunningRef.current = false;
- setIsQueueRunning(false);
- queueRef.current = [];
- queueIndexRef.current = 0;
- setQueueProgress({ current: 0, total: 0 });
+ resetPromptQueue();
stop();
}}
aria-label="Stop prompt queue"
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 4b71561cc83..7d5da0226bf 100644
--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
@@ -32,6 +32,11 @@ import {
loadChatSettingsWithLegacyImport,
savePersistedChatSettingsPatch,
} from "../utils/chat-settings-storage";
+import {
+ chatModelLifecycleGate,
+ type ModelLifecycleLease,
+} from "../utils/model-lifecycle-gate";
+import { shouldAdvanceQueuedSettingsEpoch } from "../utils/queued-settings-epoch";
import type { ResearchWebsitePolicy } from "../types/research";
import { useExternalProvidersStore } from "./external-providers-store";
import { PLUS_MENU_PINS_STORAGE_KEY } from "./plus-menu-prefs-store";
@@ -1104,6 +1109,8 @@ type ChatRuntimeStore = {
chatTemplateOverride: string | null;
loadedChatTemplateOverride: string | null;
activeThreadId: string | null;
+ activeThreadEpoch: number;
+ queuedSettingsEpoch: number;
activeProjectId: string | null;
/**
* Temporary / incognito chat toggle. When on, the active conversation
@@ -1136,11 +1143,15 @@ type ChatRuntimeStore = {
// re-selection instead of reusing a dead token.
activeNativePathExpiresAtMs: number | null;
hydratePersistedSettings: () => Promise<void>;
- setModelLoading: (loading: boolean) => void;
+ beginModelLoading: () => ModelLifecycleLease | null;
+ endModelLoading: (lease: ModelLifecycleLease) => void;
setLoadingModelPick: (pick: LoadingModelPick | null) => void;
clearLoadingModelPick: (expected: LoadingModelPick) => void;
setModelRequiresTrustRemoteCode: (required: boolean) => void;
- setParams: (params: InferenceParams) => void;
+ setParams: (
+ params: InferenceParams,
+ options?: { persist?: boolean; trackQueuedSettings?: boolean },
+ ) => void;
setCustomPresets: (presets: Preset[]) => void;
setActivePreset: (name: string) => void;
setActivePresetSource: (source: ChatPresetSource) => void;
@@ -1172,14 +1183,18 @@ type ChatRuntimeStore = {
*/
runKeyForOwner: (fallbackKey: string, owner: () => void) => string;
registerThreadCancel: (threadId: string, cancel: () => void) => void;
- clearThreadCancel: (threadId: string) => void;
+ clearThreadCancel: (threadId: string, cancel?: () => void) => void;
registerThreadServerCancel: (threadId: string, cancel: () => void) => void;
clearThreadServerCancel: (threadId: string, cancel?: () => void) => void;
setAutoTitle: (enabled: boolean) => void;
setHfToken: (token: string) => void;
setModelsError: (error: string | null) => void;
setLastModelLoadError: (error: string | null) => void;
- setCheckpoint: (modelId: string, ggufVariant?: string | null) => void;
+ setCheckpoint: (
+ modelId: string,
+ ggufVariant?: string | null,
+ options?: { trackQueuedSettings?: boolean },
+ ) => void;
setActiveThreadId: (threadId: string | null) => void;
setActiveProjectId: (projectId: string | null) => void;
setIncognito: (incognito: boolean) => void;
@@ -1608,6 +1623,8 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
chatTemplateOverride: null,
loadedChatTemplateOverride: null,
activeThreadId: null,
+ activeThreadEpoch: 0,
+ queuedSettingsEpoch: 0,
activeProjectId: null,
incognito: false,
settingsPanelOpen: false,
@@ -1659,7 +1676,18 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
})();
return settingsHydrationPromise;
},
- setModelLoading: (loading) => set({ modelLoading: loading }),
+ beginModelLoading: () => {
+ const lease = chatModelLifecycleGate.tryAcquire();
+ if (lease !== null) {
+ set({ modelLoading: true });
+ }
+ return lease;
+ },
+ endModelLoading: (lease) => {
+ if (chatModelLifecycleGate.release(lease)) {
+ set({ modelLoading: false });
+ }
+ },
setLoadingModelPick: (pick) => set({ loadingModelPick: pick }),
clearLoadingModelPick: (expected) =>
set((state) => {
@@ -1676,12 +1704,21 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
}),
setModelRequiresTrustRemoteCode: (modelRequiresTrustRemoteCode) =>
set({ modelRequiresTrustRemoteCode }),
- setParams: (params) =>
+ setParams: (params, options) =>
set((state) => {
// Bump version unconditionally so a late hydration response won't clobber
// a pre-hydrate user edit; only the HTTP write is gated on settingsHydrated.
const changedParams = getChangedInferenceParams(params, state.params);
- if (state.settingsHydrated && hasKeys(changedParams)) {
+ const queuedSettingsChanged = shouldAdvanceQueuedSettingsEpoch(
+ state.params,
+ params,
+ options?.trackQueuedSettings !== false,
+ );
+ if (
+ options?.persist !== false &&
+ state.settingsHydrated &&
+ hasKeys(changedParams)
+ ) {
saveSettingsPatch({ inferenceParams: changedParams });
}
// Mirror setCheckpoint: the local load path can mutate params.checkpoint
@@ -1690,6 +1727,9 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
const checkpointChanged = state.params.checkpoint !== params.checkpoint;
return {
params,
+ ...(queuedSettingsChanged
+ ? { queuedSettingsEpoch: state.queuedSettingsEpoch + 1 }
+ : {}),
...(checkpointChanged
? { contextUsage: null, contextUsageByThreadId: {} }
: {}),
@@ -1809,9 +1849,10 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
next[threadId] = cancel;
return { cancelByThreadId: next };
}),
- clearThreadCancel: (threadId) =>
+ clearThreadCancel: (threadId, cancel) =>
set((state) => {
if (!(threadId in state.cancelByThreadId)) return state;
+ if (cancel && state.cancelByThreadId[threadId] !== cancel) return state;
const next = { ...state.cancelByThreadId };
delete next[threadId];
return { cancelByThreadId: next };
@@ -1847,7 +1888,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
setHfToken: (hfToken) => useHfTokenStore.getState().setToken(hfToken),
setModelsError: (modelsError) => set({ modelsError }),
setLastModelLoadError: (lastModelLoadError) => set({ lastModelLoadError }),
- setCheckpoint: (modelId, ggufVariant) =>
+ setCheckpoint: (modelId, ggufVariant, options) =>
set((state) => {
// Persist external selections so they survive a refresh. Local ids are
// NOT persisted -- they're re-derived from the backend on mount, and a
@@ -1879,13 +1920,35 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
nextMaxTokens = cap;
}
}
+ const nextGgufVariant = ggufVariant ?? null;
+ const nextDeepResearchEnabled = isExternalModelId(modelId)
+ ? false
+ : state.deepResearchEnabled;
+ const queuedSettingsChanged = shouldAdvanceQueuedSettingsEpoch(
+ {
+ checkpoint: state.params.checkpoint,
+ maxTokens: state.params.maxTokens,
+ ggufVariant: state.activeGgufVariant,
+ deepResearchEnabled: state.deepResearchEnabled,
+ },
+ {
+ checkpoint: modelId,
+ maxTokens: nextMaxTokens,
+ ggufVariant: nextGgufVariant,
+ deepResearchEnabled: nextDeepResearchEnabled,
+ },
+ options?.trackQueuedSettings !== false,
+ );
return {
params: {
...state.params,
checkpoint: modelId,
maxTokens: nextMaxTokens,
},
- activeGgufVariant: ggufVariant ?? null,
+ activeGgufVariant: nextGgufVariant,
+ ...(queuedSettingsChanged
+ ? { queuedSettingsEpoch: state.queuedSettingsEpoch + 1 }
+ : {}),
// Provenance and the spec-fallback reason both describe the model
// being replaced, so they go together on a real change. Dropping only
// one leaves the settings sheet pairing a stale reason with the wrong
@@ -1909,6 +1972,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
setActiveThreadId: (activeThreadId) =>
set((state) => ({
activeThreadId,
+ activeThreadEpoch: state.activeThreadEpoch + 1,
contextUsage: activeThreadId
? (state.contextUsageByThreadId[activeThreadId] ?? null)
: null,
@@ -1931,6 +1995,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
saveLastExternalCheckpoint(null);
saveBool(CHAT_DEEP_RESEARCH_ENABLED_KEY, false);
return set((state) => ({
+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,
params: {
...state.params,
checkpoint: "",
@@ -2008,15 +2073,22 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
}));
},
setReasoningEnabled: (reasoningEnabled, options) =>
- set(() => {
+ set((state) => {
if (options?.persist !== false) {
saveBool(CHAT_REASONING_ENABLED_KEY, reasoningEnabled);
}
- return { reasoningEnabled };
+ return {
+ reasoningEnabled,
+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,
+ };
}),
setLastOpenRouterChosenModel: (lastOpenRouterChosenModel) =>
set({ lastOpenRouterChosenModel }),
- setReasoningStyle: (reasoningStyle) => set({ reasoningStyle }),
+ setReasoningStyle: (reasoningStyle) =>
+ set((state) => ({
+ reasoningStyle,
+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,
+ })),
setReasoningEffort: (reasoningEffort) =>
set((state) => {
setScalarSettingVersion(
@@ -2024,7 +2096,10 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
reasoningEffort,
state.reasoningEffort,
);
- return { reasoningEffort };
+ return {
+ reasoningEffort,
+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,
+ };
}),
setPreserveThinking: (preserveThinking) =>
set((state) => {
@@ -2033,34 +2108,48 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
preserveThinking,
state.preserveThinking,
);
- return { preserveThinking };
+ return {
+ preserveThinking,
+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,
+ };
}),
setToolsEnabled: (toolsEnabled, options) =>
- set(() => {
+ set((state) => {
if (options?.persist !== false) {
saveBool(CHAT_TOOLS_ENABLED_KEY, toolsEnabled);
}
if (toolsEnabled) saveBool(CHAT_DEEP_RESEARCH_ENABLED_KEY, false);
- return toolsEnabled ? { toolsEnabled, deepResearchEnabled: false } : { toolsEnabled };
+ return {
+ ...(toolsEnabled
+ ? { toolsEnabled, deepResearchEnabled: false }
+ : { toolsEnabled }),
+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,
+ };
}),
setCodeToolsEnabled: (codeToolsEnabled) =>
- set(() => {
+ set((state) => {
saveBool(CHAT_CODE_TOOLS_ENABLED_KEY, codeToolsEnabled);
if (codeToolsEnabled) saveBool(CHAT_DEEP_RESEARCH_ENABLED_KEY, false);
- return codeToolsEnabled
- ? { codeToolsEnabled, deepResearchEnabled: false }
- : { codeToolsEnabled };
+ return {
+ ...(codeToolsEnabled
+ ? { codeToolsEnabled, deepResearchEnabled: false }
+ : { codeToolsEnabled }),
+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,
+ };
}),
setImageToolsEnabled: (imageToolsEnabled) =>
- set(() => {
+ set((state) => {
saveBool(CHAT_IMAGE_TOOLS_ENABLED_KEY, imageToolsEnabled);
if (imageToolsEnabled) saveBool(CHAT_DEEP_RESEARCH_ENABLED_KEY, false);
- return imageToolsEnabled
- ? { imageToolsEnabled, deepResearchEnabled: false }
- : { imageToolsEnabled };
+ return {
+ ...(imageToolsEnabled
+ ? { imageToolsEnabled, deepResearchEnabled: false }
+ : { imageToolsEnabled }),
+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,
+ };
}),
setDeepResearchEnabled: (deepResearchEnabled) =>
- set(() => {
+ set((state) => {
saveBool(CHAT_DEEP_RESEARCH_ENABLED_KEY, deepResearchEnabled);
const permissionMode = loadPermissionMode();
if (deepResearchEnabled) {
@@ -2084,23 +2173,33 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
permissionMode,
confirmToolCalls:
permissionMode === "ask" || permissionMode === "auto",
+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,
}
- : { deepResearchEnabled };
+ : {
+ deepResearchEnabled,
+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,
+ };
}),
setResearchWebsitePolicy: (researchWebsitePolicy) =>
- set(() => {
+ set((state) => {
saveResearchWebsitePolicy(researchWebsitePolicy);
- return { researchWebsitePolicy };
+ return {
+ researchWebsitePolicy,
+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,
+ };
}),
setArtifactsEnabled: (artifactsEnabled, options) =>
- set(() => {
+ set((state) => {
if (options?.persist !== false) {
saveBool(CHAT_ARTIFACTS_ENABLED_KEY, artifactsEnabled);
}
if (artifactsEnabled) saveBool(CHAT_DEEP_RESEARCH_ENABLED_KEY, false);
- return artifactsEnabled
- ? { artifactsEnabled, deepResearchEnabled: false }
- : { artifactsEnabled };
+ return {
+ ...(artifactsEnabled
+ ? { artifactsEnabled, deepResearchEnabled: false }
+ : { artifactsEnabled }),
+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,
+ };
}),
setShowCanvasMenuItem: (showCanvasMenuItem) =>
set(() => {
@@ -2131,12 +2230,15 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
return { allowArtifactNetworkAccess };
}),
setMcpEnabledForChat: (mcpEnabledForChat) =>
- set(() => {
+ set((state) => {
saveBool(CHAT_MCP_ENABLED_KEY, mcpEnabledForChat);
if (mcpEnabledForChat) saveBool(CHAT_DEEP_RESEARCH_ENABLED_KEY, false);
- return mcpEnabledForChat
- ? { mcpEnabledForChat, deepResearchEnabled: false }
- : { mcpEnabledForChat };
+ return {
+ ...(mcpEnabledForChat
+ ? { mcpEnabledForChat, deepResearchEnabled: false }
+ : { mcpEnabledForChat }),
+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,
+ };
}),
setConfirmToolCalls: (confirmToolCalls) =>
set((state) => {
@@ -2144,13 +2246,22 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
// The legacy toggle is a view over the permission level: on -> "ask",
// off -> "off" (no prompts). While "full" is active the level is left
// alone (the toggle is disabled in the UI anyway).
- if (state.permissionMode === "full") return { confirmToolCalls };
+ if (state.permissionMode === "full") {
+ return {
+ confirmToolCalls,
+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,
+ };
+ }
const permissionMode: PermissionMode = confirmToolCalls ? "ask" : "off";
savePermissionMode(permissionMode);
- return { confirmToolCalls, permissionMode };
+ return {
+ confirmToolCalls,
+ permissionMode,
+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,
+ };
}),
setPermissionMode: (permissionMode) =>
- set(() => {
+ set((state) => {
// "full" is session-only (never persisted, see init); ask/auto/off
// persist and keep the legacy confirm toggle in sync (the gate is
// requested for both ask and auto).
@@ -2164,18 +2275,24 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
bypassPermissions: true,
confirmToolCalls: false,
deepResearchEnabled: false,
+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,
};
}
const confirmToolCalls =
permissionMode === "ask" || permissionMode === "auto";
saveBool(CHAT_CONFIRM_TOOL_CALLS_KEY, confirmToolCalls);
- return { permissionMode, bypassPermissions: false, confirmToolCalls };
+ return {
+ permissionMode,
+ bypassPermissions: false,
+ confirmToolCalls,
+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,
+ };
}),
setBypassPermissions: (bypassPermissions) =>
// Deliberately not persisted (see init): a reload must not silently keep
// the sandbox/confirmation bypass active without re-accepting the warning.
// Turning bypass off returns to the last persisted ask/auto level.
- set(() => {
+ set((state) => {
if (bypassPermissions) {
// Full access never prompts; mirror confirm_tool_calls=false in the
// store so metadata does not report confirmations as enabled.
@@ -2185,6 +2302,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
permissionMode: "full" as PermissionMode,
confirmToolCalls: false,
deepResearchEnabled: false,
+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,
};
}
const permissionMode = loadPermissionMode();
@@ -2192,6 +2310,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
bypassPermissions,
permissionMode,
confirmToolCalls: permissionMode === "ask" || permissionMode === "auto",
+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,
};
}),
setBypassConfirmOpen: (bypassConfirmOpen) =>
@@ -2226,38 +2345,60 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
return { toolConfirmations: next };
}),
setWebFetchToolsEnabled: (webFetchToolsEnabled) =>
- set(() => {
+ set((state) => {
saveBool(CHAT_WEB_FETCH_TOOLS_ENABLED_KEY, webFetchToolsEnabled);
- return { webFetchToolsEnabled };
+ return {
+ webFetchToolsEnabled,
+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,
+ };
}),
- setRagEnabled: (ragEnabled) => set(() => ({ ragEnabled })),
+ setRagEnabled: (ragEnabled) =>
+ set((state) => ({
+ ragEnabled,
+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,
+ })),
setRagSource: (ragSource) =>
- set(() => {
+ set((state) => {
saveRagSource(ragSource);
- return { ragSource };
+ return {
+ ragSource,
+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,
+ };
}),
setRagMode: (ragMode) =>
- set(() => {
+ set((state) => {
saveString(CHAT_RAG_MODE_KEY, ragMode);
- return { ragMode };
+ return {
+ ragMode,
+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,
+ };
}),
setRagTopK: (ragTopK) =>
- set(() => {
+ set((state) => {
saveString(CHAT_RAG_TOP_K_KEY, String(ragTopK));
- return { ragTopK };
+ return {
+ ragTopK,
+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,
+ };
}),
setRagAutoInject: (ragAutoInject) =>
- set(() => {
+ set((state) => {
saveString(CHAT_RAG_AUTOINJECT_KEY, ragAutoInject);
- return { ragAutoInject };
+ return {
+ ragAutoInject,
+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,
+ };
}),
setRagAutoInjectMinScore: (ragAutoInjectMinScore) =>
- set(() => {
+ set((state) => {
saveString(
CHAT_RAG_AUTOINJECT_MIN_SCORE_KEY,
String(ragAutoInjectMinScore),
);
- return { ragAutoInjectMinScore };
+ return {
+ ragAutoInjectMinScore,
+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,
+ };
}),
setRagOcrScanned: (ragOcrScanned) =>
set(() => {
@@ -2354,7 +2495,10 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
autoHealToolCalls,
state.autoHealToolCalls,
);
- return { autoHealToolCalls };
+ return {
+ autoHealToolCalls,
+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,
+ };
}),
setNudgeToolCalls: (nudgeToolCalls) =>
set((state) => {
@@ -2363,7 +2507,10 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
nudgeToolCalls,
state.nudgeToolCalls,
);
- return { nudgeToolCalls };
+ return {
+ nudgeToolCalls,
+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,
+ };
}),
setMaxToolCallsPerMessage: (maxToolCallsPerMessage) =>
set((state) => {
@@ -2372,7 +2519,10 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
maxToolCallsPerMessage,
state.maxToolCallsPerMessage,
);
- return { maxToolCallsPerMessage };
+ return {
+ maxToolCallsPerMessage,
+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,
+ };
}),
setToolCallTimeout: (toolCallTimeout) =>
set((state) => {
@@ -2381,7 +2531,10 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
toolCallTimeout,
state.toolCallTimeout,
);
- return { toolCallTimeout };
+ return {
+ toolCallTimeout,
+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,
+ };
}),
// Standing preference, but persisted only on a successful load (see
// use-chat-model-runtime), not on selection -- so an unapplied pick the user
diff --git a/studio/frontend/src/features/chat/stores/prompt-queue-ui-store.ts b/studio/frontend/src/features/chat/stores/prompt-queue-ui-store.ts
new file mode 100644
index 00000000000..054d6ea094b
--- /dev/null
+++ b/studio/frontend/src/features/chat/stores/prompt-queue-ui-store.ts
@@ -0,0 +1,47 @@
+// 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 { create } from "zustand";
+
+export type PromptQueueUIEntry = {
+ runId: string;
+ current: number;
+ total: number;
+ local: boolean;
+ temporary: boolean;
+ dispatched: boolean;
+};
+
+export type PromptQueueUIItemStatus =
+ | "queued"
+ | "next"
+ | "waiting"
+ | "running";
+
+export type PromptQueueUIItem = {
+ id: string;
+ runId: string;
+ prompt: string;
+ position: number;
+ total: number;
+ status: PromptQueueUIItemStatus;
+ threadIds: string[];
+ canEdit: boolean;
+ canRemove: boolean;
+};
+
+export interface PromptQueueUIState {
+ byThreadId: Record<string, PromptQueueUIEntry>;
+ current: number;
+ total: number;
+ items: PromptQueueUIItem[];
+ isRunning: boolean;
+}
+
+export const usePromptQueueUI = create<PromptQueueUIState>(() => ({
+ byThreadId: {},
+ current: 0,
+ total: 0,
+ items: [],
+ isRunning: false,
+}));
diff --git a/studio/frontend/src/features/chat/utils/chat-history-clear-boundary.ts b/studio/frontend/src/features/chat/utils/chat-history-clear-boundary.ts
new file mode 100644
index 00000000000..38ca695965a
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/chat-history-clear-boundary.ts
@@ -0,0 +1,30 @@
+export class ChatHistoryClearBoundary {
+ private generation = 0;
+ private pendingPersistence = new Set<Promise<unknown>>();
+
+ capture(): number {
+ return this.generation;
+ }
+
+ advance(): number {
+ this.generation += 1;
+ return this.generation;
+ }
+
+ trackPending<T>(work: Promise<T>): Promise<T> {
+ this.pendingPersistence.add(work);
+ work.then(
+ () => this.pendingPersistence.delete(work),
+ () => this.pendingPersistence.delete(work),
+ );
+ return work;
+ }
+
+ async waitForPending(): Promise<void> {
+ while (this.pendingPersistence.size > 0) {
+ await Promise.allSettled([...this.pendingPersistence]);
+ }
+ }
+}
+
+export const chatHistoryClearBoundary = new ChatHistoryClearBoundary();
diff --git a/studio/frontend/src/features/chat/utils/clear-all-chats.ts b/studio/frontend/src/features/chat/utils/clear-all-chats.ts
index f727e2b03e2..ef20659cf02 100644
--- a/studio/frontend/src/features/chat/utils/clear-all-chats.ts
+++ b/studio/frontend/src/features/chat/utils/clear-all-chats.ts
@@ -1,8 +1,30 @@
// 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 { useChatRuntimeStore } from "../stores/chat-runtime-store";
+import { chatHistoryClearBoundary } from "./chat-history-clear-boundary";
import { clearStoredChats, countStoredChats } from "./chat-history-storage";
+import { requestPromptQueueStop } from "./prompt-queue-boundary";
+import { stopChatThread } from "./stop-chat-thread";
export const countAllChats = countStoredChats;
-export const clearAllChats = clearStoredChats;
+export async function clearAllChats() {
+ // Invalidate fresh-thread initialization before either queue cancellation or
+ // storage enumeration can yield. A late initializer must not recreate a chat
+ // after this clear finishes.
+ chatHistoryClearBoundary.advance();
+ const { runningByThreadId, cancelByThreadId, serverCancelByThreadId } =
+ useChatRuntimeStore.getState();
+ const activeThreadIds = new Set([
+ ...Object.keys(runningByThreadId),
+ ...Object.keys(cancelByThreadId),
+ ...Object.keys(serverCancelByThreadId),
+ ]);
+ for (const threadId of activeThreadIds) {
+ stopChatThread(threadId);
+ }
+ requestPromptQueueStop();
+ await chatHistoryClearBoundary.waitForPending();
+ return await clearStoredChats();
+}
diff --git a/studio/frontend/src/features/chat/utils/confirm-stop-running-chats.ts b/studio/frontend/src/features/chat/utils/confirm-stop-running-chats.ts
index 7b20ceb362c..6524b9e2a08 100644
--- a/studio/frontend/src/features/chat/utils/confirm-stop-running-chats.ts
+++ b/studio/frontend/src/features/chat/utils/confirm-stop-running-chats.ts
@@ -3,23 +3,40 @@
import { getActiveGenerations } from "../api/chat-api";
import { useChatRuntimeStore } from "../stores/chat-runtime-store";
+import { usePromptQueueUI } from "../stores/prompt-queue-ui-store";
import {
type StopRunningChatsEffect,
useStopRunningChatsDialogStore,
} from "../stores/stop-running-chats-dialog-store";
import { listStoredChatThreads } from "./chat-history-storage";
+import { listLocalPreStreamRunReservations } from "./pre-stream-run-reservation";
export interface StopRunningChatsDecision {
/** False when the user chose to keep generating; the caller must not load. */
proceed: boolean;
/** Pass as `force_cancel_active`. True only after an explicit confirmation, so the backend's 409 still guards every other caller. */
forceCancelActive: boolean;
+ /** Local-model prompt queues to stop immediately before the model-changing request. */
+ promptQueueThreadIds: string[];
+ /** Accepted local sends that have not reached the running map yet. */
+ preStreamRunTokens: symbol[];
+}
+
+export function getLocalPromptQueueThreadIds(): string[] {
+ return [
+ ...new Set(
+ Object.entries(usePromptQueueUI.getState().byThreadId)
+ .filter(([, entry]) => entry.local)
+ .map(([threadId]) => threadId),
+ ),
+ ];
}
/**
- * Gate a model load / reload on the chats still generating: they share one llama-server,
- * so a reload ends all of them. Ask first, then let the backend cancel them once the load
- * is past preflight. External-provider chats are left out of both.
+ * Gate a model load / reload on local chats still generating or queued: they share one
+ * llama-server, so a reload ends all of them. Ask first, then let the backend cancel active
+ * runs and return the pending queue targets for the caller to stop after preflight.
+ * External-provider chats and queues are left out of both.
*/
export async function confirmStopRunningChatsIfNeeded(
action = "Loading a different model",
@@ -32,7 +49,45 @@ export async function confirmStopRunningChatsIfNeeded(
let running = Object.entries(runningByThreadId)
.filter(([threadId, on]) => on && localRunByThreadId[threadId])
.map(([threadId]) => threadId);
- let count = running.length;
+ const preStreamRuns = listLocalPreStreamRunReservations();
+ const preStreamRunTokens = preStreamRuns.map(({ token }) => token);
+ let unnamedPreStreamRuns = 0;
+ const runningIds = new Set(running);
+ for (const { threadIds } of preStreamRuns) {
+ if (threadIds.some((id) => runningIds.has(id))) {
+ continue;
+ }
+ if (threadIds.length > 0) {
+ running.push(threadIds[0]);
+ for (const threadId of threadIds) {
+ runningIds.add(threadId);
+ }
+ } else {
+ unnamedPreStreamRuns += 1;
+ }
+ }
+ const promptQueueThreadIds = getLocalPromptQueueThreadIds();
+ const promptQueuesByThreadId = usePromptQueueUI.getState().byThreadId;
+ const aliasesByQueuedRun = new Map<string, string[]>();
+ for (const threadId of promptQueueThreadIds) {
+ const entry = promptQueuesByThreadId[threadId];
+ if (!entry) {
+ continue;
+ }
+ const aliases = aliasesByQueuedRun.get(entry.runId) ?? [];
+ aliases.push(threadId);
+ aliasesByQueuedRun.set(entry.runId, aliases);
+ }
+ for (const aliases of aliasesByQueuedRun.values()) {
+ if (aliases.some((threadId) => runningIds.has(threadId))) {
+ continue;
+ }
+ const threadId = aliases[0];
+ running.push(threadId);
+ runningIds.add(threadId);
+ }
+ running = [...new Set(running)];
+ let count = running.length + unnamedPreStreamRuns;
let hasNonChat = false;
// Always merge the backend snapshot: runningByThreadId is this tab's memory, empty after a
@@ -52,8 +107,8 @@ export async function confirmStopRunningChatsIfNeeded(
// id to merge, so add those back or the prompt names fewer chats than will stop.
const unnamed = entries.filter((entry) => !entry.thread_id).length;
count = entries.length
- ? running.length + unnamed
- : Math.max(active.count ?? 0, running.length);
+ ? running.length + unnamed + unnamedPreStreamRuns
+ : Math.max(active.count ?? 0, running.length) + unnamedPreStreamRuns;
// Embeddings / completions / audio share the model but are not conversations, so the
// prompt must not offer to stop chats that do not exist.
hasNonChat = entries.some((entry) => (entry.kind ?? "chat") !== "chat");
@@ -62,7 +117,12 @@ export async function confirmStopRunningChatsIfNeeded(
}
if (count === 0) {
- return { proceed: true, forceCancelActive: false };
+ return {
+ proceed: true,
+ forceCancelActive: false,
+ promptQueueThreadIds: [],
+ preStreamRunTokens: [],
+ };
}
let titles: string[] = [];
@@ -91,10 +151,20 @@ export async function confirmStopRunningChatsIfNeeded(
.requestConfirm({ count, titles, action, hasNonChat, effect });
if (!confirmed) {
- return { proceed: false, forceCancelActive: false };
+ return {
+ proceed: false,
+ forceCancelActive: false,
+ promptQueueThreadIds: [],
+ preStreamRunTokens: [],
+ };
}
// Deliberately no local stop: the backend holds the cancel until the load clears preflight,
// so stopping now would truncate every chat even for a rejected load.
- return { proceed: true, forceCancelActive: true };
+ return {
+ proceed: true,
+ forceCancelActive: true,
+ promptQueueThreadIds,
+ preStreamRunTokens,
+ };
}
diff --git a/studio/frontend/src/features/chat/utils/model-lifecycle-gate.ts b/studio/frontend/src/features/chat/utils/model-lifecycle-gate.ts
new file mode 100644
index 00000000000..b2e218bbe75
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/model-lifecycle-gate.ts
@@ -0,0 +1,31 @@
+export type ModelLifecycleLease = number;
+
+/**
+ * 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 nextLease = 1;
+
+ tryAcquire(): ModelLifecycleLease | null {
+ if (this.activeLease !== null) {
+ return null;
+ }
+ const lease = this.nextLease++;
+ this.activeLease = lease;
+ return lease;
+ }
+
+ release(lease: ModelLifecycleLease): boolean {
+ if (this.activeLease !== lease) {
+ return false;
+ }
+ this.activeLease = null;
+ return true;
+ }
+}
+
+export const chatModelLifecycleGate = new ModelLifecycleGate();
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
new file mode 100644
index 00000000000..045a4aa2877
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/pre-stream-run-reservation.ts
@@ -0,0 +1,193 @@
+const DEFAULT_THREAD_ID = "__default";
+
+type PreStreamRunReservation = {
+ threadIds: Set<string>;
+ usesLocalModel: boolean;
+ cancel?: (threadIds: string[]) => void;
+ cancelled: boolean;
+ claimed: boolean;
+};
+
+export interface LocalPreStreamRunReservation {
+ token: symbol;
+ threadIds: string[];
+}
+
+export interface PreStreamRunReservationOptions {
+ usesLocalModel: boolean;
+ cancel?: (threadIds: string[]) => void;
+}
+
+const reservations = new Map<symbol, PreStreamRunReservation>();
+const reservationByThreadId = new Map<string, symbol>();
+
+export function preStreamRunThreadIdsForAdapter(
+ unstableThreadId: string | null | undefined,
+ activeThreadId: string | null | undefined,
+): string[] {
+ return preStreamRunThreadIdsForRuntime([unstableThreadId], activeThreadId);
+}
+
+export function preStreamRunThreadIdsForRuntime(
+ runtimeThreadIds: Iterable<string | null | undefined>,
+ activeThreadId: string | null | undefined,
+): string[] {
+ const identifiedThreadIds = [
+ ...new Set(Array.from(runtimeThreadIds).filter(Boolean)),
+ ] as string[];
+ if (identifiedThreadIds.length > 0) {
+ return identifiedThreadIds;
+ }
+ return activeThreadId ? [activeThreadId] : [];
+}
+
+function normalizedThreadIds(
+ threadIds: Iterable<string | null | undefined>,
+): string[] {
+ const ids = [...new Set(Array.from(threadIds).filter(Boolean))] as string[];
+ return ids.length > 0 ? ids : [DEFAULT_THREAD_ID];
+}
+
+export function findPreStreamRunReservation(
+ threadIds: Iterable<string | null | undefined>,
+): symbol | null {
+ for (const threadId of normalizedThreadIds(threadIds)) {
+ const token = reservationByThreadId.get(threadId);
+ if (token) {
+ return token;
+ }
+ }
+ return null;
+}
+
+export function hasPreStreamRunReservation(
+ threadIds: Iterable<string | null | undefined>,
+): boolean {
+ return findPreStreamRunReservation(threadIds) !== null;
+}
+
+export function reservePreStreamRun(
+ threadIds: Iterable<string | null | undefined>,
+ options: PreStreamRunReservationOptions = { usesLocalModel: true },
+): symbol | null {
+ const ids = normalizedThreadIds(threadIds);
+ if (ids.some((threadId) => reservationByThreadId.has(threadId))) {
+ return null;
+ }
+ const token = Symbol("pre-stream-run");
+ reservations.set(token, {
+ threadIds: new Set(ids),
+ usesLocalModel: options.usesLocalModel,
+ cancel: options.cancel,
+ cancelled: false,
+ claimed: false,
+ });
+ for (const threadId of ids) {
+ reservationByThreadId.set(threadId, token);
+ }
+ return token;
+}
+
+export function listLocalPreStreamRunReservations(): LocalPreStreamRunReservation[] {
+ return Array.from(reservations.entries())
+ .filter(
+ ([, reservation]) => reservation.usesLocalModel && !reservation.cancelled,
+ )
+ .map(([token, reservation]) => ({
+ token,
+ threadIds: [...reservation.threadIds].filter(
+ (threadId) => threadId !== DEFAULT_THREAD_ID,
+ ),
+ }));
+}
+
+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);
+ }
+ }
+ return cancelled;
+}
+
+export function claimPreStreamRunReservation(token: symbol): boolean {
+ const reservation = reservations.get(token);
+ if (!reservation || reservation.cancelled) {
+ return false;
+ }
+ reservation.claimed = true;
+ return true;
+}
+
+export function isPreStreamRunReservationCancelled(token: symbol): boolean {
+ return reservations.get(token)?.cancelled ?? false;
+}
+
+export function adoptPreStreamRunReservation(
+ token: symbol,
+ threadIds: Iterable<string | null | undefined>,
+): boolean {
+ const reservation = reservations.get(token);
+ if (!reservation || reservation.cancelled) {
+ return false;
+ }
+ const ids = normalizedThreadIds(threadIds);
+ if (
+ ids.some((threadId) => {
+ const existing = reservationByThreadId.get(threadId);
+ return existing !== undefined && existing !== token;
+ })
+ ) {
+ return false;
+ }
+ for (const threadId of ids) {
+ reservation.threadIds.add(threadId);
+ reservationByThreadId.set(threadId, token);
+ }
+ return true;
+}
+
+export function releasePreStreamRunReservation(token: symbol): boolean {
+ const reservation = reservations.get(token);
+ if (!reservation) {
+ return false;
+ }
+ reservations.delete(token);
+ for (const threadId of reservation.threadIds) {
+ if (reservationByThreadId.get(threadId) === token) {
+ reservationByThreadId.delete(threadId);
+ }
+ }
+ return true;
+}
+
+export function releasePreStreamRunForThreadIds(
+ threadIds: Iterable<string | null | undefined>,
+): boolean {
+ const token = findPreStreamRunReservation(threadIds);
+ return token ? releasePreStreamRunReservation(token) : false;
+}
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 8013917ec82..7d442d7d72e 100644
--- a/studio/frontend/src/features/chat/utils/prompt-queue-boundary.ts
+++ b/studio/frontend/src/features/chat/utils/prompt-queue-boundary.ts
@@ -1,17 +1,84 @@
+import { usePromptQueueUI } from "../stores/prompt-queue-ui-store";
+import { localPromptQueueModelBoundary } from "./prompt-queue-model-boundary";
+
export const PROMPT_QUEUE_STOP_EVENT = "unsloth:prompt-queue-stop";
+export const PROMPT_QUEUE_RUN_FAILED_EVENT = "unsloth:prompt-queue-run-failed";
+
+export type PromptQueueStopEventDetail = {
+ threadIds?: string[];
+ temporaryOnly?: boolean;
+ localOnly?: boolean;
+};
+
+export type PromptQueueRunFailedEventDetail = {
+ threadId?: string | null;
+};
+
+export function requestPromptQueueStop(threadIds?: string[]) {
+ if (
+ typeof window === "undefined" ||
+ (threadIds !== undefined && threadIds.length === 0)
+ ) {
+ return;
+ }
+ window.dispatchEvent(
+ new CustomEvent<PromptQueueStopEventDetail>(PROMPT_QUEUE_STOP_EVENT, {
+ detail: threadIds ? { threadIds } : undefined,
+ }),
+ );
+}
+
+/**
+ * Stop every materialized local queue and invalidate local queue factories
+ * that are still waiting for settings hydration.
+ */
+export function requestLocalPromptQueueStop(
+ additionalThreadIds: string[] = [],
+) {
+ localPromptQueueModelBoundary.advance();
+ const threadIds = [
+ ...new Set([
+ ...additionalThreadIds,
+ ...Object.entries(usePromptQueueUI.getState().byThreadId)
+ .filter(([, entry]) => entry.local)
+ .map(([threadId]) => threadId),
+ ]),
+ ];
+ if (typeof window === "undefined" || threadIds.length === 0) {
+ return;
+ }
+ window.dispatchEvent(
+ new CustomEvent<PromptQueueStopEventDetail>(PROMPT_QUEUE_STOP_EVENT, {
+ detail: { threadIds, localOnly: true },
+ }),
+ );
+}
-export interface PromptQueueStopOptions {
- /** Also cancel the prompt the queue already dispatched. Navigation passes `false` to
- * leave it generating; an explicit stop passes `true` (the default). */
- cancelActiveRun?: boolean;
+export function requestTemporaryPromptQueueStop() {
+ const threadIds = [
+ ...new Set(
+ Object.entries(usePromptQueueUI.getState().byThreadId)
+ .filter(([, entry]) => entry.temporary)
+ .map(([threadId]) => threadId),
+ ),
+ ];
+ if (typeof window !== "undefined") {
+ window.dispatchEvent(
+ new CustomEvent<PromptQueueStopEventDetail>(PROMPT_QUEUE_STOP_EVENT, {
+ detail: { threadIds, temporaryOnly: true },
+ }),
+ );
+ }
}
-export function requestPromptQueueStop(options: PromptQueueStopOptions = {}) {
+export function notifyPromptQueueRunFailed(threadId?: string | null) {
if (typeof window === "undefined") {
return;
}
- const { cancelActiveRun = true } = options;
window.dispatchEvent(
- new CustomEvent(PROMPT_QUEUE_STOP_EVENT, { detail: { cancelActiveRun } }),
+ new CustomEvent<PromptQueueRunFailedEventDetail>(
+ PROMPT_QUEUE_RUN_FAILED_EVENT,
+ { detail: { threadId } },
+ ),
);
}
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
new file mode 100644
index 00000000000..391f78366e5
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/prompt-queue-model-boundary.ts
@@ -0,0 +1,88 @@
+export class PromptQueueModelBoundary {
+ private generation = 0;
+
+ capture(): number {
+ return this.generation;
+ }
+
+ advance(): number {
+ this.generation += 1;
+ return this.generation;
+ }
+}
+
+export const localPromptQueueModelBoundary = new PromptQueueModelBoundary();
+
+export type PromptQueueModelStopItem = {
+ usesLocalModel: boolean;
+ dispatched: boolean;
+};
+
+export type LocalPromptQueueStopPlan = {
+ cancelActiveItem: boolean;
+ activeItemRemoved: boolean;
+ refreshTargetIdleWait: boolean;
+ retainedItemIndexes: number[];
+};
+
+/**
+ * Preserve external-provider work when the singleton local model changes.
+ *
+ * Only local items depend on the outgoing model. A dispatched local item must
+ * be cancelled, but external follow-ups remain valid and can resume once the
+ * thread runtime becomes idle.
+ */
+export function planLocalPromptQueueStop(
+ items: readonly PromptQueueModelStopItem[],
+ runIndex: number,
+): LocalPromptQueueStopPlan {
+ const activeIndex = Math.max(runIndex, 0);
+ const activeItem = items[activeIndex];
+ const retainedItemIndexes = items.flatMap((item, index) =>
+ index < activeIndex || !item.usesLocalModel ? [index] : [],
+ );
+ return {
+ cancelActiveItem: Boolean(
+ activeItem?.usesLocalModel && activeItem.dispatched,
+ ),
+ activeItemRemoved: Boolean(activeItem?.usesLocalModel),
+ refreshTargetIdleWait: Boolean(
+ runIndex < 0 &&
+ activeItem?.usesLocalModel &&
+ retainedItemIndexes.length > 0,
+ ),
+ retainedItemIndexes,
+ };
+}
+
+export function shouldAbortPendingQueueForModelBoundary({
+ capturedGeneration,
+ usesLocalModel,
+ modelLoading,
+}: {
+ capturedGeneration: number;
+ usesLocalModel: boolean;
+ modelLoading: boolean;
+}): boolean {
+ return (
+ usesLocalModel &&
+ (modelLoading ||
+ capturedGeneration !== localPromptQueueModelBoundary.capture())
+ );
+}
+
+export function shouldAbortPendingQueueForSettingsChange({
+ capturedEpoch,
+ currentEpoch,
+ capturedTemporary,
+ currentTemporary,
+}: {
+ capturedEpoch: number;
+ currentEpoch: number;
+ capturedTemporary: boolean;
+ currentTemporary: boolean;
+}): boolean {
+ return (
+ capturedEpoch !== currentEpoch || capturedTemporary !== currentTemporary
+ );
+}
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
new file mode 100644
index 00000000000..1423ceadf07
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/queued-chat-run-settings.ts
@@ -0,0 +1,141 @@
+// 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 { useChatRuntimeStore } from "../stores/chat-runtime-store";
+
+const QUEUED_SETTING_KEYS = [
+ "supportsTools",
+ "supportsReasoning",
+ "reasoningAlwaysOn",
+ "reasoningStyle",
+ "supportsReasoningOff",
+ "reasoningEffortLevels",
+ "supportsPreserveThinking",
+ "reasoningEnabled",
+ "reasoningEffort",
+ "preserveThinking",
+ "toolsEnabled",
+ "codeToolsEnabled",
+ "imageToolsEnabled",
+ "artifactsEnabled",
+ "mcpEnabledForChat",
+ "confirmToolCalls",
+ "bypassPermissions",
+ "permissionMode",
+ "webFetchToolsEnabled",
+ "deepResearchEnabled",
+ "researchWebsitePolicy",
+ "ragEnabled",
+ "ragSource",
+ "ragMode",
+ "ragTopK",
+ "ragAutoInject",
+ "ragAutoInjectMinScore",
+ "ggufContextLength",
+ "autoHealToolCalls",
+ "nudgeToolCalls",
+ "maxToolCallsPerMessage",
+ "toolCallTimeout",
+] as const;
+
+type ChatRuntimeState = ReturnType<typeof useChatRuntimeStore.getState>;
+
+export type QueuedChatRunSettings = Pick<
+ ChatRuntimeState,
+ (typeof QUEUED_SETTING_KEYS)[number]
+> & {
+ params: ChatRuntimeState["params"];
+};
+
+type PendingSettings = {
+ id: number;
+ threadIds: Set<string>;
+ settings: QueuedChatRunSettings;
+};
+
+let nextPendingSettingsId = 1;
+const pendingSettings: PendingSettings[] = [];
+
+export function snapshotQueuedChatRunSettings(
+ state: ChatRuntimeState,
+): QueuedChatRunSettings {
+ const snapshot = {
+ params: { ...state.params },
+ } as QueuedChatRunSettings;
+ for (const key of QUEUED_SETTING_KEYS) {
+ Object.assign(snapshot, { [key]: state[key] });
+ }
+ return snapshot;
+}
+
+export function registerQueuedChatRunSettings(
+ threadIds: string[],
+ settings: QueuedChatRunSettings,
+): number {
+ const id = nextPendingSettingsId++;
+ pendingSettings.push({
+ id,
+ threadIds: new Set(threadIds),
+ settings,
+ });
+ return id;
+}
+
+export function addQueuedChatRunSettingsThreadIds(
+ id: number,
+ threadIds: string[],
+): void {
+ const entry = pendingSettings.find((candidate) => candidate.id === id);
+ if (!entry) {
+ return;
+ }
+ for (const threadId of threadIds) {
+ if (threadId) {
+ entry.threadIds.add(threadId);
+ }
+ }
+}
+
+export function discardQueuedChatRunSettings(id: number): void {
+ const index = pendingSettings.findIndex((entry) => entry.id === id);
+ if (index >= 0) {
+ pendingSettings.splice(index, 1);
+ }
+}
+
+export function discardQueuedChatRunSettingsForThread(
+ threadId?: string | null,
+): void {
+ if (!threadId) {
+ return;
+ }
+ for (let index = pendingSettings.length - 1; index >= 0; index -= 1) {
+ if (pendingSettings[index].threadIds.has(threadId)) {
+ pendingSettings.splice(index, 1);
+ }
+ }
+}
+
+export function hasQueuedChatRunSettings(threadId?: string | null): boolean {
+ return Boolean(
+ threadId && pendingSettings.some((entry) => entry.threadIds.has(threadId)),
+ );
+}
+
+export function consumeQueuedChatRunSettings(
+ threadId?: string | null,
+): QueuedChatRunSettings | null {
+ const index = threadId
+ ? pendingSettings.findIndex((entry) => entry.threadIds.has(threadId))
+ : -1;
+ // Never consume another chat's snapshot as a fallback. Multiple queued
+ // chats can start concurrently, so a "sole pending entry" is not proof that
+ // it belongs to this adapter run.
+ if (index < 0) {
+ return null;
+ }
+ // Tool calls can invoke the adapter multiple times for one assistant run.
+ // Keep the snapshot available until the owning prompt queue observes that
+ // the whole run is idle, then discard it through its registration id.
+ return pendingSettings[index].settings;
+}
diff --git a/studio/frontend/src/features/chat/utils/queued-model-capabilities.ts b/studio/frontend/src/features/chat/utils/queued-model-capabilities.ts
new file mode 100644
index 00000000000..af401a603e3
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/queued-model-capabilities.ts
@@ -0,0 +1,38 @@
+import type { ChatModelSummary } from "../types/runtime";
+
+export type QueuedModelCapabilities = Pick<
+ ChatModelSummary,
+ "isVision" | "isGguf" | "isAudio" | "audioType" | "hasAudioInput"
+>;
+
+/**
+ * Give a queued run an accurate private model entry without changing the
+ * visible chat's model catalog. Status-derived capabilities override stale
+ * catalog values, and a model loaded outside Studio gets a minimal entry.
+ */
+export function mergeQueuedModelCapabilities(
+ models: ChatModelSummary[],
+ checkpoint: string,
+ capabilities: QueuedModelCapabilities | null,
+): ChatModelSummary[] {
+ if (!capabilities) {
+ return models;
+ }
+
+ const index = models.findIndex((model) => model.id === checkpoint);
+ if (index < 0) {
+ return [
+ ...models,
+ {
+ id: checkpoint,
+ name: checkpoint,
+ isLora: false,
+ ...capabilities,
+ },
+ ];
+ }
+
+ return models.map((model, modelIndex) =>
+ modelIndex === index ? { ...model, ...capabilities } : model,
+ );
+}
diff --git a/studio/frontend/src/features/chat/utils/queued-settings-epoch.ts b/studio/frontend/src/features/chat/utils/queued-settings-epoch.ts
new file mode 100644
index 00000000000..da05ff92116
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/queued-settings-epoch.ts
@@ -0,0 +1,18 @@
+export function shouldAdvanceQueuedSettingsEpoch(
+ currentValues: Readonly<object>,
+ nextValues: Readonly<object>,
+ trackQueuedSettings = true,
+): boolean {
+ if (!trackQueuedSettings) {
+ return false;
+ }
+ const keys = new Set([
+ ...Object.keys(currentValues),
+ ...Object.keys(nextValues),
+ ]);
+ const currentRecord = currentValues as Record<string, unknown>;
+ const nextRecord = nextValues as Record<string, unknown>;
+ return Array.from(keys).some(
+ (key) => !Object.is(currentRecord[key], nextRecord[key]),
+ );
+}
diff --git a/studio/frontend/src/features/chat/utils/stop-chat-thread.ts b/studio/frontend/src/features/chat/utils/stop-chat-thread.ts
index ba0fac9aa9a..bd963054de2 100644
--- a/studio/frontend/src/features/chat/utils/stop-chat-thread.ts
+++ b/studio/frontend/src/features/chat/utils/stop-chat-thread.ts
@@ -15,10 +15,13 @@ export function stopChatThread(threadId: string | null | undefined): boolean {
if (!threadId) return false;
const { runningByThreadId, cancelByThreadId, serverCancelByThreadId } =
useChatRuntimeStore.getState();
- if (!runningByThreadId[threadId]) return false;
+ const cancel = cancelByThreadId[threadId];
+ const serverCancels = serverCancelByThreadId[threadId] ?? [];
+ if (!runningByThreadId[threadId] && !cancel && serverCancels.length === 0) {
+ return false;
+ }
let stopped = false;
try {
- const cancel = cancelByThreadId[threadId];
if (cancel) {
cancel();
stopped = true;
@@ -27,7 +30,7 @@ export function stopChatThread(threadId: string | null | undefined): boolean {
// The run may have ended between the read above and this call.
}
// Also after cancelRun(): a proxy that swallows the fetch abort leaves the backend decoding.
- for (const serverCancel of serverCancelByThreadId[threadId] ?? []) {
+ for (const serverCancel of serverCancels) {
try {
serverCancel();
stopped = true;
diff --git a/studio/frontend/tests/chat-history-clear-boundary.test.ts b/studio/frontend/tests/chat-history-clear-boundary.test.ts
new file mode 100644
index 00000000000..3df7a25c375
--- /dev/null
+++ b/studio/frontend/tests/chat-history-clear-boundary.test.ts
@@ -0,0 +1,30 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { ChatHistoryClearBoundary } from "../src/features/chat/utils/chat-history-clear-boundary.ts";
+
+test("a history clear invalidates work captured before it", () => {
+ const boundary = new ChatHistoryClearBoundary();
+ const captured = boundary.capture();
+ assert.equal(boundary.capture(), captured);
+ boundary.advance();
+ assert.notEqual(boundary.capture(), captured);
+});
+
+test("a history clear can drain persistence accepted before it", async () => {
+ const boundary = new ChatHistoryClearBoundary();
+ let finish!: () => void;
+ const pending = new Promise<void>((resolve) => {
+ finish = resolve;
+ });
+ boundary.trackPending(pending);
+ let drained = false;
+ const wait = boundary.waitForPending().then(() => {
+ drained = true;
+ });
+ await Promise.resolve();
+ assert.equal(drained, false);
+ finish();
+ await wait;
+ assert.equal(drained, true);
+});
diff --git a/studio/frontend/tests/model-lifecycle-gate.test.ts b/studio/frontend/tests/model-lifecycle-gate.test.ts
new file mode 100644
index 00000000000..c341cfd6cac
--- /dev/null
+++ b/studio/frontend/tests/model-lifecycle-gate.test.ts
@@ -0,0 +1,22 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { ModelLifecycleGate } from "../src/features/chat/utils/model-lifecycle-gate.ts";
+
+test("the model lifecycle has one owner and ignores stale releases", () => {
+ const gate = new ModelLifecycleGate();
+ const first = gate.tryAcquire();
+
+ assert.notEqual(first, null);
+ if (first === null) {
+ assert.fail("expected the first lifecycle lease");
+ }
+ assert.equal(gate.tryAcquire(), null);
+ assert.equal(gate.release(first + 1), false);
+ assert.equal(gate.tryAcquire(), null);
+ assert.equal(gate.release(first), true);
+
+ const second = gate.tryAcquire();
+ assert.notEqual(second, null);
+ assert.notEqual(second, first);
+});
diff --git a/studio/frontend/tests/pre-stream-run-reservation.test.ts b/studio/frontend/tests/pre-stream-run-reservation.test.ts
new file mode 100644
index 00000000000..5ba16fc4261
--- /dev/null
+++ b/studio/frontend/tests/pre-stream-run-reservation.test.ts
@@ -0,0 +1,136 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ adoptPreStreamRunReservation,
+ cancelPreStreamRunReservations,
+ claimPreStreamRunReservation,
+ findPreStreamRunReservation,
+ hasPreStreamRunReservation,
+ isPreStreamRunReservationCancelled,
+ listLocalPreStreamRunReservations,
+ preStreamRunThreadIdsForAdapter,
+ preStreamRunThreadIdsForRuntime,
+ releasePreStreamRunForThreadIds,
+ releasePreStreamRunReservation,
+ reservePreStreamRun,
+} from "../src/features/chat/utils/pre-stream-run-reservation.ts";
+
+test("adapter thread ids never mix an identified background run with the visible chat", () => {
+ assert.deepEqual(
+ preStreamRunThreadIdsForAdapter("background-thread", "visible-thread"),
+ ["background-thread"],
+ );
+ assert.deepEqual(
+ preStreamRunThreadIdsForAdapter(undefined, "visible-thread"),
+ ["visible-thread"],
+ );
+ assert.deepEqual(preStreamRunThreadIdsForAdapter(undefined, null), []);
+});
+
+test("runtime thread ids use the visible chat only when no runtime identity exists", () => {
+ assert.deepEqual(
+ preStreamRunThreadIdsForRuntime(
+ ["remote-thread", "local-thread"],
+ "visible-thread",
+ ),
+ ["remote-thread", "local-thread"],
+ );
+ assert.deepEqual(
+ preStreamRunThreadIdsForRuntime([null, undefined], "visible-thread"),
+ ["visible-thread"],
+ );
+ assert.deepEqual(
+ preStreamRunThreadIdsForRuntime(["thread", "thread"], null),
+ ["thread"],
+ );
+});
+
+test("pre-stream reservations are immediate and scoped per thread", () => {
+ const first = reservePreStreamRun(["thread-a"]);
+ assert.ok(first);
+ assert.equal(hasPreStreamRunReservation(["thread-a"]), true);
+ assert.equal(reservePreStreamRun(["thread-a"]), null);
+
+ const sibling = reservePreStreamRun(["thread-b"]);
+ assert.ok(sibling);
+ assert.notEqual(sibling, first);
+
+ assert.equal(releasePreStreamRunReservation(first), true);
+ assert.equal(hasPreStreamRunReservation(["thread-a"]), false);
+ assert.equal(hasPreStreamRunReservation(["thread-b"]), true);
+ assert.equal(releasePreStreamRunReservation(sibling), true);
+});
+
+test("a reservation follows thread hydration and releases every alias", () => {
+ const token = reservePreStreamRun(["local-thread"]);
+ assert.ok(token);
+ assert.equal(
+ adoptPreStreamRunReservation(token, ["local-thread", "remote-thread"]),
+ true,
+ );
+ assert.equal(findPreStreamRunReservation(["remote-thread"]), token);
+ assert.equal(releasePreStreamRunForThreadIds(["remote-thread"]), true);
+ assert.equal(hasPreStreamRunReservation(["local-thread"]), false);
+ assert.equal(hasPreStreamRunReservation(["remote-thread"]), false);
+ assert.equal(releasePreStreamRunReservation(token), false);
+});
+
+test("alias adoption cannot steal another thread reservation", () => {
+ const first = reservePreStreamRun(["first-local"]);
+ const second = reservePreStreamRun(["second-local", "shared-remote"]);
+ assert.ok(first);
+ assert.ok(second);
+ assert.equal(
+ adoptPreStreamRunReservation(first, ["first-local", "shared-remote"]),
+ false,
+ );
+ assert.equal(findPreStreamRunReservation(["shared-remote"]), second);
+ assert.equal(releasePreStreamRunReservation(first), true);
+ assert.equal(releasePreStreamRunReservation(second), true);
+});
+
+test("local reservations can be snapshotted and cancelled before streaming", () => {
+ let cancelCount = 0;
+ const local = reservePreStreamRun(["local-thread"], {
+ usesLocalModel: true,
+ cancel: (threadIds) => {
+ assert.deepEqual(threadIds, ["local-thread", "remote-thread"]);
+ cancelCount += 1;
+ },
+ });
+ const external = reservePreStreamRun(["external-thread"], {
+ usesLocalModel: false,
+ });
+ assert.ok(local);
+ assert.ok(external);
+ assert.equal(
+ adoptPreStreamRunReservation(local, ["remote-thread"]),
+ true,
+ );
+ assert.deepEqual(listLocalPreStreamRunReservations(), [
+ { token: local, threadIds: ["local-thread", "remote-thread"] },
+ ]);
+ assert.equal(claimPreStreamRunReservation(local), true);
+ assert.equal(cancelPreStreamRunReservations([local]), 1);
+ assert.equal(cancelCount, 1);
+ assert.equal(isPreStreamRunReservationCancelled(local), true);
+ assert.equal(hasPreStreamRunReservation(["local-thread"]), false);
+ assert.equal(adoptPreStreamRunReservation(local, ["late-alias"]), false);
+ assert.deepEqual(listLocalPreStreamRunReservations(), []);
+ assert.equal(cancelPreStreamRunReservations([local]), 0);
+ assert.equal(releasePreStreamRunReservation(local), true);
+ assert.equal(releasePreStreamRunReservation(external), true);
+});
+
+test("cancelling an unclaimed reservation releases it immediately", () => {
+ const token = reservePreStreamRun(["attachment-thread"], {
+ usesLocalModel: true,
+ });
+ assert.ok(token);
+
+ assert.equal(cancelPreStreamRunReservations([token]), 1);
+ assert.equal(hasPreStreamRunReservation(["attachment-thread"]), false);
+ assert.equal(isPreStreamRunReservationCancelled(token), false);
+ assert.equal(releasePreStreamRunReservation(token), false);
+});
diff --git a/studio/frontend/tests/prompt-queue-model-boundary.test.ts b/studio/frontend/tests/prompt-queue-model-boundary.test.ts
new file mode 100644
index 00000000000..be3d19ea50e
--- /dev/null
+++ b/studio/frontend/tests/prompt-queue-model-boundary.test.ts
@@ -0,0 +1,147 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ localPromptQueueModelBoundary,
+ planLocalPromptQueueStop,
+ shouldAbortPendingQueueForModelBoundary,
+ shouldAbortPendingQueueForSettingsChange,
+} from "../src/features/chat/utils/prompt-queue-model-boundary.ts";
+
+test("a local model stop preserves an active external item", () => {
+ assert.deepEqual(
+ planLocalPromptQueueStop(
+ [
+ { usesLocalModel: false, dispatched: true },
+ { usesLocalModel: true, dispatched: false },
+ { usesLocalModel: false, dispatched: false },
+ ],
+ 0,
+ ),
+ {
+ cancelActiveItem: false,
+ activeItemRemoved: false,
+ refreshTargetIdleWait: false,
+ retainedItemIndexes: [0, 2],
+ },
+ );
+});
+
+test("a dispatched local item is cancelled without losing external follow-ups", () => {
+ assert.deepEqual(
+ planLocalPromptQueueStop(
+ [
+ { usesLocalModel: true, dispatched: true },
+ { usesLocalModel: false, dispatched: false },
+ ],
+ 0,
+ ),
+ {
+ cancelActiveItem: true,
+ activeItemRemoved: true,
+ refreshTargetIdleWait: false,
+ retainedItemIndexes: [1],
+ },
+ );
+});
+
+test("an undispatched local item is dropped without losing external follow-ups", () => {
+ assert.deepEqual(
+ planLocalPromptQueueStop(
+ [
+ { usesLocalModel: true, dispatched: false },
+ { usesLocalModel: false, dispatched: false },
+ ],
+ -1,
+ ),
+ {
+ cancelActiveItem: false,
+ activeItemRemoved: true,
+ refreshTargetIdleWait: true,
+ retainedItemIndexes: [1],
+ },
+ );
+});
+
+test("completed queue history is preserved when pending local work is dropped", () => {
+ assert.deepEqual(
+ planLocalPromptQueueStop(
+ [
+ { usesLocalModel: true, dispatched: true },
+ { usesLocalModel: false, dispatched: true },
+ { usesLocalModel: true, dispatched: false },
+ { usesLocalModel: false, dispatched: false },
+ ],
+ 1,
+ ),
+ {
+ cancelActiveItem: false,
+ activeItemRemoved: false,
+ refreshTargetIdleWait: false,
+ retainedItemIndexes: [0, 1, 3],
+ },
+ );
+});
+
+test("a local model boundary invalidates only pending local factories", () => {
+ const capturedGeneration = localPromptQueueModelBoundary.capture();
+ localPromptQueueModelBoundary.advance();
+
+ assert.equal(
+ shouldAbortPendingQueueForModelBoundary({
+ capturedGeneration,
+ usesLocalModel: true,
+ modelLoading: false,
+ }),
+ true,
+ );
+ assert.equal(
+ shouldAbortPendingQueueForModelBoundary({
+ capturedGeneration,
+ usesLocalModel: false,
+ modelLoading: false,
+ }),
+ false,
+ );
+});
+
+test("a pending local factory cannot materialize during a model load", () => {
+ assert.equal(
+ shouldAbortPendingQueueForModelBoundary({
+ capturedGeneration: localPromptQueueModelBoundary.capture(),
+ usesLocalModel: true,
+ modelLoading: true,
+ }),
+ true,
+ );
+});
+
+test("a hydrated queue aborts when accepted settings or temporary mode changed", () => {
+ assert.equal(
+ shouldAbortPendingQueueForSettingsChange({
+ capturedEpoch: 4,
+ currentEpoch: 4,
+ capturedTemporary: false,
+ currentTemporary: false,
+ }),
+ false,
+ );
+ assert.equal(
+ shouldAbortPendingQueueForSettingsChange({
+ capturedEpoch: 4,
+ currentEpoch: 5,
+ capturedTemporary: false,
+ currentTemporary: false,
+ }),
+ true,
+ );
+ assert.equal(
+ shouldAbortPendingQueueForSettingsChange({
+ capturedEpoch: 4,
+ currentEpoch: 4,
+ capturedTemporary: false,
+ currentTemporary: true,
+ }),
+ true,
+ );
+});
diff --git a/studio/frontend/tests/queued-model-capabilities.test.ts b/studio/frontend/tests/queued-model-capabilities.test.ts
new file mode 100644
index 00000000000..7c413eab0c2
--- /dev/null
+++ b/studio/frontend/tests/queued-model-capabilities.test.ts
@@ -0,0 +1,100 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { getImageInputUnavailableReason } from "../src/features/chat/utils/image-input-support.ts";
+import { mergeQueuedModelCapabilities } from "../src/features/chat/utils/queued-model-capabilities.ts";
+
+test("status capabilities synthesize an audio model missing from the catalog", () => {
+ assert.deepEqual(
+ mergeQueuedModelCapabilities([], "local/audio-model", {
+ isVision: false,
+ isGguf: false,
+ isAudio: true,
+ audioType: "tts",
+ hasAudioInput: false,
+ }),
+ [
+ {
+ id: "local/audio-model",
+ name: "local/audio-model",
+ isLora: false,
+ isVision: false,
+ isGguf: false,
+ isAudio: true,
+ audioType: "tts",
+ hasAudioInput: false,
+ },
+ ],
+ );
+});
+
+test("status capabilities override stale catalog flags", () => {
+ assert.deepEqual(
+ mergeQueuedModelCapabilities(
+ [
+ {
+ id: "local/audio-model",
+ name: "Friendly audio model",
+ isVision: true,
+ isLora: true,
+ isGguf: true,
+ isAudio: false,
+ audioType: null,
+ hasAudioInput: true,
+ },
+ ],
+ "local/audio-model",
+ {
+ isVision: false,
+ isGguf: false,
+ isAudio: true,
+ audioType: "tts",
+ hasAudioInput: false,
+ },
+ ),
+ [
+ {
+ id: "local/audio-model",
+ name: "Friendly audio model",
+ isVision: false,
+ isLora: true,
+ isGguf: false,
+ isAudio: true,
+ audioType: "tts",
+ hasAudioInput: false,
+ },
+ ],
+ );
+});
+
+test("audio-input capability keeps the synthesized model off the output-only path", () => {
+ const [model] = mergeQueuedModelCapabilities([], "local/audio-vlm", {
+ isVision: false,
+ isGguf: false,
+ isAudio: true,
+ audioType: "audio_vlm",
+ hasAudioInput: true,
+ });
+
+ assert.equal(model.isAudio && !model.hasAudioInput, false);
+});
+
+test("synthesized audio-only capability reaches image validation", () => {
+ const [model] = mergeQueuedModelCapabilities([], "local/audio-model", {
+ isVision: false,
+ isGguf: false,
+ isAudio: true,
+ audioType: "tts",
+ hasAudioInput: false,
+ });
+
+ assert.equal(
+ getImageInputUnavailableReason({
+ activeModel: model,
+ isExternalModel: false,
+ loadedIsMultimodal: true,
+ modelLoaded: true,
+ }),
+ "local/audio-model cannot accept images. Load a vision-capable model before attaching images.",
+ );
+});
diff --git a/studio/frontend/tests/queued-settings-epoch.test.ts b/studio/frontend/tests/queued-settings-epoch.test.ts
new file mode 100644
index 00000000000..42f93eee8f6
--- /dev/null
+++ b/studio/frontend/tests/queued-settings-epoch.test.ts
@@ -0,0 +1,23 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { shouldAdvanceQueuedSettingsEpoch } from "../src/features/chat/utils/queued-settings-epoch.ts";
+
+test("no-op status reconciliation does not invalidate a pending queue", () => {
+ const current = {
+ checkpoint: "model",
+ maxTokens: 2048,
+ ggufVariant: "Q4_K_M",
+ };
+ assert.equal(
+ shouldAdvanceQueuedSettingsEpoch(current, { ...current }),
+ false,
+ );
+});
+
+test("real setting changes invalidate pending queues unless tracking is suppressed", () => {
+ const current = { checkpoint: "model-a", maxTokens: 2048 };
+ const next = { checkpoint: "model-b", maxTokens: 2048 };
+ assert.equal(shouldAdvanceQueuedSettingsEpoch(current, next), true);
+ assert.equal(shouldAdvanceQueuedSettingsEpoch(current, next, false), false);
+});
diff --git a/studio/frontend/tests/sidebar-spinner-column.test.ts b/studio/frontend/tests/sidebar-spinner-column.test.ts
index 86aaec8f078..c1b6a749ea3 100644
--- a/studio/frontend/tests/sidebar-spinner-column.test.ts
+++ b/studio/frontend/tests/sidebar-spinner-column.test.ts
@@ -2,8 +2,8 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import assert from "node:assert/strict";
-import test from "node:test";
import { readFile } from "node:fs/promises";
+import test from "node:test";
// Both spinners are ml-auto, so each one sits at its row's padding-right plus
// its own margin-right. The two rows carry different padding, so the margins
@@ -46,19 +46,23 @@ test("nav and Recents spinners land on one trailing column", async () => {
);
const chatSpinner = grab(
source,
- /data-testid="chat-row-spinner"[\s\S]{0,200}?className="(ml-auto[^"]*)"/,
+ /data-testid="chat-row-spinner"[\s\S]{0,400}?className="(ml-auto[^"]*)"/,
"Recents chat spinner",
);
const nav = inset(navRow, "pr") + inset(navSpinner, "mr");
const chat = inset(chatRow, "pr") + inset(chatSpinner, "mr");
- assert.equal(nav, chat, `nav spinner sits ${nav}px in, chat spinner ${chat}px`);
+ assert.equal(
+ nav,
+ chat,
+ `nav spinner sits ${nav}px in, chat spinner ${chat}px`,
+ );
assert.equal(nav, 16);
});
// The kebab overlays the row's right edge, so a spinner row must pad past it.
-test("a generating Recents row clears the kebab on hover", async () => {
+test("a working Recents row clears the kebab on hover", async () => {
const [source, css] = await Promise.all([
readFile(new URL("../src/components/app-sidebar.tsx", import.meta.url), "utf8"),
readFile(new URL("../src/index.css", import.meta.url), "utf8"),
@@ -69,14 +73,15 @@ test("a generating Recents row clears the kebab on hover", async () => {
inset(grab(css, /\.sidebar-row-action-glyph \{\s*@apply ([^;]*);/, "action glyph"), "size");
assert.equal(kebabInset, 30);
- const generating = grab(
+ const working = grab(
source,
- // Anchor on the ternary so only the branch under test can match.
- /isGenerating\s*\?[\s\S]{0,300}?"(group-hover\/recent-item:pr-[^"]*)"/,
- "the isGenerating padding branch",
+ // Anchor on the branch comment so nested spinner ternaries cannot redirect
+ // the match to a pinned or project row.
+ /A spinner glyph cannot truncate[\s\S]{0,120}?"(group-hover\/recent-item:pr-[^"]*)"/,
+ "the showWorkSpinner padding branch",
);
// hover, menu-open and coarse-pointer all reveal the kebab, so all must clear it
- const pads = [...generating.matchAll(/:pr-([0-9.]+)(?: |$)/g)].map(
+ const pads = [...working.matchAll(/:pr-([0-9.]+)(?: |$)/g)].map(
(m) => Number(m[1]) * TAILWIND_UNIT,
);
assert.ok(pads.length >= 3, `expected hover, open and coarse paddings, got ${pads.length}`);
diff --git a/tests/studio/playwright_chat_ui.py b/tests/studio/playwright_chat_ui.py
index 6a139490010..56668d111f7 100644
--- a/tests/studio/playwright_chat_ui.py
+++ b/tests/studio/playwright_chat_ui.py
@@ -950,7 +950,13 @@ with sync_playwright() as p:
page.wait_for_timeout(300)
# ─────────────────────────────────────────────────────
- # 4. Five chat turns, all non-empty.
+ # 4. A follow-up submitted 100 ms after a normal send must queue behind it.
+ # This targets the interval before assistant-ui paints isRunning: without a
+ # synchronous per-thread reservation the second submit starts immediately,
+ # cancels the first turn, and leaves its assistant bubble empty.
+ # ─────────────────────────────────────────────────────
+ # ─────────────────────────────────────────────────────
+ # 4b. Five chat turns, all non-empty.
# ─────────────────────────────────────────────────────
prompts = [
"Reply with exactly: hello",
@@ -1051,6 +1057,39 @@ with sync_playwright() as p:
shoot(f"04-turn-{idx}-still-streaming")
raise
+ step("rapid submit: 100 ms follow-up queues behind the first turn")
+ rapid_bubbles_before = _bubble_count()
+ composer_form = page.locator('form:has(textarea[aria-label="Message input"])').first
+ composer.fill("Reply with exactly: rapid-first")
+ composer_form.evaluate("form => form.requestSubmit()")
+ page.wait_for_timeout(100)
+ composer.fill("Reply with exactly: rapid-second")
+ composer_form.evaluate("form => form.requestSubmit()")
+
+ # The follow-up must materialize as queued work instead of a second direct
+ # append. This control exists only while that queued item is cancellable.
+ page.wait_for_selector(
+ 'button[aria-label="Remove queued prompt 1"]',
+ state = "attached",
+ timeout = 10_000,
+ )
+ page.wait_for_function(
+ """(want) => {
+ const replies = Array.from(
+ document.querySelectorAll('[data-role="assistant"]')
+ ).slice(-2);
+ return replies.length === 2 &&
+ document.querySelectorAll('[data-role="assistant"]').length >= want &&
+ replies.every((reply) => (reply.innerText || '').trim().length > 0) &&
+ !document.querySelector('button[aria-label="Stop generating"]') &&
+ !document.querySelector('button[aria-label="Remove queued prompt 1"]');
+ }""",
+ arg = rapid_bubbles_before + 2,
+ timeout = TURN_TIMEOUT_MS * 2,
+ )
+ shoot("04-rapid-submit-queued")
+ info("OK 100 ms follow-up waited and both assistant turns completed")
+
for i, p_ in enumerate(prompts, start = 1):
step(f"turn {i}: {p_!r}")
send_and_wait(p_, i)
diff --git a/tests/studio/test_chat_autoload_failure_gate.py b/tests/studio/test_chat_autoload_failure_gate.py
index a018bb99082..ebfb2cf07de 100644
--- a/tests/studio/test_chat_autoload_failure_gate.py
+++ b/tests/studio/test_chat_autoload_failure_gate.py
@@ -65,6 +65,24 @@ export function setScenario(scenario: Scenario) {
const GPU_LAYERS_AUTO = -1;
+// The sliced region now includes the queue-specific empty-model resolver and
+// visible-state snapshot helpers, so their imported contracts must exist even
+// though these scenarios call autoLoadSmallestModel directly.
+async function getInferenceStatus() {
+ return { active_model: null };
+}
+function isExternalModelId(value: unknown) {
+ return typeof value === "string" && value.startsWith("external::");
+}
+function resolveInferenceCheckpointId(status: any) {
+ return status.active_model
+ ? (status.model_identifier ?? status.active_model)
+ : null;
+}
+function snapshotQueuedChatRunSettings(state: any) {
+ return { ...state, params: { ...state.params } };
+}
+
function makeStore(): any {
const state: any = {
hfToken: null,
diff --git a/tests/studio/test_deep_research_frontend_contract.py b/tests/studio/test_deep_research_frontend_contract.py
index c8636518ccf..911e3e28fb1 100644
--- a/tests/studio/test_deep_research_frontend_contract.py
+++ b/tests/studio/test_deep_research_frontend_contract.py
@@ -63,7 +63,11 @@ def test_research_mode_is_single_chat_and_detaches_without_cancel() -> None:
# runSignal, not abortSignal: each run gets its own controller, forwarded from the thread
# signal, so one chat's Stop cannot abort a sibling streaming in the background.
assert "if (runSignal.aborted) return" in adapter
- assert "await autoLoadSmallestModel()" in adapter
+ research = adapter.split("if (\n runtime.deepResearchEnabled", 1)[1].split(
+ "const sandboxSessionId", 1
+ )[0]
+ assert "await resolveQueuedEmptyLocalModel(abortSignal)" in research
+ assert "queuedEmptyModelRuntime = resolution.modelRuntime" in research
assert "signal: researchFollowController.signal" in adapter
assert "beginExternalResearchFollow(" in adapter
assert "ragScope" in adapter
@@ -201,9 +205,9 @@ def test_research_presentation_is_integrated() -> None:
assert "effectiveDeepResearchEnabled ? (" in thread
assert "replayFrom: session?.lastAppliedSeq ?? 0" in coordinator
assert "loadBool(CHAT_DEEP_RESEARCH_ENABLED_KEY, false)" in store
- checkpoint_update = store.split("setCheckpoint: (modelId, ggufVariant) =>", 1)[1].split(
- "setActiveThreadId:", 1
- )[0]
+ checkpoint_update = store.split("setCheckpoint: (modelId, ggufVariant, options) =>", 1)[
+ 1
+ ].split("setActiveThreadId:", 1)[0]
assert "saveBool(CHAT_DEEP_RESEARCH_ENABLED_KEY, false)" in checkpoint_update
assert "const permissionMode = loadPermissionMode();" in store
assert "permissionMode," in store
diff --git a/tests/studio/test_first_turn_thread_identity.py b/tests/studio/test_first_turn_thread_identity.py
index 49dbc83ef9c..85f2d4c7901 100644
--- a/tests/studio/test_first_turn_thread_identity.py
+++ b/tests/studio/test_first_turn_thread_identity.py
@@ -55,7 +55,11 @@ def test_the_run_is_given_its_real_thread_id():
)
assert block, "createPersistedRunAdapter's run wrapper not found"
body = block.group(0)
- assert "const adoptedThreadId = await waitForRunStartHistoryAppend(" in body
+ assert "let adoptedThreadId: string | undefined;" in body
+ assert re.search(
+ r"adoptedThreadId\s*=\s*await waitForRunStartHistoryAppend\(",
+ body,
+ ), "the persisted-run preflight must retain the assigned thread id"
assert (
"!options.unstable_threadId && adoptedThreadId" in body
), "only fill in the id when assistant-ui had none"
diff --git a/tests/studio/test_model_picker_contracts.py b/tests/studio/test_model_picker_contracts.py
index f8c6eeabd20..19021fb2d68 100644
--- a/tests/studio/test_model_picker_contracts.py
+++ b/tests/studio/test_model_picker_contracts.py
@@ -595,10 +595,11 @@ def test_local_mtp_warning_covers_path_and_native_gguf_sources():
# Switching models must drop both together: a kept flag would classify the
# newly selected model by the old one's provenance.
store = _read("features/chat/stores/chat-runtime-store.ts")
- reset = re.search(r"setCheckpoint: \(modelId, ggufVariant\) =>.*?\}\),", store, re.S)
- assert reset
- assert "activeModelIsLocal: false" in reset.group(0)
- assert "specFallbackReason: null" in reset.group(0)
+ reset = store.split("setCheckpoint: (modelId, ggufVariant, options) =>", 1)[1].split(
+ "setActiveThreadId:", 1
+ )[0]
+ assert "activeModelIsLocal: false" in reset
+ assert "specFallbackReason: null" in reset
assert "isLocalGguf" in src.split('specFallbackReason === "drafter_not_found"', 1)[1]
@@ -1355,7 +1356,7 @@ def test_parallel_slots_control_cleared_when_the_load_never_sent_them():
# so it cannot swallow the fresh-default path below and stay green.
candidate = adapter.split("async function loadAutoLoadCandidate", 1)[1]
gguf_branch, non_gguf_rest = candidate.split('if (candidate.kind === "gguf") {', 1)[1].split(
- "\n } else {\n", 1
+ "} else {", 1
)
non_gguf_branch = non_gguf_rest.split("if (!(loadResp.is_lora ?? false)) {", 1)[0]
# The cached-GGUF branch keeps the remembered override via the gated local...
diff --git a/tests/studio/test_multi_chat_prompt_queue_contract.py b/tests/studio/test_multi_chat_prompt_queue_contract.py
new file mode 100644
index 00000000000..67092a9fb9b
--- /dev/null
+++ b/tests/studio/test_multi_chat_prompt_queue_contract.py
@@ -0,0 +1,794 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Static contracts for independent per-chat prompt queues."""
+
+import re
+from pathlib import Path
+
+
+REPO = Path(__file__).resolve().parents[2]
+FRONTEND = REPO / "studio/frontend/src"
+THREAD = (FRONTEND / "components/assistant-ui/thread.tsx").read_text(encoding = "utf-8")
+APP_SIDEBAR = (FRONTEND / "components/app-sidebar.tsx").read_text(encoding = "utf-8")
+CHAT_ADAPTER = (FRONTEND / "features/chat/api/chat-adapter.ts").read_text(encoding = "utf-8")
+MODEL_RUNTIME = (FRONTEND / "features/chat/hooks/use-chat-model-runtime.ts").read_text(
+ encoding = "utf-8"
+)
+CONFIRM_MODEL_SWAP = (FRONTEND / "features/chat/utils/confirm-stop-running-chats.ts").read_text(
+ encoding = "utf-8"
+)
+RUNTIME_PROVIDER = (FRONTEND / "features/chat/runtime-provider.tsx").read_text(encoding = "utf-8")
+CHAT_RUNTIME_STORE = (FRONTEND / "features/chat/stores/chat-runtime-store.ts").read_text(
+ encoding = "utf-8"
+)
+CHAT_PAGE = (FRONTEND / "features/chat/chat-page.tsx").read_text(encoding = "utf-8")
+SHARED_COMPOSER = (FRONTEND / "features/chat/shared-composer.tsx").read_text(encoding = "utf-8")
+QUEUE_BOUNDARY = (FRONTEND / "features/chat/utils/prompt-queue-boundary.ts").read_text(
+ encoding = "utf-8"
+)
+QUEUED_MODEL_CAPABILITIES = (
+ FRONTEND / "features/chat/utils/queued-model-capabilities.ts"
+).read_text(encoding = "utf-8")
+PRE_STREAM_RESERVATION = (FRONTEND / "features/chat/utils/pre-stream-run-reservation.ts").read_text(
+ encoding = "utf-8"
+)
+CHAT_CLEAR_BOUNDARY = (FRONTEND / "features/chat/utils/chat-history-clear-boundary.ts").read_text(
+ encoding = "utf-8"
+)
+QUEUED_SETTINGS = (FRONTEND / "features/chat/utils/queued-chat-run-settings.ts").read_text(
+ encoding = "utf-8"
+)
+SIDEBAR_ITEMS = (FRONTEND / "features/chat/hooks/use-chat-sidebar-items.ts").read_text(
+ encoding = "utf-8"
+)
+CLEAR_ALL_CHATS = (FRONTEND / "features/chat/utils/clear-all-chats.ts").read_text(encoding = "utf-8")
+STOP_CHAT_THREAD = (FRONTEND / "features/chat/utils/stop-chat-thread.ts").read_text(
+ encoding = "utf-8"
+)
+
+
+def _between(source: str, start: str, end: str) -> str:
+ assert start in source, f"missing start marker: {start}"
+ tail = source.split(start, 1)[1]
+ assert end in tail, f"missing end marker after {start}: {end}"
+ return tail.split(end, 1)[0]
+
+
+def test_scheduler_dispatches_each_ready_chat_without_a_frontend_global_cap():
+ pump = _between(
+ THREAD,
+ "function pumpPromptQueues()",
+ "async function dispatchQueuedPrompt(",
+ )
+ assert "while (true)" in pump
+ assert pump.index("promptQueueDispatchingRunIds.add(run.id)") < pump.index(
+ "dispatchQueuedPrompt(run, item, run.generation)"
+ )
+ assert "PROMPT_QUEUE_GLOBAL_CONCURRENCY" not in THREAD
+ assert "promptQueueHasCapacity" not in THREAD
+ assert "const reservations = new Map<symbol" in PRE_STREAM_RESERVATION
+ assert "reservationByThreadId" in PRE_STREAM_RESERVATION
+ assert "let preStreamRunReservations = 0" not in PRE_STREAM_RESERVATION
+
+
+def test_each_chat_queue_stays_sequential_and_targets_its_background_runtime():
+ target = _between(
+ THREAD,
+ "const createPromptQueueTarget = useCallback(",
+ "const dismissWaitToast",
+ )
+ state_handler = _between(
+ THREAD,
+ "function handlePromptQueueRunState(",
+ "function ensurePromptQueueSubscription(",
+ )
+ assert "runtime.threads.getById(id)" in target
+ assert "setActiveThreadId" not in target
+ assert "return runningIds.length > 0" not in THREAD
+ assert "isPromptQueueRunTargetRunning(run" in state_handler
+ assert "advancePromptQueue(run)" in state_handler
+ assert "promptQueueActiveRunIds.has(run.id)" in THREAD
+ assert "Boolean(getActivePromptQueueItem(run)?.dispatched)" in THREAD
+ append = _between(
+ THREAD,
+ "function appendQueuedPrompt(",
+ "async function targetHasIndexingDocuments(",
+ )
+ assert "schedulePromptQueueTargetStatePoll(run)" in append
+ indexing_probe = _between(
+ THREAD,
+ "async function targetHasIndexingDocuments(",
+ "function getActivePromptQueueItem(",
+ )
+ assert "const documents = await listThreadDocuments(threadId)" in indexing_probe
+ assert "catch {\n // A failed status probe" in indexing_probe
+ assert "return true;" in indexing_probe
+
+
+def test_saved_queues_survive_navigation_but_abandoned_temporary_queues_stop():
+ saved_switch = _between(
+ RUNTIME_PROVIDER,
+ "function ThreadAutoSwitch(",
+ "function ThreadNewChatSwitch(",
+ )
+ temporary_switch = _between(
+ RUNTIME_PROVIDER,
+ "function ThreadNewChatSwitch(",
+ "function ActiveThreadSync(",
+ )
+ assert "requestPromptQueueStop" not in saved_switch
+ assert "requestTemporaryPromptQueueStop()" in saved_switch
+ assert "switchToThread(threadId)" in saved_switch
+ assert "requestTemporaryPromptQueueStop()" in temporary_switch
+ assert "switchToNewThread()" in temporary_switch
+
+ temporary_toggle = _between(
+ CHAT_PAGE,
+ "const toggleIncognito = useCallback(",
+ "const hydratePersistedSettings",
+ )
+ assert "if (wasIncognito)" in temporary_toggle
+ assert "requestTemporaryPromptQueueStop()" in temporary_toggle
+ assert temporary_toggle.index("requestTemporaryPromptQueueStop()") < temporary_toggle.index(
+ "if (onEmptyScratchChat) return"
+ )
+ cancel_registrar = _between(
+ RUNTIME_PROVIDER,
+ "function CancelRegistrar()",
+ "function ThreadBackendAutosave(",
+ )
+ assert "thread?.getState().isRunning" in cancel_registrar
+ assert "unsubscribe = thread.subscribe(" in cancel_registrar
+ assert "threadListItem.remoteId" in cancel_registrar
+ assert "registerThreadCancel(threadId, cancel)" in cancel_registrar
+ assert "clearThreadCancel(threadId, cancel)" in cancel_registrar
+ assert cancel_registrar.index("thread.subscribe(") < cancel_registrar.rindex(
+ "clearThreadCancel(threadId, cancel)"
+ )
+ assert "state.cancelByThreadId[threadId] !== cancel" in CHAT_RUNTIME_STORE
+
+
+def test_composer_only_queues_behind_the_current_chat():
+ submit = _between(
+ THREAD,
+ "const handleSubmit = useCallback(",
+ "const stopQueue = useCallback(",
+ )
+ assert "aui.thread().getState().isRunning" in submit
+ assert "usePromptQueueUI.getState()" in submit
+ assert "livePreStreamRunActive" in submit
+ assert "liveThreadIsRunning || livePreStreamRunActive" in submit
+ assert "startHydratedPromptQueue(" in submit
+ assert "aui.composer().getState().text.trim() !== queuedPrompt" in submit
+ assert "promptQueueStartPendingRef.current" in THREAD
+ assert "promptQueueStartPendingRef.current.has(reservationKey)" in THREAD
+ assert "promptQueueStartPendingRef.current.delete(reservationKey)" in THREAD
+ assert "promptQueueStartPendingRef.current.set(reservationKey, reservation)" in THREAD
+ assert "temporary: useChatRuntimeStore.getState().incognito" in THREAD
+ assert "localPromptQueueModelBoundary.capture()" in THREAD
+ assert "shouldAbortPendingQueueForModelBoundary" in THREAD
+ assert "queuedSettingsEpoch:" in THREAD
+ assert "shouldAbortPendingQueueForSettingsChange" in THREAD
+ assert "capturedEpoch: reservation.queuedSettingsEpoch" in THREAD
+ assert "currentEpoch: currentQueueSettings.queuedSettingsEpoch" in THREAD
+ assert "capturedTemporary: reservation.temporary" in THREAD
+ assert "currentTemporary: currentQueueSettings.incognito" in THREAD
+ assert "!settingsInvalidated" in THREAD
+ assert "reservation.cancelled = true" in THREAD
+ assert "temporaryOnly && !reservation.temporary" in THREAD
+ assert "onAborted?.()" in THREAD
+ assert 'toast.info("Saved list was not queued"' in THREAD
+ assert ".finally(() =>" in THREAD
+ assert "anyPromptQueueRunning" not in submit
+ assert "promptQueueAtCapacity" not in submit
+ assert "sendReservedComposer();" in submit
+ assert "reservePreStreamRun(preStreamThreadIds, {" in THREAD
+ assert "usesLocalModel:" in THREAD
+ assert "aui.threads().__internal_getAssistantRuntime?.()" in THREAD
+ assert "threads.getById(reservedThreadId).cancelRun()" in THREAD
+ assert "adoptPreStreamRunReservation(token, preStreamThreadIds)" in THREAD
+ assert "hasPreStreamRunReservation(getQueueThreadIds())" in THREAD
+ append_failure = _between(
+ THREAD,
+ "function handleQueuedPromptAppendFailure(",
+ "function consumePromptQueueDeepResearch(",
+ )
+ terminal_failure = append_failure.split(
+ "if (item.dispatchRetries > PROMPT_QUEUE_MAX_DISPATCH_RETRIES)", 1
+ )[1]
+ assert terminal_failure.index("item.target.cancel();") < terminal_failure.index(
+ "deletePromptQueueRun(run);"
+ )
+ assert terminal_failure.index("deletePromptQueueRun(run);") < terminal_failure.index(
+ "item.target.complete();"
+ )
+ assert "releaseCurrentPreStreamRun();" in CHAT_ADAPTER
+ assert "releasePreStreamRunReservation(reservationToken)" in CHAT_ADAPTER
+ assert "class PreStreamAwareAttachmentAdapter" in RUNTIME_PROVIDER
+ assert "preStreamRunThreadIdsForRuntime(" in RUNTIME_PROVIDER
+ attachment_adapter = _between(
+ RUNTIME_PROVIDER,
+ "const attachments = useMemo(",
+ "const adapters = useMemo(",
+ )
+ assert "[state.remoteId, state.id]" in attachment_adapter
+ assert "useChatRuntimeStore.getState().activeThreadId" in attachment_adapter
+ assert "preStreamRunThreadIdsForAdapter(" in CHAT_ADAPTER
+ adapter_wrapper = CHAT_ADAPTER.rsplit("async *run(args)", 1)[1]
+ assert "args.unstable_threadId," in adapter_wrapper
+ assert "useChatRuntimeStore.getState().activeThreadId" in adapter_wrapper
+
+ persisted_wrapper = _between(
+ RUNTIME_PROVIDER,
+ "function createPersistedRunAdapter(",
+ "function useStudioRuntimeAdapters(",
+ )
+ assert persisted_wrapper.index(
+ "const trackedRunStartThreadIds = runStartThreadIdsForMessages("
+ ) < persisted_wrapper.index("findPreStreamRunReservation(reservationThreadIds)")
+ assert "[options.unstable_threadId, ...trackedRunStartThreadIds]" in persisted_wrapper
+ assert "findPreStreamRunReservation(reservationThreadIds)" in persisted_wrapper
+ assert "await waitForRunStartHistoryAppend(options.messages)" in persisted_wrapper
+ assert "releasePreStreamRunReservation(reservationToken)" in persisted_wrapper
+ assert "notifyPromptQueueRunFailed(" in persisted_wrapper
+ persisted_failure = _between(
+ persisted_wrapper,
+ "} catch (error) {",
+ "throw error;",
+ )
+ assert persisted_failure.index("releasePreStreamRunReservation(reservationToken)") < (
+ persisted_failure.index("notifyPromptQueueRunFailed(")
+ )
+ assert re.search(
+ r"releasePreStreamRunReservation\(reservationToken\);\s*}\s*"
+ r"//.*?notifyPromptQueueRunFailed\(",
+ persisted_failure,
+ re.S,
+ ), "queue failure notification must not depend on a direct-send reservation"
+
+
+def test_queued_settings_are_thread_scoped_without_cross_chat_fallback():
+ target = _between(
+ THREAD,
+ "const createPromptQueueTarget = useCallback(",
+ "const dismissWaitToast",
+ )
+ assert "await useChatRuntimeStore.getState().hydratePersistedSettings()" in target
+ assert target.index(
+ "await useChatRuntimeStore.getState().hydratePersistedSettings()"
+ ) < target.index("snapshotQueuedChatRunSettings(chatStateAtQueueStart)")
+ 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 "registerQueuedChatRunSettings(" in target
+ assert "params: { ...runSettingsAtQueueStart.params }" in target
+ assert "runSettingsAtQueueStart.deepResearchEnabled = false" in target
+ assert target.index("const appendResult = thread.append(") < target.index(
+ "runSettingsAtQueueStart.deepResearchEnabled = false"
+ )
+ assert "void (appendResult as Promise<void>).catch(() => undefined)" in target
+ assert "function consumePromptQueueDeepResearch(" in THREAD
+ assert "!item.target.usesDeepResearch" in THREAD
+ assert ".then(() => consumePromptQueueDeepResearch(run, item))" in THREAD
+ assert "usesDeepResearch: runSettingsAtQueueStart.deepResearchEnabled" in target
+ assert "if (existingRun.deepResearchConsumed)" in THREAD
+ assert "addQueuedChatRunSettingsThreadIds(settingsId" in target
+ assert ".getItemById(state.id)\n .initialize()" in target
+ assert "await updateStoredChatThread(remoteId" in target
+ assert "let shouldCorrectPersistedModel: boolean | null = null" in target
+ assert "shouldCorrectPersistedModel ??= !state.remoteId" in target
+ assert "if (shouldCorrectPersistedModel)" in target
+ assert (
+ target.index("await updateStoredChatThread(remoteId")
+ < target.index("shouldCorrectPersistedModel = false")
+ < target.index("const appendResult = thread.append(")
+ )
+ assert 'modelId: runSettingsAtQueueStart.params.checkpoint ?? ""' in target
+ assert target.index("await updateStoredChatThread(remoteId") < target.index(
+ "const appendResult = thread.append("
+ )
+ assert (
+ target.index("addQueuedChatRunSettingsThreadIds(settingsId")
+ < target.index("syncPromptQueueUI()")
+ < target.index("const appendResult = thread.append(")
+ )
+ assert "let cancelled = false" in target
+ assert target.count("cancelled ||") >= 2
+ assert target.count("!pendingSettingsIds.has(settingsId)") >= 2
+ assert target.index("!pendingSettingsIds.has(settingsId)") < target.index(
+ "const appendResult = thread.append("
+ )
+ assert "cancelled = true" in target
+ assert "isTargetCurrentThread() &&" in target
+ assert "consumeQueuedChatRunSettings(resolvedThreadId)" in CHAT_ADAPTER
+ assert '"deepResearchEnabled"' in QUEUED_SETTINGS
+ assert '"supportsReasoning"' in QUEUED_SETTINGS
+ assert '"reasoningAlwaysOn"' in QUEUED_SETTINGS
+ assert '"reasoningStyle"' in QUEUED_SETTINGS
+ assert '"supportsReasoningOff"' in QUEUED_SETTINGS
+ assert '"reasoningEffortLevels"' in QUEUED_SETTINGS
+ assert '"supportsPreserveThinking"' in QUEUED_SETTINGS
+ assert '"researchWebsitePolicy"' in QUEUED_SETTINGS
+ assert CHAT_ADAPTER.index(
+ "consumeQueuedChatRunSettings(resolvedThreadId)"
+ ) < CHAT_ADAPTER.index("if (runtime.deepResearchEnabled && threadAlreadyResearched)")
+ research = _between(
+ CHAT_ADAPTER,
+ "if (\n runtime.deepResearchEnabled",
+ "const sandboxSessionId",
+ )
+ assert "const liveRuntime = useChatRuntimeStore.getState()" in research
+ assert "...queuedRunSettings" in research
+ auto_load_merge = _between(
+ CHAT_ADAPTER,
+ "// Re-read store after auto-load / model-ready wait.",
+ "const { params } = runtime",
+ )
+ assert "...queuedRunSettings.params" in auto_load_merge
+ assert "queuedEmptyModelRuntime?.checkpoint" in auto_load_merge
+ assert "liveRuntime.params.checkpoint" in auto_load_merge
+ assert "liveRuntime.supportsTools" in auto_load_merge
+ assert "liveRuntime.supportsReasoning" in auto_load_merge
+ assert "liveRuntime.ggufContextLength" in auto_load_merge
+ assert "isExternalModelId(visibleState.params.checkpoint)" in CHAT_ADAPTER
+ assert "resolveInferenceCheckpointId(status)" in CHAT_ADAPTER
+ assert "skipAdoptServerModel: true" in CHAT_ADAPTER
+ assert "snapshotVisibleModelState(" in CHAT_ADAPTER
+ assert "restoreVisibleModelState(visibleExternalState)" in CHAT_ADAPTER
+ assert '"ggufContextLength"' in CHAT_ADAPTER
+ assert '"ggufMaxContextLength"' in CHAT_ADAPTER
+ assert '"ggufNativeContextLength"' in CHAT_ADAPTER
+ assert '"loadedIsMultimodal"' in CHAT_ADAPTER
+ assert '"loadedIsDiffusion"' in CHAT_ADAPTER
+ assert (
+ '"contextUsage"'
+ not in CHAT_ADAPTER[
+ CHAT_ADAPTER.index("const VISIBLE_MODEL_RUNTIME_KEYS") : CHAT_ADAPTER.index(
+ "] as const satisfies", CHAT_ADAPTER.index("const VISIBLE_MODEL_RUNTIME_KEYS")
+ )
+ ]
+ )
+ assert "contextUsage: liveUsage.contextUsage" in CHAT_ADAPTER
+ assert "contextUsageByThreadId: liveUsage.contextUsageByThreadId" in CHAT_ADAPTER
+ assert "visibleState.activeThreadEpoch" in CHAT_ADAPTER
+ assert "activeThreadEpoch ===" in CHAT_ADAPTER
+ assert "visibleState.queuedSettingsEpoch" in CHAT_ADAPTER
+ assert "queuedSettingsEpoch ===" in CHAT_ADAPTER
+ assert "preserveVisibleSettings: true" in CHAT_ADAPTER
+ assert "captureResolvedRuntime: (runtime) =>" in CHAT_ADAPTER
+ assert "applyAutoLoadRuntimeState(options" in CHAT_ADAPTER
+ assert CHAT_ADAPTER.count("trackQueuedSettings: !options?.preserveVisibleSettings") >= 4
+ assert "const visibleRoute = window.location.href" in CHAT_ADAPTER
+ assert "window.location.href === visibleRoute" in CHAT_ADAPTER
+ assert "trackQueuedSettings: false" in CHAT_ADAPTER
+ assert CHAT_ADAPTER.count("await resolveQueuedEmptyLocalModel(abortSignal)") >= 2
+ assert "persist: !options?.preserveVisibleSettings" in CHAT_ADAPTER
+ assert "beginModelLoading()" in CHAT_ADAPTER
+ assert "endModelLoading(lifecycleLease)" in CHAT_ADAPTER
+ lifecycle = _between(
+ CHAT_ADAPTER,
+ "async function resolveQueuedEmptyLocalModel(",
+ "export function createOpenAIStreamAdapter",
+ )
+ assert lifecycle.index("beginModelLoading()") < lifecycle.index("await getInferenceStatus()")
+ assert lifecycle.index("await getInferenceStatus()") < lifecycle.index(
+ "await autoLoadSmallestModel("
+ )
+ assert "getInferenceStatus().catch(() => null)" not in lifecycle
+ assert "const status = await getInferenceStatus();" in lifecycle
+ assert "options?.abortSignal?.throwIfAborted()" in CHAT_ADAPTER
+ assert CHAT_ADAPTER.count("await persistResolvedQueuedModel(params.checkpoint)") >= 2
+ assert "notifyQueuedRunFailed" not in CHAT_ADAPTER
+ assert "pendingSettings.length === 1" not in QUEUED_SETTINGS
+ assert "entry.threadIds.has(threadId)" in QUEUED_SETTINGS
+ assert "return pendingSettings[index].settings" in QUEUED_SETTINGS
+ assert "pendingSettings.splice(index, 1)[0].settings" not in QUEUED_SETTINGS
+ assert "complete: discardOldestPendingSettings" in target
+ assert "getActivePromptQueueItem(run)?.target.complete()" in THREAD
+ assert "adapterRunStartedSignals" not in CHAT_ADAPTER
+ assert "pendingSettings.some((entry) => entry.threadIds.has(threadId))" in QUEUED_SETTINGS
+ queued_run_failure = _between(
+ CHAT_ADAPTER,
+ "try {\n yield* adapter.run(args);",
+ "} finally {",
+ )
+ assert "if (!args.abortSignal.aborted)" in queued_run_failure
+ assert queued_run_failure.index("notifyPromptQueueRunFailed(") < queued_run_failure.index(
+ "throw error;"
+ )
+ queue_failure_handler = _between(
+ THREAD,
+ "function handlePromptQueueRunFailed(",
+ 'if (typeof window !== "undefined")',
+ )
+ assert "if (failedRun)" in queue_failure_handler
+ assert "retainPendingPromptQueueItemsAfterFailure(failedRun)" in queue_failure_handler
+ assert "deletePromptQueueRun(failedRun);" in queue_failure_handler
+ retained_failure = _between(
+ THREAD,
+ "function retainPendingPromptQueueItemsAfterFailure(run: PromptQueueRun)",
+ "function cancelPendingPromptQueueFactoriesForStop<",
+ )
+ assert retained_failure.index("activeItem.target.complete();") < retained_failure.index(
+ "run.items.splice(activeIndex, 1);"
+ )
+ assert "waitForPromptQueueTargetIdle(run);" in retained_failure
+ local_queue_stop = _between(
+ THREAD,
+ "function stopLocalPromptQueueRun(run: PromptQueueRun)",
+ "function stopLocalPromptQueueRunsForThreadIds(threadIds: string[])",
+ )
+ assert "if (plan.refreshTargetIdleWait)" in local_queue_stop
+ assert "refreshPromptQueueTargetIdleWait(run);" in local_queue_stop
+ assert "claimPreStreamRunReservation(reservationToken);" in RUNTIME_PROVIDER
+ assert "if (!reservation.claimed)" in PRE_STREAM_RESERVATION
+ assert "loadedIsMultimodal: isMultimodalResponse(status)" in lifecycle
+ assert "isAudio: status.is_audio ?? false" in lifecycle
+ assert "hasAudioInput: status.has_audio_input ?? false" in lifecycle
+ assert CHAT_ADAPTER.count("models: mergeQueuedModelCapabilities(") == 2
+ assert "modelIndex === index ? { ...model, ...capabilities } : model" in (
+ QUEUED_MODEL_CAPABILITIES
+ )
+ assert "loadedIsMultimodal: state.loadedIsMultimodal" in CHAT_ADAPTER
+ assert "queuedEmptyModelRuntime?.loadedIsMultimodal" in auto_load_merge
+ assert "usesLocalModel:" in target
+ assert "usePromptQueueUI.getState().byThreadId" in CONFIRM_MODEL_SWAP
+ assert "getLocalPromptQueueThreadIds" in CONFIRM_MODEL_SWAP
+ assert "promptQueueThreadIds" in MODEL_RUNTIME
+ assert MODEL_RUNTIME.count("requestLocalPromptQueueStop(") >= 4
+ assert MODEL_RUNTIME.index("requestLocalPromptQueueStop();") < MODEL_RUNTIME.index(
+ "const loadResponse = await loadModel("
+ )
+ eject = _between(
+ MODEL_RUNTIME,
+ "const ejectModel = useCallback(",
+ "return {",
+ )
+ select_model = _between(
+ MODEL_RUNTIME,
+ "const selectModel = useCallback(",
+ "const ejectModel = useCallback(",
+ )
+ assert (
+ select_model.index("beginModelLoading()")
+ < select_model.index("await confirmStopRunningChatsIfNeeded(")
+ < select_model.index("cancelPreStreamRunReservations(stopDecision.preStreamRunTokens)")
+ < select_model.index("requestLocalPromptQueueStop(stopDecision.promptQueueThreadIds)")
+ )
+ assert "beginModelLoading()" in eject
+ assert "endModelLoading(lifecycleLease)" in eject
+ assert "beginModelLoading()" in SHARED_COMPOSER
+ assert "endModelLoading(compareLifecycleLease)" in SHARED_COMPOSER
+ assert SHARED_COMPOSER.count("releaseCompareModelLifecycle();") >= 3
+ compare_upgrade = _between(
+ SHARED_COMPOSER,
+ "const upgraded = await confirmTransformersUpgradeIfNeeded({",
+ "});",
+ )
+ assert "forceCancelActive:" in compare_upgrade
+ assert "compareStopDecision?.forceCancelActive ?? false" in compare_upgrade
+ compare_handle = _between(
+ SHARED_COMPOSER,
+ "export function RegisterCompareHandle(",
+ "type PendingImage =",
+ )
+ assert "aui.threads().__internal_getAssistantRuntime?.()" in compare_handle
+ assert "runtime?.threads.getById(threadId)" in compare_handle
+ assert "thread.subscribe(" in compare_handle
+ assert "useChatRuntimeStore.subscribe(" not in compare_handle
+ gpu_discovery = _between(
+ SHARED_COMPOSER,
+ "// Warm the device cache before the snapshot below",
+ "// The GPU/offload knobs both compare loads must use",
+ )
+ assert "await ensureGpuDeviceCache();" in gpu_discovery
+ assert "catch (error) {\n releaseCompareModelLifecycle();" in gpu_discovery
+ side_one = _between(
+ SHARED_COMPOSER,
+ "// Side 1: load → generate → wait",
+ "// Side 2: load → generate → wait",
+ )
+ assert (
+ side_one.index("const status1 = await ensureModelLoaded(model1)")
+ < side_one.index("releaseCompareModelLifecycle();")
+ < side_one.index("handle1.startRun()")
+ )
+ side_two = _between(
+ SHARED_COMPOSER,
+ "// Side 2: load → generate → wait",
+ "compareStepSucceededRef.current = true",
+ )
+ assert (
+ side_two.index("acquireCompareModelLifecycle();")
+ < side_two.index("await confirmStopRunningChatsIfNeeded(")
+ < side_two.index("compareStopDecision = currentStopDecision")
+ < side_two.index("const status2 = await ensureModelLoaded(model2)")
+ < side_two.index("releaseCompareModelLifecycle();")
+ < side_two.index("handle2.startRun()")
+ )
+ assert "requestLocalPromptQueueStop" in eject
+ assert (
+ eject.index("beginModelLoading()")
+ < eject.index("await confirmStopRunningChatsIfNeeded(")
+ < eject.index("cancelPreStreamRunReservations(stopDecision.preStreamRunTokens)")
+ < eject.index("requestLocalPromptQueueStop(stopDecision.promptQueueThreadIds)")
+ )
+ assert "function promptQueueRunUsesLocalModel(run: PromptQueueRun)" in THREAD
+ assert ".slice(Math.max(run.index, 0))" in THREAD
+ assert ".some((item) => item.target.usesLocalModel)" in THREAD
+ assert "local: promptQueueRunUsesLocalModel(run)" in THREAD
+ assert "detail: { threadIds, localOnly: true }" in QUEUE_BOUNDARY
+ assert "stopLocalPromptQueueRunsForThreadIds(threadIds ?? [])" in THREAD
+ local_queue_stop = _between(
+ THREAD,
+ "function stopLocalPromptQueueRun(run: PromptQueueRun)",
+ "function stopLocalPromptQueueRunsForThreadIds(threadIds: string[])",
+ )
+ assert "planLocalPromptQueueStop(" in local_queue_stop
+ assert "activeItem?.target.cancel();" in local_queue_stop
+ assert "waitForPromptQueueTargetIdle(run);" in local_queue_stop
+ pending_factory_stop = _between(
+ THREAD,
+ "function cancelPendingPromptQueueFactoriesForStop<",
+ "function stopAllPromptQueueRuns()",
+ )
+ assert pending_factory_stop.index("if (localOnly)") < pending_factory_stop.index(
+ "for (const [key, reservation]"
+ )
+ assert "cancelPendingPromptQueueFactoriesForStop(" in THREAD
+ assert "temporary: incognitoAtQueueStart" in THREAD
+ assert "temporary: promptQueueRunIsTemporary(run)" in THREAD
+ assert "dispatched: Boolean(getActivePromptQueueItem(run)?.dispatched)" in THREAD
+ assert "queueEntry?.dispatched" in THREAD
+ assert 'aria-label="Stop queued message"' in THREAD
+ assert "entry.temporary" in QUEUE_BOUNDARY
+ assert "localPromptQueueModelBoundary.advance()" in QUEUE_BOUNDARY
+ assert "entry.local" in QUEUE_BOUNDARY
+ assert "queuedRunSettings.params.checkpoint" in CHAT_ADAPTER
+ persisted_adapter = _between(
+ RUNTIME_PROVIDER,
+ "function createPersistedRunAdapter(",
+ "function useStudioRuntimeAdapters(",
+ )
+ assert "const trackedRunStartThreadIds = runStartThreadIdsForMessages(" in persisted_adapter
+ assert "isPreStreamRunReservationCancelled(reservationToken)" in persisted_adapter
+ assert persisted_adapter.count("throwIfReservationCancelled();") == 2
+ assert persisted_adapter.index(
+ "requestPromptQueueStop(persistedRunThreadIds)"
+ ) < persisted_adapter.index("notifyPromptQueueRunFailed(")
+ assert "pendingRunStartThreadIdsByMessageId" in RUNTIME_PROVIDER
+ assert "localThreadId," in RUNTIME_PROVIDER
+ successful_persisted_preflight = _between(
+ RUNTIME_PROVIDER,
+ "async function waitForRunStartHistoryAppend(",
+ "function createPersistedRunAdapter(",
+ )
+ assert successful_persisted_preflight.index(
+ "pendingRunStartReadyByMessageId.delete(userMessage.id)"
+ ) < successful_persisted_preflight.index(
+ "pendingRunStartThreadIdsByMessageId.delete(userMessage.id)"
+ )
+ assert "!runningByThreadId[threadId] && !cancel" in STOP_CHAT_THREAD
+ assert "serverCancels.length === 0" in STOP_CHAT_THREAD
+ assert "await confirmStopRunningChatsIfNeeded(" in SHARED_COMPOSER
+ send_flow = _between(
+ SHARED_COMPOSER,
+ "async function send()",
+ "sendRef.current = send;",
+ )
+ assert "const submittedText = text;" in send_flow
+ assert "const submittedImages = pendingImages;" in send_flow
+ assert "const submittedAudio = pendingAudio;" in send_flow
+ assert "textRef.current === submittedText" in send_flow
+ assert "pendingImagesRef.current === submittedImages" in send_flow
+ assert "pendingAudioRef.current === submittedAudio" in send_flow
+ confirm_index = send_flow.index("await confirmStopRunningChatsIfNeeded(")
+ first_draft_check = send_flow.index("if (!submittedDraftIsCurrent())")
+ gpu_discovery_index = send_flow.index("await ensureGpuDeviceCache();")
+ second_draft_check = send_flow.index(
+ "if (!submittedDraftIsCurrent())",
+ gpu_discovery_index,
+ )
+ assert (
+ send_flow.index("beginModelLoading()")
+ < confirm_index
+ < first_draft_check
+ < gpu_discovery_index
+ < second_draft_check
+ < send_flow.index("clearSubmittedDraft();")
+ )
+ assert "requestLocalPromptQueueStop(" in SHARED_COMPOSER
+ assert "compareStopDecision?.preStreamRunTokens ?? []" in SHARED_COMPOSER
+ assert SHARED_COMPOSER.index("requestLocalPromptQueueStop(") < SHARED_COMPOSER.index(
+ "const resp = await loadModel("
+ )
+ apply_compare_stop = _between(
+ send_flow,
+ "const applyCompareStopDecision = () => {",
+ "// Helper: load a model and update store checkpoint",
+ )
+ assert "cancelPreStreamRunReservations(" in apply_compare_stop
+ assert "compareStopDecision?.preStreamRunTokens ?? []" in apply_compare_stop
+ assert "requestLocalPromptQueueStop(" in apply_compare_stop
+ assert "compareStopDecision?.promptQueueThreadIds" in apply_compare_stop
+ ensure_compare_model = _between(
+ send_flow,
+ "async function ensureModelLoaded(",
+ "// Side 1: load",
+ )
+ already_active = _between(
+ ensure_compare_model,
+ "if (isAlreadyActive && !config && !loadedFromConfig) {",
+ "}",
+ )
+ assert already_active.index("applyCompareStopDecision();") < already_active.index(
+ 'return "ready";'
+ )
+ assert ensure_compare_model.count("applyCompareStopDecision();") == 2
+ validated_load_stop = ensure_compare_model.rindex("applyCompareStopDecision();")
+ assert (
+ ensure_compare_model.index("const validation = await validateModel(")
+ < validated_load_stop
+ < ensure_compare_model.index("const resp = await loadModel(")
+ )
+ assert "force_cancel_active:" in SHARED_COMPOSER
+ assert (
+ "resolvedThreadId ===\n useChatRuntimeStore.getState().activeThreadId"
+ in CHAT_ADAPTER
+ )
+ assert (
+ "findLatestUserAudioBase64(\n survivingMessages,\n !queuedRunSettings"
+ in CHAT_ADAPTER
+ )
+ assert "if (audioBase64 && !queuedRunSettings)" in CHAT_ADAPTER
+ assert ".setThreadContextUsage(usageThreadKey, usage)" in CHAT_ADAPTER
+ assert (
+ "usageThreadIsVisible &&\n"
+ " useChatRuntimeStore.getState().params.checkpoint === params.checkpoint"
+ in CHAT_ADAPTER
+ )
+
+
+def test_compare_prompt_list_resets_when_preflight_never_starts_a_run():
+ reset = _between(
+ SHARED_COMPOSER,
+ "function resetPromptQueue()",
+ "function advanceQueue()",
+ )
+ assert "isQueueRunningRef.current = false;" in reset
+ assert "setIsQueueRunning(false);" in reset
+ assert "queueRef.current = [];" in reset
+ assert "queueIndexRef.current = 0;" in reset
+ assert "setQueueProgress({ current: 0, total: 0 });" in reset
+
+ send_flow = _between(
+ SHARED_COMPOSER,
+ "async function send()",
+ "sendRef.current = send;",
+ )
+ unavailable_lifecycle = _between(
+ send_flow,
+ "if (compareLifecycleLease === null)",
+ "const releaseCompareModelLifecycle = () =>",
+ )
+ assert "resetPromptQueue();" in unavailable_lifecycle
+
+ failed_preflight = _between(
+ send_flow,
+ "compareStopDecision = await confirmStopRunningChatsIfNeeded(",
+ "if (!compareStopDecision.proceed)",
+ )
+ assert "resetPromptQueue();" in failed_preflight
+
+ declined_preflight = _between(
+ send_flow,
+ "if (!compareStopDecision.proceed)",
+ "if (!submittedDraftIsCurrent())",
+ )
+ assert (
+ declined_preflight.index("releaseCompareModelLifecycle();")
+ < declined_preflight.index("resetPromptQueue();")
+ < declined_preflight.index("return;")
+ )
+
+ changed_draft = _between(
+ send_flow,
+ "const keepChangedDraft = () =>",
+ "const clearSubmittedDraft = () =>",
+ )
+ assert "releaseCompareModelLifecycle();" in changed_draft
+ assert "resetPromptQueue();" in changed_draft
+
+ failed_gpu_discovery = _between(
+ send_flow,
+ "// Warm the device cache before the snapshot below",
+ "// The GPU/offload knobs both compare loads must use",
+ )
+ assert "resetPromptQueue();" in failed_gpu_discovery
+
+ compare_run = _between(
+ send_flow,
+ "setComparing(true);",
+ "} else {",
+ )
+ failed_compare = _between(compare_run, "} catch (err) {", "} finally {")
+ assert "compareStepSucceededRef.current = false;" in failed_compare
+ assert "resetPromptQueue();" in failed_compare
+
+
+def test_clear_all_invalidates_and_removes_late_fresh_thread_initialization():
+ target = _between(
+ THREAD,
+ "const createPromptQueueTarget = useCallback(",
+ "const dismissWaitToast",
+ )
+ assert "const historyClearGeneration = chatHistoryClearBoundary.capture()" in target
+ assert "chatHistoryClearBoundary.capture() !== historyClearGeneration" in target
+ assert "if (initializingFreshThread)" in target
+ assert "initializedFreshThreadId = remoteId" in target
+ assert "freshThreadAppendAccepted = true" in target
+ assert "removeFreshThreadPersistedAfterAbort()" in target
+ assert "removeFreshThreadPersistedAfterAbort(true)" not in target
+ assert "markChatThreadDeleted(initializedFreshThreadId)" in target
+ assert "deleteStoredChatThreads([initializedFreshThreadId])" in target
+ assert "aui.threads().switchToNewThread()" in target
+ assert "chatHistoryClearBoundary.advance();" in CLEAR_ALL_CHATS
+ assert CLEAR_ALL_CHATS.index("chatHistoryClearBoundary.advance();") < CLEAR_ALL_CHATS.index(
+ "requestPromptQueueStop();"
+ )
+ assert CLEAR_ALL_CHATS.index("requestPromptQueueStop();") < CLEAR_ALL_CHATS.index(
+ "await chatHistoryClearBoundary.waitForPending();"
+ )
+ assert "const historyClearGeneration = chatHistoryClearBoundary.capture();" in RUNTIME_PROVIDER
+ assert "await throwIfHistoryWasCleared(initialized.remoteId);" in RUNTIME_PROVIDER
+ assert "await throwIfHistoryWasCleared(remoteId);" in RUNTIME_PROVIDER
+ assert "chatHistoryClearBoundary.trackPending(write)" in RUNTIME_PROVIDER
+ assert "class ChatHistoryClearBoundary" in CHAT_CLEAR_BOUNDARY
+ assert "async waitForPending(): Promise<void>" in CHAT_CLEAR_BOUNDARY
+
+
+def test_noop_setting_refreshes_do_not_invalidate_pending_queues():
+ assert "shouldAdvanceQueuedSettingsEpoch(" in CHAT_RUNTIME_STORE
+ set_params = _between(CHAT_RUNTIME_STORE, "setParams: (params, options)", "setCustomPresets:")
+ assert "state.params," in set_params
+ assert "params," in set_params
+ assert "queuedSettingsChanged" in set_params
+ set_checkpoint = _between(
+ CHAT_RUNTIME_STORE,
+ "setCheckpoint: (modelId, ggufVariant, options)",
+ "setActiveThreadId:",
+ )
+ assert "nextGgufVariant" in set_checkpoint
+ assert "nextDeepResearchEnabled" in set_checkpoint
+ assert "queuedSettingsChanged" in set_checkpoint
+
+
+def test_stop_delete_archive_and_clear_are_thread_scoped():
+ stop_listener = _between(
+ THREAD,
+ "window.addEventListener(PROMPT_QUEUE_STOP_EVENT",
+ "window.addEventListener(PROMPT_QUEUE_RUN_FAILED_EVENT",
+ )
+ assert "stopPromptQueueRunForThreadIds(threadIds)" in stop_listener
+ assert "requestPromptQueueStop(toArchive.map((thread) => thread.id));" in SIDEBAR_ITEMS
+ assert "requestPromptQueueStop(threadIds);" in SIDEBAR_ITEMS
+ assert "requestPromptQueueStop();" in CLEAR_ALL_CHATS
+ assert "serverCancelByThreadId" in CLEAR_ALL_CHATS
+ assert "stopChatThread(threadId)" in CLEAR_ALL_CHATS
+ assert "detail: { threadIds, temporaryOnly: true }" in QUEUE_BOUNDARY
+ assert "if (temporaryOnly)" in THREAD
+ assert "threadIds !== undefined && threadIds.length === 0" in QUEUE_BOUNDARY
+ assert "detail: threadIds ? { threadIds } : undefined" in QUEUE_BOUNDARY
+ assert "const aliasesByQueuedRun = new Map<string, string[]>()" in CONFIRM_MODEL_SWAP
+ assert "aliases.some((threadId) => runningIds.has(threadId))" in CONFIRM_MODEL_SWAP
+
+
+def test_sidebar_exposes_queue_activity_for_each_thread():
+ assert "const queueByThreadId = usePromptQueueUI((s) => s.byThreadId);" in APP_SIDEBAR
+ assert "hasQueuedActivity" in APP_SIDEBAR
+ assert "showWorkSpinner" in APP_SIDEBAR
+ assert "{showWorkSpinner && (" in APP_SIDEBAR
+ assert "hasUnreadActivity" in APP_SIDEBAR
+ assert "clearChatNotifications(item)" in APP_SIDEBAR
diff --git a/tests/studio/test_new_chat_context_recount.py b/tests/studio/test_new_chat_context_recount.py
index 23e0fa4805a..24722c3f628 100644
--- a/tests/studio/test_new_chat_context_recount.py
+++ b/tests/studio/test_new_chat_context_recount.py
@@ -91,7 +91,7 @@ def _store_reducers() -> str:
text = read(STORE)
checkpoint = slice_between(
text,
- "setCheckpoint: (modelId, ggufVariant) =>",
+ "setCheckpoint: (modelId, ggufVariant, options) =>",
" // Re-apply the incoming thread's own usage",
)
active = slice_between(text, "setActiveThreadId: (activeThreadId) =>", "setActiveProjectId:")
@@ -181,6 +181,17 @@ const useExternalProvidersStore: any = { getState: () => ({ providers: [] }) };
function getExternalMaxOutputTokens(_providerType: any, _modelId: any): number {
return 8192;
}
+function shouldAdvanceQueuedSettingsEpoch(
+ currentValues: Readonly<object>,
+ nextValues: Readonly<object>,
+ trackQueuedSettings = true,
+): boolean {
+ if (!trackQueuedSettings) return false;
+ const keys = new Set([...Object.keys(currentValues), ...Object.keys(nextValues)]);
+ return Array.from(keys).some(
+ (key) => !Object.is((currentValues as any)[key], (nextValues as any)[key]),
+ );
+}
const actions: any = {
__STORE_REDUCERS__
@@ -264,6 +275,9 @@ async function countChatInputTokens(payload: any): Promise<any> {
const requestPromptQueueStop = (_opts: any): void => {
world.promptQueueStops += 1;
};
+const requestTemporaryPromptQueueStop = (): void => {
+ world.promptQueueStops += 1;
+};
const auiFixture: any = {
threads: () => ({