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.

Chat: queue prompts with Cmd/Ctrl+Enter and drag to reorder the queue (#8952)

Michael Hane4d4eb68e4a0
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index 300b2667509..c54e240b091 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -36,8 +36,15 @@ import { TerminalToolUI } from "@/components/assistant-ui/tool-ui-terminal";
import { WebSearchToolUI } from "@/components/assistant-ui/tool-ui-web-search";
import { ChatDictationBar } from "@/components/assistant-ui/chat-dictation-bar";
import {
+ PROMPT_QUEUE_DRAG_TYPE,
attachmentsPastedText,
+ hasPendingPromptQueueStart,
isPastedTextFile,
+ isPromptQueueChord,
+ isPromptQueueDragTypes,
+ pastedTextQueueKey,
+ promptQueueActiveItemChanged,
+ reorderPromptQueueItems,
pasteClipboardFiles,
extractYoutubeVideoId,
pasteLongTextAsFile,
@@ -904,6 +911,54 @@ function removePromptQueueItem(itemId: string) {
return true;
}
+/**
+ * Move a queued prompt into another's slot. Both must still be pending: a
+ * dispatched item is already on its way out, and a run mid-dispatch would race
+ * the pump. Insert index is read off the pre-splice array, so a downward drag
+ * lands after the target and an upward drag lands before it.
+ */
+function movePromptQueueItem(itemId: string, targetItemId: string) {
+ if (itemId === targetItemId) {
+ return false;
+ }
+ const match = findPromptQueueRunByItemId(itemId);
+ const target = findPromptQueueRunByItemId(targetItemId);
+ if (!match || !target || match.run !== target.run) {
+ return false;
+ }
+ const { run, itemIndex, item } = match;
+ if (item.dispatched || target.item.dispatched) {
+ return false;
+ }
+ if (promptQueueDispatchingRunIds.has(run.id)) {
+ return false;
+ }
+ const activeIndex = Math.max(run.index, 0);
+ const before = run.items;
+ const after = reorderPromptQueueItems(
+ before,
+ itemIndex,
+ target.itemIndex,
+ activeIndex,
+ );
+ if (!after) {
+ return false;
+ }
+ const activeChanged = promptQueueActiveItemChanged(before, after, run.index);
+ run.items = after;
+ syncPromptQueueUI();
+
+ // A move across the active slot changes what dispatches next, so retarget the
+ // pending send the way a removal does.
+ const nowActive = run.items[run.index];
+ if (run.index >= 0 && !run.waitingForTargetIdle && nowActive && activeChanged) {
+ clearPromptQueueRetryTimer(run);
+ run.prevStoreRunning = false;
+ scheduleQueuedPromptDispatch(run, nowActive, 50);
+ }
+ return true;
+}
+
function isPromptQueueTargetRunning(
target: PromptQueueTarget,
runningByThreadId: Record<string, boolean>,
@@ -2134,6 +2189,26 @@ const Composer: FC<{
const pastedTextMinChars = useChatPreferencesStore(
(state) => state.pastedTextMinChars,
);
+ // Set by Cmd/Ctrl+Enter and read once by the handleSubmit that requestSubmit
+ // reaches synchronously. Armed only when that call will happen: with no form,
+ // or no requestSubmit, it would stay armed and queue whatever submit came
+ // next.
+ const forceQueueRef = useRef(false);
+ const queueOnModEnter = useCallback(
+ (event: KeyboardEvent<HTMLTextAreaElement>) => {
+ const form = event.currentTarget.form;
+ if (typeof form?.requestSubmit !== "function") {
+ return;
+ }
+ forceQueueRef.current = true;
+ try {
+ form.requestSubmit();
+ } catch {
+ forceQueueRef.current = false;
+ }
+ },
+ [],
+ );
// Read by both writers that could put the sent text back, the input handlers
// and the draft restore. Armed by every path that clears the composer.
const justSentRef = useRef<SentTextGuard | null>(null);
@@ -2141,7 +2216,12 @@ const Composer: FC<{
// thread that sent. Kept in step by the effect alongside pasteDraftKeyRef.
const draftKeyRef = useRef<string | null>(null);
const { inputProps, isComposing, isComposingRef } =
- useImeComposerInputHandlers({ submitOnEnter: true, justSentRef, draftKeyRef });
+ useImeComposerInputHandlers({
+ submitOnEnter: true,
+ onModEnter: queueOnModEnter,
+ justSentRef,
+ draftKeyRef,
+ });
// A pasted YouTube link offers a transcript attachment above the composer.
const [youtubeLink, setYoutubeLink] = useState<string | null>(null);
const handleFilePaste = useCallback(
@@ -2803,8 +2883,26 @@ const Composer: FC<{
{
temporary: boolean;
cancelled: boolean;
+ threadId: string | null;
+ localModelBoundaryGeneration: number;
+ queuedSettingsEpoch: number;
+ }
+ >(),
+ );
+ // Reading a pasted-text attachment happens before the queue start is
+ // registered, so the intent is recorded here for the length of the read.
+ // Keyed like a reservation so a submit during the read cannot start a second
+ // read of the same attachment, and carrying the boundaries the read predates.
+ const pastedTextQueuePendingRef = useRef(
+ new Map<
+ string,
+ {
+ temporary: boolean;
+ cancelled: boolean;
+ threadId: string | null;
localModelBoundaryGeneration: number;
queuedSettingsEpoch: number;
+ historyClearGeneration: number;
}
>(),
);
@@ -2819,9 +2917,17 @@ const Composer: FC<{
const detail =
(event as CustomEvent<PromptQueueStopEventDetail>).detail ?? {};
const state = aui.threadListItem().getState();
+ const aliases = compactIds([state.id, state.remoteId, referenceThreadId]);
cancelPendingPromptQueueFactoriesForStop(
promptQueueStartPendingRef.current,
- compactIds([state.id, state.remoteId, referenceThreadId]),
+ aliases,
+ detail,
+ );
+ // A read in flight has no reservation yet, so it needs cancelling here
+ // too or Clear all lets it queue a prompt and recreate the chat.
+ cancelPendingPromptQueueFactoriesForStop(
+ pastedTextQueuePendingRef.current,
+ aliases,
detail,
);
};
@@ -2838,6 +2944,10 @@ const Composer: FC<{
}, [aui, referenceThreadId]);
const [pendingSend, setPendingSend] = useState(false);
const pendingSendRef = useRef(false);
+ // Whether the parked send is a queue gesture. A chord pressed while this
+ // chat's settings load parks like any other send, and the release path would
+ // otherwise send the prompt the user asked to stack.
+ const pendingSendForceQueueRef = useRef(false);
const waitToastRef = useRef<string | number | null>(null);
// This chat's own settings are still on their way; a send now would run on the
// installation defaults showing in their place.
@@ -3095,27 +3205,72 @@ const Composer: FC<{
};
}, [aui, referenceThreadId]);
+ // Whether a pending start is already going to be refused when it resolves,
+ // so a retry replaces it rather than being turned away as a duplicate and
+ // leaving neither gesture to queue anything. Only the checks that need no
+ // queue target are here; the model boundary stays with the reservation,
+ // where usesLocalModel is known, so this can never be the stricter of the
+ // two and start a second queue for the same prompt.
+ const pendingQueueStartIsStale = useCallback(
+ (pending: {
+ cancelled: boolean;
+ temporary: boolean;
+ queuedSettingsEpoch: number;
+ historyClearGeneration?: number;
+ }): boolean => {
+ if (pending.cancelled) return true;
+ if (
+ pending.historyClearGeneration !== undefined &&
+ chatHistoryClearBoundary.capture() !== pending.historyClearGeneration
+ ) {
+ return true;
+ }
+ const chatState = useChatRuntimeStore.getState();
+ return shouldAbortPendingQueueForSettingsChange({
+ capturedEpoch: pending.queuedSettingsEpoch,
+ currentEpoch: chatState.queuedSettingsEpoch,
+ capturedTemporary: pending.temporary,
+ currentTemporary: chatState.incognito,
+ });
+ },
+ [],
+ );
+
const startHydratedPromptQueue = useCallback(
(
items: string[],
waitForCurrentRun = false,
onStarted?: () => void,
onAborted?: () => void,
+ // Captured before an awaited step that precedes this call, so a boundary
+ // or setting changed during that step still invalidates the queue.
+ capturedAt?: {
+ localModelBoundaryGeneration: number;
+ queuedSettingsEpoch: number;
+ temporary: boolean;
+ },
) => {
const reservationKey = JSON.stringify([
referenceThreadId,
items,
waitForCurrentRun,
]);
- if (promptQueueStartPendingRef.current.has(reservationKey)) {
+ // A reservation that is still going to start owns this prompt. One that
+ // is already invalid is replaced, so the retry is the one that queues.
+ const existing = promptQueueStartPendingRef.current.get(reservationKey);
+ if (existing && !pendingQueueStartIsStale(existing)) {
return false;
}
const reservation = {
- temporary: useChatRuntimeStore.getState().incognito,
+ temporary:
+ capturedAt?.temporary ?? useChatRuntimeStore.getState().incognito,
cancelled: false,
+ threadId: referenceThreadId,
localModelBoundaryGeneration:
+ capturedAt?.localModelBoundaryGeneration ??
localPromptQueueModelBoundary.capture(),
queuedSettingsEpoch:
+ capturedAt?.queuedSettingsEpoch ??
useChatRuntimeStore.getState().queuedSettingsEpoch,
};
promptQueueStartPendingRef.current.set(reservationKey, reservation);
@@ -3147,7 +3302,12 @@ const Composer: FC<{
) {
startPromptQueue(items, target, waitForCurrentRun);
onStarted?.();
- } else {
+ } else if (
+ promptQueueStartPendingRef.current.get(reservationKey) ===
+ reservation
+ ) {
+ // Superseded reservations stay quiet: the one that replaced this
+ // is still going, so nothing has been lost to report.
onAborted?.();
}
})
@@ -3168,7 +3328,7 @@ const Composer: FC<{
});
return true;
},
- [createPromptQueueTarget, referenceThreadId],
+ [createPromptQueueTarget, pendingQueueStartIsStale, referenceThreadId],
);
// The queue carries text, and a long paste is text the composer parked in a
@@ -3187,13 +3347,23 @@ const Composer: FC<{
const attachmentIds = attachments.map((attachment) => attachment.id);
const textAtQueue = composer.getState().text.trim();
- void Promise.all(files.map((file) => file.text()))
- .then((texts) => {
- const queuedPrompt = [textAtQueue, ...texts]
- .filter((part) => part.trim().length > 0)
- .join("\n\n");
- if (queuedPrompt.length === 0) return;
- startHydratedPromptQueue([queuedPrompt], waitForCurrentRun, () => {
+ const queueTexts = (
+ texts: string[],
+ // Captured before an awaited read, when there was one.
+ capturedAt?: {
+ localModelBoundaryGeneration: number;
+ queuedSettingsEpoch: number;
+ temporary: boolean;
+ },
+ ) => {
+ const queuedPrompt = [textAtQueue, ...texts]
+ .filter((part) => part.trim().length > 0)
+ .join("\n\n");
+ if (queuedPrompt.length === 0) return;
+ startHydratedPromptQueue(
+ [queuedPrompt],
+ waitForCurrentRun,
+ () => {
const state = composer.getState();
// Only clear the composer this prompt was queued from.
if (
@@ -3211,15 +3381,118 @@ const Composer: FC<{
});
clearStoredDraft();
armJustSent(state.text);
- });
+ },
+ () => {
+ toast.info("Pasted text was not queued", {
+ description: "The chat settings changed. Send it again.",
+ });
+ },
+ capturedAt,
+ );
+ };
+
+ // createPastedTextFile records the body under the File identity matched
+ // above, so read it from there: a gesture that awaits the File joins the
+ // queue behind any later one that does not, reversing the two.
+ const cachedTexts: string[] = [];
+ for (const file of files) {
+ const text = pastedTextOf(file);
+ if (text === undefined) break;
+ cachedTexts.push(text);
+ }
+ if (cachedTexts.length === files.length) {
+ queueTexts(cachedTexts);
+ return true;
+ }
+
+ // Registered before the read, or a submit during it takes the send path
+ // and this queues the same text again once the read finishes.
+ const pendingKey = pastedTextQueueKey(
+ referenceThreadId,
+ textAtQueue,
+ attachmentIds,
+ );
+ // The same intent as a read already running: report it handled rather
+ // than queue a duplicate. A read whose baselines have gone stale will
+ // abort, so it must not absorb the retry either.
+ const inFlight = pastedTextQueuePendingRef.current.get(pendingKey);
+ if (inFlight && !pendingQueueStartIsStale(inFlight)) return true;
+ // Every baseline the reservation would otherwise take after the read, so
+ // a setting or boundary changed during it still aborts the queue.
+ const chatState = useChatRuntimeStore.getState();
+ const pendingRead = {
+ temporary: chatState.incognito,
+ cancelled: false,
+ threadId: referenceThreadId,
+ // The chat the read began in. The target is anchored after the read,
+ // so a switch mid-read would otherwise dispatch into the new chat.
+ composerIdentity: composerIdentityRef.current,
+ localModelBoundaryGeneration: localPromptQueueModelBoundary.capture(),
+ queuedSettingsEpoch: chatState.queuedSettingsEpoch,
+ historyClearGeneration: chatHistoryClearBoundary.capture(),
+ };
+ // Replaces a stale read under the same key. That read still resolves, but
+ // it no longer owns the key, so its own start is skipped and only this
+ // one can queue.
+ pastedTextQueuePendingRef.current.set(pendingKey, pendingRead);
+ void Promise.all(files.map((file) => file.text()))
+ .then((texts) => {
+ // Stopped, cleared, replaced, or aimed at another chat while the
+ // read was in flight.
+ if (
+ pendingQueueStartIsStale(pendingRead) ||
+ composerIdentityRef.current !== pendingRead.composerIdentity ||
+ pastedTextQueuePendingRef.current.get(pendingKey) !== pendingRead
+ ) {
+ return;
+ }
+ queueTexts(texts, pendingRead);
})
.catch(() => {
toast.error("Could not queue the pasted text.", {
description: "Show it in the text field, then send it again.",
});
+ })
+ .finally(() => {
+ if (pastedTextQueuePendingRef.current.get(pendingKey) === pendingRead) {
+ pastedTextQueuePendingRef.current.delete(pendingKey);
+ }
});
return true;
},
+ [
+ armJustSent,
+ aui,
+ clearStoredDraft,
+ pendingQueueStartIsStale,
+ referenceThreadId,
+ startHydratedPromptQueue,
+ ],
+ );
+
+ // Queue whatever the composer holds. Hoisted out of handleSubmit because the
+ // parked-send release needs it too and cannot reach that closure. Reads the
+ // live composer, not the rendered text, which at release time can be a commit
+ // behind.
+ const queueComposerText = useCallback(
+ (waitForCurrentRun: boolean) => {
+ const queuedPrompt = aui.composer().getState().text.trim();
+ if (!queuedPrompt) {
+ return;
+ }
+ startHydratedPromptQueue([queuedPrompt], waitForCurrentRun, () => {
+ // Guard the untrimmed text too: that is what a late write carries.
+ const cleared = aui.composer().getState().text;
+ if (cleared.trim() !== queuedPrompt) {
+ return;
+ }
+ flushResourcesSync(() => {
+ aui.composer().setText("");
+ });
+ clearStoredDraft();
+ armJustSent(queuedPrompt, cleared);
+ });
+ },
[armJustSent, aui, clearStoredDraft, startHydratedPromptQueue],
);
@@ -3237,6 +3510,7 @@ const Composer: FC<{
const cancelQueuedSend = useCallback(() => {
pendingSendRef.current = false;
+ pendingSendForceQueueRef.current = false;
setPendingSend(false);
// A dictation send held behind the same block would otherwise fire alone.
sendAfterDictationRef.current = false;
@@ -3409,11 +3683,30 @@ const Composer: FC<{
return;
}
const { text, attachments } = aui.composer().getState();
+ const forceQueue = pendingSendForceQueueRef.current;
pendingSendRef.current = false;
+ pendingSendForceQueueRef.current = false;
setPendingSend(false);
dismissWaitToast();
if (text.trim().length > 0 || attachments.length > 0) {
clearStoredDraft();
+ if (forceQueue) {
+ // Wait mode read now, not carried from the parked submit: a run can
+ // start while the settings load, and ignoring it would dispatch on top
+ // of the response already streaming.
+ const waitForCurrentRun = aui.thread().getState().isRunning;
+ // The chord's own two branches from handleSubmit, in the same order. A
+ // long paste lives in an attachment, so queueing the text alone queues
+ // nothing at all when that is all there is.
+ if (canQueueCurrentPrompt) {
+ queueComposerText(waitForCurrentRun);
+ return;
+ }
+ if (canQueuePastedTextPrompt && queuePastedTextPrompt(waitForCurrentRun)) {
+ return;
+ }
+ // Nothing queueable: send, as this path did before it carried intent.
+ }
sendReservedComposer();
}
}, [
@@ -3423,8 +3716,12 @@ const Composer: FC<{
hasMaterializingImageAttachments,
hasMaterializingAudioAttachments,
aui,
+ canQueueCurrentPrompt,
+ canQueuePastedTextPrompt,
clearStoredDraft,
dismissWaitToast,
+ queueComposerText,
+ queuePastedTextPrompt,
sendReservedComposer,
]);
@@ -3432,6 +3729,7 @@ const Composer: FC<{
useEffect(
() => () => {
pendingSendRef.current = false;
+ pendingSendForceQueueRef.current = false;
if (waitToastRef.current !== null) toast.dismiss(waitToastRef.current);
},
[],
@@ -3547,6 +3845,9 @@ const Composer: FC<{
preventDefault: () => void;
stopPropagation?: () => void;
}) => {
+ // Read once per submit: a rejected send must not leave it armed.
+ const forceQueue = forceQueueRef.current;
+ forceQueueRef.current = false;
if (isResearchActive) {
event.preventDefault();
return;
@@ -3561,6 +3862,10 @@ const Composer: FC<{
// defaults on screen, so a chat stored as "ask" would queue as "off".
if (threadScopedSettingsPending && !overlay) {
event.preventDefault();
+ // The intent rides with the parked send; the release reads it back.
+ if (forceQueue) {
+ pendingSendForceQueueRef.current = true;
+ }
enqueueSend("settings");
return;
}
@@ -3572,6 +3877,14 @@ const Composer: FC<{
threadIsRunning || aui.thread().getState().isRunning;
const livePromptQueueActive =
promptQueueActive ||
+ hasPendingPromptQueueStart(
+ promptQueueStartPendingRef.current.values(),
+ referenceThreadId,
+ ) ||
+ hasPendingPromptQueueStart(
+ pastedTextQueuePendingRef.current.values(),
+ referenceThreadId,
+ ) ||
Boolean(
findPromptQueueEntry(
usePromptQueueUI.getState(),
@@ -3612,26 +3925,27 @@ const Composer: FC<{
}
return;
}
- const queuedPrompt = composerText.trim();
- startHydratedPromptQueue(
- [queuedPrompt],
- liveThreadIsRunning || livePreStreamRunActive,
- () => {
- // Guard the untrimmed text too: that is what a late write carries.
- const cleared = aui.composer().getState().text;
- if (cleared.trim() !== queuedPrompt) {
- return;
- }
- flushResourcesSync(() => {
- aui.composer().setText("");
- });
- clearStoredDraft();
- armJustSent(queuedPrompt, cleared);
- },
- );
+ queueComposerText(liveThreadIsRunning || livePreStreamRunActive);
return;
}
+ // Cmd/Ctrl+Enter queues even with nothing running, so prompts can be
+ // stacked up front. The queue dispatches this one immediately; the next
+ // Cmd/Ctrl+Enter lands behind it.
+ if (forceQueue && !disableQueue) {
+ if (canQueueCurrentPrompt) {
+ event.preventDefault();
+ queueComposerText(false);
+ return;
+ }
+ if (canQueuePastedTextPrompt) {
+ event.preventDefault();
+ if (queuePastedTextPrompt(false)) {
+ return;
+ }
+ }
+ }
+
if (interceptSend(event)) return;
if (overlay) {
@@ -3695,15 +4009,14 @@ const Composer: FC<{
sendReservedComposer();
},
[
- armJustSent,
aui,
canQueueCurrentPrompt,
canQueuePastedTextPrompt,
+ queueComposerText,
queuePastedTextPrompt,
clearStoredDraft,
closeOverlay,
composerText,
- startHydratedPromptQueue,
disabled,
disableQueue,
hasAttachments,
@@ -4003,10 +4316,13 @@ const IME_STUCK_TIMEOUT_MS = 2500;
function useImeComposerInputHandlers({
submitOnEnter = false,
+ onModEnter,
justSentRef,
draftKeyRef,
}: {
submitOnEnter?: boolean;
+ /** Cmd/Ctrl+Enter without Shift, claimed before the plain-Enter submit. */
+ onModEnter?: (event: KeyboardEvent<HTMLTextAreaElement>) => void;
// Guard armed by the last send or queue. See setComposerText below.
justSentRef?: RefObject<SentTextGuard | null>;
// Thread on screen. The composer outlives a thread switch, so this is what
@@ -4160,12 +4476,23 @@ function useImeComposerInputHandlers({
// rather than waiting for the 2500ms watchdog.
setCompositionState(false);
}
+ if (onModEnter && isPromptQueueChord(e)) {
+ e.preventDefault();
+ onModEnter(e);
+ return;
+ }
if (submitOnEnter && e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
e.currentTarget.form?.requestSubmit();
}
},
- [justSentRef, refreshStuckTimer, setCompositionState, submitOnEnter],
+ [
+ justSentRef,
+ onModEnter,
+ refreshStuckTimer,
+ setCompositionState,
+ submitOnEnter,
+ ],
);
// On macOS, switching input methods (e.g. ABC → Pinyin) while the textarea
@@ -5321,6 +5648,11 @@ function promptQueueStatusLabel(status: PromptQueueUIItemStatus) {
}
}
+// dataTransfer.getData is blocked during dragover, but types is always readable.
+function isPromptQueueDrag(event: ReactDragEvent): boolean {
+ return isPromptQueueDragTypes(event.dataTransfer?.types);
+}
+
const PromptQueueStack: FC<{ queueThreadIds: string[] }> = ({
queueThreadIds,
}) => {
@@ -5330,6 +5662,8 @@ const PromptQueueStack: FC<{ queueThreadIds: string[] }> = ({
const items = usePromptQueueUI((s) => s.items);
const [editingItemId, setEditingItemId] = useState<string | null>(null);
const [draftPrompt, setDraftPrompt] = useState("");
+ const [draggingItemId, setDraggingItemId] = useState<string | null>(null);
+ const [dragOverItemId, setDragOverItemId] = useState<string | null>(null);
const editInputRef = useRef<HTMLTextAreaElement>(null);
const visibleItems = queueEntry
? items.filter((item) => item.runId === queueEntry.runId)
@@ -5371,6 +5705,19 @@ const PromptQueueStack: FC<{ queueThreadIds: string[] }> = ({
setEditingItemId(null);
setDraftPrompt("");
};
+ const endDrag = () => {
+ setDraggingItemId(null);
+ setDragOverItemId(null);
+ };
+ // Keyboard equivalent of a drag, since HTML5 drag events never fire for keys.
+ const moveByOffset = (index: number, offset: number) => {
+ const target = visibleItems[index + offset];
+ if (!target) {
+ return;
+ }
+ movePromptQueueItem(visibleItems[index].id, target.id);
+ };
+ const reorderable = visibleItems.length > 1;
return (
<div
@@ -5384,7 +5731,47 @@ const PromptQueueStack: FC<{ queueThreadIds: string[] }> = ({
return (
<div
key={item.id}
- className={cn("min-h-10", isEditing ? "h-auto" : "h-10")}
+ className={cn(
+ "min-h-10",
+ isEditing ? "h-auto" : "h-10",
+ draggingItemId === item.id && "opacity-40",
+ dragOverItemId === item.id &&
+ draggingItemId !== item.id &&
+ "rounded-md ring-1 ring-ring/60",
+ )}
+ draggable={reorderable && !isEditing}
+ onDragStart={(event) => {
+ setDraggingItemId(item.id);
+ event.dataTransfer.effectAllowed = "move";
+ event.dataTransfer.setData(PROMPT_QUEUE_DRAG_TYPE, item.id);
+ }}
+ onDragEnd={endDrag}
+ onDragOver={(event) => {
+ // Own type only: a file dragged over a row must reach the page
+ // dropzone, which skips events already prevented here.
+ if (!isPromptQueueDrag(event) || draggingItemId === item.id) {
+ return;
+ }
+ event.preventDefault();
+ event.dataTransfer.dropEffect = "move";
+ setDragOverItemId(item.id);
+ }}
+ onDragLeave={() => {
+ setDragOverItemId((id) => (id === item.id ? null : id));
+ }}
+ onDrop={(event) => {
+ if (!isPromptQueueDrag(event)) {
+ return;
+ }
+ event.preventDefault();
+ const sourceId =
+ event.dataTransfer.getData(PROMPT_QUEUE_DRAG_TYPE) ||
+ draggingItemId;
+ if (sourceId) {
+ movePromptQueueItem(sourceId, item.id);
+ }
+ endDrag();
+ }}
aria-label={`${promptQueueStatusLabel(item.status)} prompt ${visiblePosition} of ${visibleItems.length}: ${item.prompt}`}
>
{isEditing ? (
@@ -5433,7 +5820,27 @@ const PromptQueueStack: FC<{ queueThreadIds: string[] }> = ({
) : (
<div className="grid h-10 grid-cols-[minmax(0,1fr)_auto_2rem] items-center gap-2.5">
<div className="flex min-w-0 items-center gap-2.5">
- <CornerDownRightIcon className="size-4 shrink-0 text-muted-foreground/50" />
+ {reorderable ? (
+ <button
+ type="button"
+ className="shrink-0 cursor-grab text-muted-foreground/50 outline-none hover:text-muted-foreground focus-visible:text-foreground active:cursor-grabbing"
+ aria-label={`Reorder queued prompt ${visiblePosition} of ${visibleItems.length}`}
+ onKeyDown={(event) => {
+ if (event.key !== "ArrowUp" && event.key !== "ArrowDown") {
+ return;
+ }
+ event.preventDefault();
+ moveByOffset(
+ visibleIndex,
+ event.key === "ArrowUp" ? -1 : 1,
+ );
+ }}
+ >
+ <CornerDownRightIcon className="size-4" />
+ </button>
+ ) : (
+ <CornerDownRightIcon className="size-4 shrink-0 text-muted-foreground/50" />
+ )}
<div className="truncate text-sm text-muted-foreground">
{item.prompt}
</div>
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index fa89c769152..6fdb8cb8b80 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -120,6 +120,17 @@ export {
releasePreStreamRunReservation,
reservePreStreamRun,
} from "./utils/pre-stream-run-reservation";
+export {
+ promptQueueActiveItemChanged,
+ reorderPromptQueueItems,
+} from "./utils/prompt-queue-reorder";
+export {
+ PROMPT_QUEUE_DRAG_TYPE,
+ hasPendingPromptQueueStart,
+ isPromptQueueChord,
+ isPromptQueueDragTypes,
+ pastedTextQueueKey,
+} from "./utils/prompt-queue-input";
export {
localPromptQueueModelBoundary,
planLocalPromptQueueStop,
diff --git a/studio/frontend/src/features/chat/utils/prompt-queue-input.ts b/studio/frontend/src/features/chat/utils/prompt-queue-input.ts
new file mode 100644
index 00000000000..70ebc0fc6db
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/prompt-queue-input.ts
@@ -0,0 +1,73 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/** How keyboard and drag input map to prompt-queue actions. */
+
+/**
+ * Private drag type for a queue row, so a reorder is distinguishable from a
+ * file or a text selection dragged in from outside.
+ */
+export const PROMPT_QUEUE_DRAG_TYPE = "application/x-unsloth-prompt-queue-item";
+
+/**
+ * Whether a drag carries a queue row. Anything else must pass through
+ * untouched: the page dropzone skips events the row already prevented, so
+ * claiming a file drag here would silently drop the file.
+ */
+export function isPromptQueueDragTypes(
+ types: ArrayLike<string> | undefined | null,
+): boolean {
+ if (!types) return false;
+ return Array.from(types).includes(PROMPT_QUEUE_DRAG_TYPE);
+}
+
+/**
+ * Cmd/Ctrl+Enter, the queue chord. Shift+Enter stays a newline whatever else is
+ * held, and Alt disqualifies it too: Windows reports AltGr as Ctrl+Alt on any
+ * layout the browser does not read as having a real AltGraph, and those layouts
+ * hold AltGr for everyday characters. `key`, not `code`, so the keypad's Enter
+ * is the same chord.
+ */
+export function isPromptQueueChord(event: {
+ key: string;
+ shiftKey: boolean;
+ metaKey: boolean;
+ ctrlKey: boolean;
+ altKey?: boolean;
+}): boolean {
+ if (event.key !== "Enter" || event.shiftKey || event.altKey) return false;
+ return event.metaKey || event.ctrlKey;
+}
+
+/**
+ * Whether a queue start for this thread is registered but has not reached the
+ * queue store yet. Starting one awaits settings hydration, and nothing else
+ * marks the thread as queueing during that gap, so a plain Enter would send the
+ * same text the pending queue is about to dispatch.
+ */
+export function hasPendingPromptQueueStart(
+ reservations: Iterable<{ cancelled: boolean; threadId: string | null }>,
+ threadId: string | null,
+): boolean {
+ for (const reservation of reservations) {
+ if (reservation.cancelled) continue;
+ if (reservation.threadId === threadId) return true;
+ }
+ return false;
+}
+
+/**
+ * Identity of a pasted-text queue start, held for the length of the file read
+ * before it, so a submit during that read joins it instead of starting a second
+ * read of the same attachment.
+ *
+ * The wait mode is deliberately out: it is recomputed per submit and flips if a
+ * run starts mid-read, which would split one prompt across two keys.
+ */
+export function pastedTextQueueKey(
+ threadId: string | null,
+ text: string,
+ attachmentIds: readonly string[],
+): string {
+ return JSON.stringify([threadId, text, attachmentIds]);
+}
diff --git a/studio/frontend/src/features/chat/utils/prompt-queue-reorder.ts b/studio/frontend/src/features/chat/utils/prompt-queue-reorder.ts
new file mode 100644
index 00000000000..563a5e032a6
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/prompt-queue-reorder.ts
@@ -0,0 +1,59 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * Index math for dragging a queued prompt into another's slot, kept apart from
+ * the queue engine so the ordering rules are testable on plain arrays.
+ */
+
+/**
+ * Items already sent are fixed, so nothing may move to or from a slot before
+ * the one about to dispatch.
+ */
+export function canReorderPromptQueueRange(
+ fromIndex: number,
+ toIndex: number,
+ activeIndex: number,
+ itemCount: number,
+): boolean {
+ if (fromIndex === toIndex) return false;
+ if (!Number.isInteger(fromIndex) || !Number.isInteger(toIndex)) return false;
+ if (fromIndex < 0 || toIndex < 0) return false;
+ if (fromIndex >= itemCount || toIndex >= itemCount) return false;
+ return fromIndex >= activeIndex && toIndex >= activeIndex;
+}
+
+/**
+ * The queue after the move, or null when the move is not allowed. `toIndex` is
+ * read off the original array, so a downward drag lands after the target and an
+ * upward drag lands before it, which is how a dragged row reads on screen.
+ */
+export function reorderPromptQueueItems<T>(
+ items: readonly T[],
+ fromIndex: number,
+ toIndex: number,
+ activeIndex = 0,
+): T[] | null {
+ if (
+ !canReorderPromptQueueRange(fromIndex, toIndex, activeIndex, items.length)
+ ) {
+ return null;
+ }
+ const next = [...items];
+ const [moved] = next.splice(fromIndex, 1);
+ next.splice(toIndex, 0, moved);
+ return next;
+}
+
+/**
+ * Whether the move changed which item dispatches next, so the caller knows to
+ * retarget the pending send.
+ */
+export function promptQueueActiveItemChanged<T>(
+ before: readonly T[],
+ after: readonly T[],
+ activeIndex: number,
+): boolean {
+ if (activeIndex < 0) return false;
+ return before[activeIndex] !== after[activeIndex];
+}
diff --git a/studio/frontend/tests/pasted-text-attachment.test.ts b/studio/frontend/tests/pasted-text-attachment.test.ts
index 70de153ad9f..ddaca712546 100644
Binary files a/studio/frontend/tests/pasted-text-attachment.test.ts and b/studio/frontend/tests/pasted-text-attachment.test.ts differ
diff --git a/studio/frontend/tests/prompt-queue-input-edges.test.ts b/studio/frontend/tests/prompt-queue-input-edges.test.ts
new file mode 100644
index 00000000000..4e162b98e88
--- /dev/null
+++ b/studio/frontend/tests/prompt-queue-input-edges.test.ts
@@ -0,0 +1,249 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * Edge cases for the queue's keyboard and drag predicates, on top of what
+ * `prompt-queue-input.test.ts` already pins: the shapes the DOM hands us on
+ * platforms this box cannot run, a keypad Enter, a Windows AltGr chord, and a
+ * `DOMStringList` rather than Chromium's array.
+ *
+ * The drag type is matched literally because it was measured, not assumed:
+ * driven through a real DataTransfer, Chromium 151, Firefox 153 and WebKit 26.5
+ * all report it back lowercase and unchanged.
+ */
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ PROMPT_QUEUE_DRAG_TYPE,
+ hasPendingPromptQueueStart,
+ isPromptQueueChord,
+ isPromptQueueDragTypes,
+ pastedTextQueueKey,
+} from "../src/features/chat/utils/prompt-queue-input.ts";
+import { isGuardRetiringKey } from "../src/features/chat/utils/composer-send-guard.ts";
+
+type ChordEvent = {
+ key: string;
+ shiftKey: boolean;
+ metaKey: boolean;
+ ctrlKey: boolean;
+ altKey?: boolean;
+};
+
+function key(overrides: Partial<ChordEvent> = {}): ChordEvent {
+ return {
+ key: "Enter",
+ shiftKey: false,
+ metaKey: false,
+ ctrlKey: false,
+ altKey: false,
+ ...overrides,
+ };
+}
+
+// ── the chord ────────────────────────────────────────────────────────────────
+
+test("every platform's queue chord matches", () => {
+ // macOS sends Cmd, Windows and Linux send Ctrl, and either is accepted
+ // everywhere: a Mac user with a PC keyboard habit still queues.
+ assert.equal(isPromptQueueChord(key({ metaKey: true })), true);
+ assert.equal(isPromptQueueChord(key({ ctrlKey: true })), true);
+ assert.equal(isPromptQueueChord(key({ metaKey: true, ctrlKey: true })), true);
+});
+
+test("the numeric keypad's Enter is the same chord", () => {
+ // `code` differs (NumpadEnter) but `key` is "Enter" on every engine, and the
+ // predicate reads `key`, so a full-size keyboard's right-hand Enter queues.
+ assert.equal(isPromptQueueChord(key({ ctrlKey: true })), true);
+});
+
+test("Shift disqualifies the chord whatever else is held", () => {
+ // Shift+Enter is a newline, and this is the rule that keeps it one: the
+ // plain-Enter branch below carries the !shiftKey exclusion, so a chord that
+ // matched with Shift held would turn a newline into a queue.
+ assert.equal(isPromptQueueChord(key({ ctrlKey: true, shiftKey: true })), false);
+ assert.equal(isPromptQueueChord(key({ metaKey: true, shiftKey: true })), false);
+ assert.equal(
+ isPromptQueueChord(key({ metaKey: true, ctrlKey: true, shiftKey: true })),
+ false,
+ );
+});
+
+test("a bare Enter is not the chord", () => {
+ assert.equal(isPromptQueueChord(key()), false);
+ assert.equal(isPromptQueueChord(key({ shiftKey: true })), false);
+});
+
+test("only the Enter key is the chord, and the name is case sensitive", () => {
+ for (const name of ["enter", "ENTER", "Return", "NumpadEnter", "Escape", " "]) {
+ assert.equal(
+ isPromptQueueChord(key({ key: name, ctrlKey: true })),
+ false,
+ `${name} must not queue`,
+ );
+ }
+});
+
+test("AltGr+Enter on a Windows layout does not queue", () => {
+ // AltGr is reported as Ctrl+Alt. A layout that needs AltGr for everyday
+ // characters would otherwise queue on a keypress the user means as a newline
+ // or a plain send, and there is no Ctrl+Alt+Enter binding worth keeping.
+ assert.equal(isPromptQueueChord(key({ ctrlKey: true, altKey: true })), false);
+ assert.equal(isPromptQueueChord(key({ metaKey: true, altKey: true })), false);
+});
+
+test("an event without altKey at all still matches", () => {
+ // Not every synthetic event carries the flag; absent must read as not held,
+ // or a hand-built event in a test or a bridge would stop queueing.
+ const bare = { key: "Enter", shiftKey: false, metaKey: false, ctrlKey: true };
+ assert.equal(isPromptQueueChord(bare), true);
+});
+
+// ── the drag type ────────────────────────────────────────────────────────────
+
+test("a queue row's drag is recognised however the engine lists the types", () => {
+ assert.equal(isPromptQueueDragTypes([PROMPT_QUEUE_DRAG_TYPE]), true);
+ assert.equal(
+ isPromptQueueDragTypes(["text/plain", PROMPT_QUEUE_DRAG_TYPE]),
+ true,
+ );
+ // DataTransfer.types is a DOMStringList in WebKit and a frozen array in
+ // Chromium; both are ArrayLike, which is all the predicate requires.
+ const domStringList = { length: 1, 0: PROMPT_QUEUE_DRAG_TYPE };
+ assert.equal(isPromptQueueDragTypes(domStringList), true);
+});
+
+test("nothing else counts as a queue drag", () => {
+ assert.equal(isPromptQueueDragTypes(["Files"]), false);
+ assert.equal(isPromptQueueDragTypes(["text/plain", "text/uri-list"]), false);
+ assert.equal(isPromptQueueDragTypes([]), false);
+ assert.equal(isPromptQueueDragTypes(null), false);
+ assert.equal(isPromptQueueDragTypes(undefined), false);
+ // A file drag must reach the page dropzone, which skips events a row already
+ // prevented, so a false positive here silently swallows the file.
+ assert.equal(isPromptQueueDragTypes(["Files", "application/x-moz-file"]), false);
+});
+
+test("a near-miss type is not the queue type", () => {
+ assert.equal(isPromptQueueDragTypes([`${PROMPT_QUEUE_DRAG_TYPE}-2`]), false);
+ assert.equal(
+ isPromptQueueDragTypes([PROMPT_QUEUE_DRAG_TYPE.slice(0, -1)]),
+ false,
+ );
+});
+
+// ── pending starts ───────────────────────────────────────────────────────────
+
+test("a pending start is only this thread's while it is live", () => {
+ const live = { cancelled: false, threadId: "t1" };
+ const other = { cancelled: false, threadId: "t2" };
+ const dead = { cancelled: true, threadId: "t1" };
+ assert.equal(hasPendingPromptQueueStart([live], "t1"), true);
+ assert.equal(hasPendingPromptQueueStart([other], "t1"), false);
+ assert.equal(hasPendingPromptQueueStart([dead], "t1"), false);
+ assert.equal(hasPendingPromptQueueStart([dead, live], "t1"), true);
+ assert.equal(hasPendingPromptQueueStart([], "t1"), false);
+});
+
+test("a new chat's null thread matches only another null", () => {
+ assert.equal(hasPendingPromptQueueStart([{ cancelled: false, threadId: null }], null), true);
+ assert.equal(hasPendingPromptQueueStart([{ cancelled: false, threadId: "t1" }], null), false);
+ assert.equal(hasPendingPromptQueueStart([{ cancelled: false, threadId: null }], "t1"), false);
+});
+
+test("a Map's values are consumed exactly once, as the caller passes them", () => {
+ // thread.tsx hands this `map.values()`, a one-shot iterator. Reading it twice
+ // would report the second call empty, so the predicate must not iterate more
+ // than once, and the caller must not reuse the iterator.
+ const map = new Map([["k", { cancelled: false, threadId: "t1" }]]);
+ const iterator = map.values();
+ assert.equal(hasPendingPromptQueueStart(iterator, "t1"), true);
+ assert.equal(hasPendingPromptQueueStart(iterator, "t1"), false);
+ assert.equal(hasPendingPromptQueueStart(map.values(), "t1"), true);
+});
+
+// ── the pasted-text key ──────────────────────────────────────────────────────
+
+test("the pasted-text key is stable and separates what it must", () => {
+ const k = () => pastedTextQueueKey("t1", "hello", ["a1", "a2"]);
+ assert.equal(k(), k());
+ assert.notEqual(k(), pastedTextQueueKey("t2", "hello", ["a1", "a2"]));
+ assert.notEqual(k(), pastedTextQueueKey("t1", "hello!", ["a1", "a2"]));
+ assert.notEqual(k(), pastedTextQueueKey("t1", "hello", ["a2", "a1"]));
+ assert.notEqual(k(), pastedTextQueueKey("t1", "hello", ["a1"]));
+ assert.notEqual(
+ pastedTextQueueKey(null, "hello", []),
+ pastedTextQueueKey("null", "hello", []),
+ );
+});
+
+test("the pasted-text key survives text that looks like its own encoding", () => {
+ // The key is JSON, and the text is user input: a prompt full of quotes and
+ // brackets must not be able to collide with another prompt's key.
+ const tricky = '","x"],["t1","';
+ assert.notEqual(
+ pastedTextQueueKey("t1", tricky, []),
+ pastedTextQueueKey("t1", "x", []),
+ );
+ assert.equal(
+ pastedTextQueueKey("t1", tricky, []),
+ pastedTextQueueKey("t1", tricky, []),
+ );
+});
+
+test("the pasted-text key handles unicode and long prompts", () => {
+ const long = "\u6f22\u5b57".repeat(5_000);
+ assert.equal(pastedTextQueueKey("t1", long, []), pastedTextQueueKey("t1", long, []));
+ // Two Unicode spellings of the same word are two different prompts, which is
+ // the conservative side to fall on: the cost is a second read, never a
+ // dropped one. Written as escapes because the two look identical in a file.
+ const composed = "caf\u00e9";
+ const decomposed = "cafe\u0301";
+ assert.notEqual(
+ pastedTextQueueKey("t1", composed, []),
+ pastedTextQueueKey("t1", decomposed, []),
+ );
+});
+
+/**
+ * One `onKeyDown` consults the chord and the composer send guard (#8849), so a
+ * key the chord claims must not also read as the typing that retires the guard.
+ * Each has its own AltGr rule, so pin that the two agree.
+ */
+test("no key is both a queue chord and a guard-retiring keystroke", () => {
+ const keys = ["Enter", "a", "1", "é", "Escape", "Tab", "Shift", "Control",
+ "Alt", "Meta", "CapsLock", "ArrowUp", "Backspace", "F5"];
+ for (const k of keys) {
+ for (const ctrlKey of [false, true]) {
+ for (const metaKey of [false, true]) {
+ for (const altKey of [false, true]) {
+ for (const shiftKey of [false, true]) {
+ const event = { key: k, ctrlKey, metaKey, altKey, shiftKey };
+ const chord = isPromptQueueChord(event);
+ const retires = isGuardRetiringKey(event);
+ assert.equal(
+ chord && retires,
+ false,
+ `${k} ctrl=${ctrlKey} meta=${metaKey} alt=${altKey} shift=${shiftKey}`,
+ );
+ }
+ }
+ }
+ }
+ }
+});
+
+test("AltGr reads the same way to the chord and to the guard", () => {
+ // Windows reports AltGr as Ctrl+Alt, so it types rather than queues: not a
+ // chord, and deliberate enough to retire the guard.
+ const altGrChar = { key: "é", ctrlKey: true, altKey: true, metaKey: false,
+ shiftKey: false };
+ assert.equal(isPromptQueueChord(altGrChar), false);
+ assert.equal(isGuardRetiringKey(altGrChar), true);
+ // AltGr+Enter is not a character, and neither side claims it.
+ const altGrEnter = { ...altGrChar, key: "Enter" };
+ assert.equal(isPromptQueueChord(altGrEnter), false);
+ assert.equal(isGuardRetiringKey(altGrEnter), false);
+});
diff --git a/studio/frontend/tests/prompt-queue-input.test.ts b/studio/frontend/tests/prompt-queue-input.test.ts
new file mode 100644
index 00000000000..d04340bfe28
--- /dev/null
+++ b/studio/frontend/tests/prompt-queue-input.test.ts
@@ -0,0 +1,167 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ PROMPT_QUEUE_DRAG_TYPE,
+ hasPendingPromptQueueStart,
+ isPromptQueueChord,
+ isPromptQueueDragTypes,
+ pastedTextQueueKey,
+} from "../src/features/chat/utils/prompt-queue-input.ts";
+
+function key(
+ overrides: Partial<{
+ key: string;
+ shiftKey: boolean;
+ metaKey: boolean;
+ ctrlKey: boolean;
+ }> = {},
+) {
+ return {
+ key: "Enter",
+ shiftKey: false,
+ metaKey: false,
+ ctrlKey: false,
+ ...overrides,
+ };
+}
+
+test("Cmd or Ctrl plus Enter is the queue chord", () => {
+ assert.ok(isPromptQueueChord(key({ metaKey: true })));
+ assert.ok(isPromptQueueChord(key({ ctrlKey: true })));
+});
+
+test("Shift+Enter stays a newline, with or without a modifier", () => {
+ assert.equal(isPromptQueueChord(key({ shiftKey: true })), false);
+ assert.equal(
+ isPromptQueueChord(key({ shiftKey: true, metaKey: true })),
+ false,
+ );
+ assert.equal(
+ isPromptQueueChord(key({ shiftKey: true, ctrlKey: true })),
+ false,
+ );
+});
+
+test("plain Enter and other keys are left alone", () => {
+ assert.equal(isPromptQueueChord(key()), false);
+ assert.equal(isPromptQueueChord(key({ key: "k", metaKey: true })), false);
+ assert.equal(isPromptQueueChord(key({ key: "NumpadEnter" })), false);
+});
+
+test("a drag carrying the queue type is a reorder", () => {
+ assert.ok(isPromptQueueDragTypes([PROMPT_QUEUE_DRAG_TYPE]));
+ assert.ok(isPromptQueueDragTypes([PROMPT_QUEUE_DRAG_TYPE, "text/plain"]));
+});
+
+test("file and foreign drags are not claimed", () => {
+ // A claimed file drag would be swallowed: the page dropzone skips events the
+ // row already prevented, so the file would never attach.
+ assert.equal(isPromptQueueDragTypes(["Files"]), false);
+ assert.equal(isPromptQueueDragTypes(["text/plain"]), false);
+ assert.equal(isPromptQueueDragTypes(["text/uri-list", "text/html"]), false);
+ assert.equal(isPromptQueueDragTypes([]), false);
+ assert.equal(isPromptQueueDragTypes(undefined), false);
+ assert.equal(isPromptQueueDragTypes(null), false);
+});
+
+test("the drag type is private to the queue", () => {
+ // A generic type would collide with drags from other panes.
+ assert.match(PROMPT_QUEUE_DRAG_TYPE, /^application\/x-unsloth-/);
+});
+
+const pending = (threadId: string | null, cancelled = false) => ({
+ cancelled,
+ threadId,
+});
+
+// Starting a queue awaits settings hydration. During that gap nothing else
+// marks the thread as queueing, so a plain Enter took the send path and the
+// pending queue then dispatched its own copy of the same prompt.
+test("a pending start counts as queueing for its own thread", () => {
+ assert.equal(
+ hasPendingPromptQueueStart([pending("thread-1")], "thread-1"),
+ true,
+ );
+});
+
+test("another thread's pending start does not block this one", () => {
+ assert.equal(
+ hasPendingPromptQueueStart([pending("thread-2")], "thread-1"),
+ false,
+ );
+});
+
+test("a cancelled reservation stops counting", () => {
+ assert.equal(
+ hasPendingPromptQueueStart([pending("thread-1", true)], "thread-1"),
+ false,
+ );
+});
+
+test("nothing pending is not queueing", () => {
+ assert.equal(hasPendingPromptQueueStart([], "thread-1"), false);
+});
+
+// A new chat has no id until it persists, so null has to match null rather
+// than being treated as "no thread".
+test("a new chat's pending start is matched on null", () => {
+ assert.equal(hasPendingPromptQueueStart([pending(null)], null), true);
+ assert.equal(hasPendingPromptQueueStart([pending(null)], "thread-1"), false);
+});
+
+test("one live reservation among cancelled ones still counts", () => {
+ assert.equal(
+ hasPendingPromptQueueStart(
+ [pending("thread-1", true), pending("thread-1")],
+ "thread-1",
+ ),
+ true,
+ );
+});
+
+// Reading a pasted-text attachment registers its intent in a plain list while
+// the read is in flight, so the same predicate has to work over that shape.
+test("concurrent pasted-text reads are tracked per thread", () => {
+ const reads = [pending("thread-1"), pending("thread-2")];
+ assert.equal(hasPendingPromptQueueStart(reads, "thread-1"), true);
+ assert.equal(hasPendingPromptQueueStart(reads, "thread-2"), true);
+ assert.equal(hasPendingPromptQueueStart(reads, "thread-3"), false);
+ // Finishing one read leaves the other counted.
+ reads.splice(0, 1);
+ assert.equal(hasPendingPromptQueueStart(reads, "thread-1"), false);
+ assert.equal(hasPendingPromptQueueStart(reads, "thread-2"), true);
+});
+
+// A submit during the file read is routed to the queue branch, so the read has
+// to be recognisable or it starts a second one and queues a duplicate.
+test("the same pasted prompt reads under one key", () => {
+ const key = () => pastedTextQueueKey("t1", "notes", ["a1", "a2"]);
+ assert.equal(key(), key());
+});
+
+test("a different thread, text or attachment is a different read", () => {
+ const base = pastedTextQueueKey("t1", "notes", ["a1"]);
+ assert.notEqual(base, pastedTextQueueKey("t2", "notes", ["a1"]));
+ assert.notEqual(base, pastedTextQueueKey("t1", "other", ["a1"]));
+ assert.notEqual(base, pastedTextQueueKey("t1", "notes", ["a2"]));
+});
+
+// Attachment order is part of the prompt, since the texts are joined in order.
+test("reordered attachments are a different read", () => {
+ assert.notEqual(
+ pastedTextQueueKey("t1", "notes", ["a1", "a2"]),
+ pastedTextQueueKey("t1", "notes", ["a2", "a1"]),
+ );
+});
+
+// A new chat has no id yet, and the composer survives thread switches.
+test("a null thread does not collide with a named one", () => {
+ assert.notEqual(
+ pastedTextQueueKey(null, "notes", []),
+ pastedTextQueueKey("t1", "notes", []),
+ );
+});
diff --git a/studio/frontend/tests/prompt-queue-reorder-sweep.test.ts b/studio/frontend/tests/prompt-queue-reorder-sweep.test.ts
new file mode 100644
index 00000000000..4ced57e4541
--- /dev/null
+++ b/studio/frontend/tests/prompt-queue-reorder-sweep.test.ts
@@ -0,0 +1,219 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * An exhaustive sweep of the reorder math, on top of the named cases in
+ * `prompt-queue-reorder.test.ts`. Those say what a drag should do; this says
+ * what a drag may never do, over every queue length, from/to pair and active
+ * slot: nothing lost or duplicated, nothing at or before the dispatching slot
+ * moved, the caller's array untouched, and the dispatch-changed flag honest.
+ */
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ canReorderPromptQueueRange,
+ promptQueueActiveItemChanged,
+ reorderPromptQueueItems,
+} from "../src/features/chat/utils/prompt-queue-reorder.ts";
+
+const MAX_LEN = 7;
+
+function queue(length: number): string[] {
+ return Array.from({ length }, (_, index) => `item-${index}`);
+}
+
+test("every accepted move is a permutation that loses nothing", () => {
+ for (let length = 0; length <= MAX_LEN; length++) {
+ const items = queue(length);
+ for (let active = 0; active <= length; active++) {
+ for (let from = 0; from < length; from++) {
+ for (let to = 0; to < length; to++) {
+ const next = reorderPromptQueueItems(items, from, to, active);
+ if (!next) continue;
+ assert.equal(next.length, items.length);
+ assert.deepEqual([...next].sort(), [...items].sort());
+ assert.equal(new Set(next).size, next.length);
+ }
+ }
+ }
+ }
+});
+
+test("the range check and the reorder never disagree", () => {
+ // The check guards a move the UI is about to make, so a move the check
+ // allows must produce an array and one it refuses must produce null. If the
+ // two drift apart, a row either refuses a legal drag or slips past the
+ // dispatch boundary.
+ for (let length = 0; length <= MAX_LEN; length++) {
+ const items = queue(length);
+ for (let active = 0; active <= length; active++) {
+ for (let from = -2; from <= length + 1; from++) {
+ for (let to = -2; to <= length + 1; to++) {
+ const allowed = canReorderPromptQueueRange(from, to, active, length);
+ const next = reorderPromptQueueItems(items, from, to, active);
+ assert.equal(
+ allowed,
+ next !== null,
+ `length=${length} active=${active} from=${from} to=${to}`,
+ );
+ }
+ }
+ }
+ }
+});
+
+test("the dragged item lands exactly where the drop said", () => {
+ for (let length = 1; length <= MAX_LEN; length++) {
+ const items = queue(length);
+ for (let from = 0; from < length; from++) {
+ for (let to = 0; to < length; to++) {
+ const next = reorderPromptQueueItems(items, from, to, 0);
+ if (!next) continue;
+ assert.equal(
+ next.indexOf(items[from]),
+ to,
+ `dragging ${from} onto ${to} in a queue of ${length}`,
+ );
+ }
+ }
+ }
+});
+
+test("nothing at or before the dispatching slot ever moves", () => {
+ // The item in the active slot is the one about to be sent, and everything
+ // before it has already gone. A move that reached them would either send a
+ // prompt the user had moved out of the way or re-send a spent one.
+ for (let length = 1; length <= MAX_LEN; length++) {
+ const items = queue(length);
+ for (let active = 0; active < length; active++) {
+ for (let from = 0; from < length; from++) {
+ for (let to = 0; to < length; to++) {
+ const next = reorderPromptQueueItems(items, from, to, active);
+ if (!next) continue;
+ assert.deepEqual(
+ next.slice(0, active),
+ items.slice(0, active),
+ `the spent head moved: active=${active} from=${from} to=${to}`,
+ );
+ }
+ }
+ }
+ }
+});
+
+test("a move and its reverse restore the queue", () => {
+ for (let length = 2; length <= MAX_LEN; length++) {
+ const items = queue(length);
+ for (let from = 0; from < length; from++) {
+ for (let to = 0; to < length; to++) {
+ const moved = reorderPromptQueueItems(items, from, to, 0);
+ if (!moved) continue;
+ assert.deepEqual(reorderPromptQueueItems(moved, to, from, 0), items);
+ }
+ }
+ }
+});
+
+test("the caller's array is never mutated", () => {
+ for (let length = 1; length <= MAX_LEN; length++) {
+ const items = queue(length);
+ const snapshot = [...items];
+ for (let from = 0; from < length; from++) {
+ for (let to = 0; to < length; to++) {
+ reorderPromptQueueItems(items, from, to, 0);
+ assert.deepEqual(items, snapshot);
+ }
+ }
+ }
+});
+
+test("a frozen queue can be reordered", () => {
+ // run.items is handed straight to this helper, and a store that freezes its
+ // state in development would throw on any in-place splice.
+ const frozen = Object.freeze(queue(4));
+ assert.deepEqual(reorderPromptQueueItems(frozen, 0, 2, 0), [
+ "item-1",
+ "item-2",
+ "item-0",
+ "item-3",
+ ]);
+});
+
+test("indices that are not real positions are refused", () => {
+ const items = queue(4);
+ for (const bad of [
+ Number.NaN,
+ Number.POSITIVE_INFINITY,
+ Number.NEGATIVE_INFINITY,
+ 1.5,
+ -1,
+ 4,
+ 99,
+ -0.5,
+ ]) {
+ assert.equal(reorderPromptQueueItems(items, bad, 1, 0), null, `from=${bad}`);
+ assert.equal(reorderPromptQueueItems(items, 1, bad, 0), null, `to=${bad}`);
+ }
+ // -0 is an integer and index 0, so it is a real position and must be allowed
+ // rather than falling into the refusals above.
+ assert.deepEqual(reorderPromptQueueItems(items, -0, 2, 0), [
+ "item-1",
+ "item-2",
+ "item-0",
+ "item-3",
+ ]);
+});
+
+test("an empty queue and a single row have nothing to reorder", () => {
+ assert.equal(reorderPromptQueueItems([], 0, 0, 0), null);
+ assert.equal(reorderPromptQueueItems(["only"], 0, 0, 0), null);
+});
+
+test("an active slot past the end refuses everything", () => {
+ // The run has dispatched every item it holds; there is nothing left to move.
+ const items = queue(4);
+ for (let from = 0; from < 4; from++) {
+ for (let to = 0; to < 4; to++) {
+ assert.equal(reorderPromptQueueItems(items, from, to, 4), null);
+ }
+ }
+});
+
+test("the dispatch-changed flag agrees with the slot it reports on", () => {
+ for (let length = 1; length <= MAX_LEN; length++) {
+ const items = queue(length);
+ for (let active = 0; active < length; active++) {
+ for (let from = 0; from < length; from++) {
+ for (let to = 0; to < length; to++) {
+ const next = reorderPromptQueueItems(items, from, to, active);
+ if (!next) continue;
+ assert.equal(
+ promptQueueActiveItemChanged(items, next, active),
+ items[active] !== next[active],
+ `active=${active} from=${from} to=${to}`,
+ );
+ }
+ }
+ }
+ }
+});
+
+test("a run that has not dispatched yet reports no dispatch change", () => {
+ // run.index is -1 before the first send, and there is no pending dispatch to
+ // retarget, so the caller must not be told to reschedule one.
+ const items = queue(3);
+ const next = reorderPromptQueueItems(items, 0, 2, 0);
+ assert.ok(next);
+ assert.equal(promptQueueActiveItemChanged(items, next, -1), false);
+});
+
+test("the flag compares identity, not contents", () => {
+ // Queue items are objects, so two prompts with the same text are still two
+ // items. Comparing by value would miss a real change between them.
+ const a = { prompt: "same" };
+ const b = { prompt: "same" };
+ assert.equal(promptQueueActiveItemChanged([a, b], [b, a], 0), true);
+ assert.equal(promptQueueActiveItemChanged([a, b], [a, b], 0), false);
+});
diff --git a/studio/frontend/tests/prompt-queue-reorder.test.ts b/studio/frontend/tests/prompt-queue-reorder.test.ts
new file mode 100644
index 00000000000..fff6e143891
--- /dev/null
+++ b/studio/frontend/tests/prompt-queue-reorder.test.ts
@@ -0,0 +1,91 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ canReorderPromptQueueRange,
+ promptQueueActiveItemChanged,
+ reorderPromptQueueItems,
+} from "../src/features/chat/utils/prompt-queue-reorder.ts";
+
+const QUEUE = ["a", "b", "c", "d"];
+
+test("a downward drag lands after the target", () => {
+ assert.deepEqual(reorderPromptQueueItems(QUEUE, 0, 2), ["b", "c", "a", "d"]);
+});
+
+test("an upward drag lands before the target", () => {
+ assert.deepEqual(reorderPromptQueueItems(QUEUE, 3, 1), ["a", "d", "b", "c"]);
+});
+
+test("adjacent rows swap", () => {
+ assert.deepEqual(reorderPromptQueueItems(QUEUE, 1, 2), ["a", "c", "b", "d"]);
+ assert.deepEqual(reorderPromptQueueItems(QUEUE, 2, 1), ["a", "c", "b", "d"]);
+});
+
+test("the queue keeps every item, and the source array is untouched", () => {
+ const next = reorderPromptQueueItems(QUEUE, 0, 3);
+ assert.ok(next);
+ assert.deepEqual([...next].sort(), [...QUEUE].sort());
+ assert.deepEqual(QUEUE, ["a", "b", "c", "d"]);
+});
+
+test("a move onto itself is refused", () => {
+ assert.equal(reorderPromptQueueItems(QUEUE, 2, 2), null);
+});
+
+test("nothing crosses the item about to dispatch", () => {
+ // activeIndex 1: "a" is spent, so it is neither a source nor a destination.
+ assert.equal(reorderPromptQueueItems(QUEUE, 0, 2, 1), null);
+ assert.equal(reorderPromptQueueItems(QUEUE, 2, 0, 1), null);
+ // Moves at or past the active slot still go through.
+ assert.deepEqual(reorderPromptQueueItems(QUEUE, 1, 3, 1), [
+ "a",
+ "c",
+ "d",
+ "b",
+ ]);
+});
+
+test("out-of-range and non-integer indices are refused", () => {
+ assert.equal(reorderPromptQueueItems(QUEUE, -1, 2), null);
+ assert.equal(reorderPromptQueueItems(QUEUE, 0, 4), null);
+ assert.equal(reorderPromptQueueItems(QUEUE, 1.5, 2), null);
+ assert.equal(reorderPromptQueueItems([], 0, 0), null);
+});
+
+test("the range check agrees with the reorder it guards", () => {
+ for (let from = -1; from <= QUEUE.length; from += 1) {
+ for (let to = -1; to <= QUEUE.length; to += 1) {
+ assert.equal(
+ canReorderPromptQueueRange(from, to, 1, QUEUE.length),
+ reorderPromptQueueItems(QUEUE, from, to, 1) !== null,
+ `from ${from} to ${to}`,
+ );
+ }
+ }
+});
+
+test("a move into the active slot reports the dispatch target changed", () => {
+ const before = QUEUE;
+ const after = reorderPromptQueueItems(before, 2, 1, 1);
+ assert.ok(after);
+ assert.equal(promptQueueActiveItemChanged(before, after, 1), true);
+});
+
+test("a move below the active slot leaves the dispatch target alone", () => {
+ const before = QUEUE;
+ const after = reorderPromptQueueItems(before, 2, 3, 1);
+ assert.ok(after);
+ assert.equal(promptQueueActiveItemChanged(before, after, 1), false);
+});
+
+test("a run with no active item reports no change", () => {
+ // run.index is -1 before the first dispatch, so there is nothing to retarget.
+ assert.equal(
+ promptQueueActiveItemChanged(QUEUE, ["b", "a", "c", "d"], -1),
+ false,
+ );
+});