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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: stop a sent prompt staying in the chat composer (#8849)
Michael Han127f2a3f8566
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex c744032c389..300b2667509 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -174,6 +174,14 @@ import {usePlusMenuPrefsStore,writeComposerDraft,} from "@/features/chat";+import {+ applySentTextGuard,+ armSentTextGuard,+ isGuardRetiringKey,+ markSentTextGuardUserInput,+ sentTextGuardBlocksDraft,+ type SentTextGuard,+} from "@/features/chat/utils/composer-send-guard";import { deleteThreadMessage } from "@/features/chat/utils/delete-thread-message";import {getStoredChatThread,@@ -261,6 +269,7 @@ import {type KeyboardEvent,type DragEvent as ReactDragEvent,type ReactNode,+ type RefObject,Fragment,createContext,memo,@@ -2125,8 +2134,14 @@ const Composer: FC<{const pastedTextMinChars = useChatPreferencesStore((state) => state.pastedTextMinChars,);+ // 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);+ // Thread on screen, so the guard can tell whether a write belongs to the+ // thread that sent. Kept in step by the effect alongside pasteDraftKeyRef.+ const draftKeyRef = useRef<string | null>(null);const { inputProps, isComposing, isComposingRef } =- useImeComposerInputHandlers({ submitOnEnter: true });+ useImeComposerInputHandlers({ submitOnEnter: true, justSentRef, draftKeyRef });// A pasted YouTube link offers a transcript attachment above the composer.const [youtubeLink, setYoutubeLink] = useState<string | null>(null);const handleFilePaste = useCallback(@@ -2177,6 +2192,17 @@ const Composer: FC<{description: "The clipboard item is unsupported, unreadable, or exceeds its size limit.",}),);+ // A paste is a gesture, so it retires the guard and re-pasting the sent+ // prompt goes through. Last, and only when the browser will really insert+ // the text: a payload carrying files is preventDefaulted above, so+ // retiring for it would just free the next queued write to refill.+ if (+ pastedText.length > 0 &&+ !event.defaultPrevented &&+ justSentRef.current?.draftKey === draftKeyRef.current+ ) {+ justSentRef.current = null;+ }},[aui, overlay, pastedTextMinChars],);@@ -2620,10 +2646,36 @@ const Composer: FC<{useEffect(() => {const draft = draftKey ? (readComposerDraft(draftKey) ?? "") : "";const composer = aui.composer();- if (composer.getState().isEditing) {- composer.setText(draft);+ if (!composer.getState().isEditing) return;+ // A save that raced the send still holds the sent text, so restoring it+ // would undo the clear. Keyed on the sending thread, so another thread's+ // identical draft still restores. Clear rather than return early, which+ // would leave the previous thread's text on screen under this one.+ if (sentTextGuardBlocksDraft(justSentRef.current, draft, draftKey)) {+ // Written inline rather than via clearStoredDraft, which is declared+ // below this effect. Cancel the pending save too, or it rewrites the key.+ if (draftSaveTimerRef.current !== null) {+ clearTimeout(draftSaveTimerRef.current);+ draftSaveTimerRef.current = null;+ }+ if (draftKey) writeComposerDraft(draftKey, "");+ composer.setText("");+ return;}+ composer.setText(draft);}, [draftKey, aui]);+ // The saved-prompt menu and the prompt storage dialog fill the composer+ // directly, bypassing the guard. Text appearing while the sending thread is+ // on screen was put there deliberately, so retire; the draftKey check keeps+ // another thread's restored draft from doing the same. Read live, or a+ // pending render retires it on stale text. Must stay after the restore+ // above, which clears the raced draft this would otherwise retire on.+ useEffect(() => {+ const guard = justSentRef.current;+ if (guard === null || guard.draftKey !== draftKey) return;+ if (aui.composer().getState().text.length === 0) return;+ justSentRef.current = null;+ }, [composerText, draftKey, aui]);// Separate from the text restore above, which must stay keyed on the draft// alone: this one retries on attachment changes, and rewriting the composer// text on those would drop whatever had been typed since the last autosave.@@ -2675,14 +2727,15 @@ const Composer: FC<{draftSaveTimerRef.current = t;return () => clearTimeout(t);}, [composerText, draftKey]);- // Without this the restore effect above puts the sent text back when the- // runtime rebinds on the first message.- const draftKeyRef = useRef(draftKey);const pasteDraftKeyRef = useRef(pasteDraftKey);useEffect(() => {draftKeyRef.current = draftKey;pasteDraftKeyRef.current = pasteDraftKey;}, [draftKey, pasteDraftKey]);+ // Call wherever the composer is emptied because its text left as a message.+ const armJustSent = useCallback((...texts: string[]) => {+ justSentRef.current = armSentTextGuard(texts, draftKeyRef.current);+ }, []);const clearStoredDraft = useCallback(() => {if (draftSaveTimerRef.current !== null) {clearTimeout(draftSaveTimerRef.current);@@ -3157,6 +3210,7 @@ const Composer: FC<{composer.setText("");});clearStoredDraft();+ armJustSent(state.text);});}).catch(() => {@@ -3166,7 +3220,7 @@ const Composer: FC<{});return true;},- [aui, clearStoredDraft, startHydratedPromptQueue],+ [armJustSent, aui, clearStoredDraft, startHydratedPromptQueue],);const dismissWaitToast = useCallback(() => {@@ -3254,7 +3308,9 @@ const Composer: FC<{],);- const sendReservedComposer = useCallback(() => {+ // alsoGuard: text the composer showed before this path rewrote it, so a late+ // write carrying what the user actually typed is refused too.+ const sendReservedComposer = useCallback((...alsoGuard: string[]) => {const assistantRuntime =aui.threads().__internal_getAssistantRuntime?.();let reservationToken: symbol | null = null;@@ -3283,7 +3339,10 @@ const Composer: FC<{}preStreamRunReservationRef.current = reservationToken;try {+ const sentText = aui.composer().getState().text;aui.composer().send();+ // Empty texts are dropped, so an attachment-only send still clears.+ armJustSent(sentText, ...alsoGuard);} catch (error) {if (releasePreStreamRunReservation(reservationToken)) {notifyPromptQueueRunFailed(referenceThreadId);@@ -3294,7 +3353,7 @@ const Composer: FC<{error instanceof Error ? error.message : "Please retry the send.",});}- }, [aui, preStreamThreadIds, referenceThreadId]);+ }, [aui, armJustSent, preStreamThreadIds, referenceThreadId]);// Gate for both form submit and the Send button. Returns true when it handled// the event (blocked or queued) so callers stop.@@ -3558,13 +3617,16 @@ const Composer: FC<{[queuedPrompt],liveThreadIsRunning || livePreStreamRunActive,() => {- if (aui.composer().getState().text.trim() !== queuedPrompt) {+ // 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);},);return;@@ -3605,6 +3667,9 @@ const Composer: FC<{: {}),openaiReasoningItem: overlay.openaiReasoningItem,});+ // Live, not composerText: a late DOM write carries exactly what the+ // textarea held, whitespace and all, and that is what must be armed.+ const visibleBeforeWrap = aui.composer().getState().text;flushResourcesSync(() => {aui.composer()@@ -3614,7 +3679,8 @@ const Composer: FC<{});closeOverlay();event.preventDefault();- sendReservedComposer();+ // The wrapper replaced what the user typed, so guard that text as well.+ sendReservedComposer(visibleBeforeWrap, trimmed);return;}@@ -3629,6 +3695,7 @@ const Composer: FC<{sendReservedComposer();},[+ armJustSent,aui,canQueueCurrentPrompt,canQueuePastedTextPrompt,@@ -3801,15 +3868,15 @@ const Composer: FC<{[queuedPrompt],true,() => {- if (- aui.composer().getState().text.trim() !== queuedPrompt- ) {+ const cleared = aui.composer().getState().text;+ if (cleared.trim() !== queuedPrompt) {return;}flushResourcesSync(() => {aui.composer().setText("");});clearStoredDraft();+ armJustSent(queuedPrompt, cleared);},);}}@@ -3888,6 +3955,44 @@ function isNativeComposing(event: Event) {return "isComposing" in event && (event as InputEvent).isComposing === true;}+// An autocorrect commit, never a keystroke, a paste or an undo. Its value can+// differ from what was sent, so equality alone would let it through.+function isTextReplacement(event: Event | undefined) {+ return inputTypeOf(event) === "insertReplacementText";+}++// An IME composition write. Finalisation converts the text, so equality never+// matches it, and it is stale only when the composition began before the send:+// one begun after raises compositionstart, which records user input.+// compositionend counts because onCompositionEnd applies that value itself and+// the browser raises no input event for it.+function isCompositionWrite(event: Event | undefined) {+ return (+ inputTypeOf(event) === "insertCompositionText" ||+ event?.type === "compositionend" ||+ (event !== undefined && isNativeComposing(event))+ );+}++// Input types only a gesture produces, so they apply even when they carry the+// sent text. Drag and drop and yank have no event to hook the way paste does.+const DELIBERATE_INPUT_TYPES = new Set([+ "historyUndo",+ "historyRedo",+ "insertFromPaste",+ "insertFromDrop",+ "insertFromYank",+]);++function isDeliberateWrite(event: Event | undefined) {+ return DELIBERATE_INPUT_TYPES.has(inputTypeOf(event) ?? "");+}++function inputTypeOf(event: Event | undefined): string | undefined {+ if (event === undefined || !("inputType" in event)) return undefined;+ return (event as InputEvent).inputType;+}+// Fallback timeout for stuck IME composition. With Chrome on Windows against// a WSL-hosted Unsloth (issue #5546), `compositionend` never fires after the// candidate commits, so `composingRef` stays true and Send stays disabled.@@ -3898,8 +4003,15 @@ const IME_STUCK_TIMEOUT_MS = 2500;function useImeComposerInputHandlers({submitOnEnter = false,+ justSentRef,+ draftKeyRef,}: {submitOnEnter?: boolean;+ // 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+ // says whether the armed guard belongs to the thread being typed into.+ draftKeyRef?: RefObject<string | null>;} = {}) {const aui = useAui();const composingRef = useRef(false);@@ -3943,22 +4055,50 @@ function useImeComposerInputHandlers({useEffect(() => clearStuckTimer, [clearStuckTimer]);+ // False when refused, so the caller can preventDefault and stop+ // ComposerPrimitive.Input's own handler applying the same value.const setComposerText = useCallback(- (value: string) => {+ (value: string, nativeEvent?: Event): boolean => {const composer = aui.composer();if (!composer.getState().isEditing) {- return;+ return false;+ }+ // Refuse a write that is the sent message coming back, but only for the+ // thread that sent: typing in another thread must not retire a guard it+ // does not own, or its raced draft returns.+ const guardOwnsThread =+ justSentRef?.current == null ||+ draftKeyRef === undefined ||+ justSentRef.current.draftKey === draftKeyRef.current;+ if (justSentRef && guardOwnsThread) {+ const result = applySentTextGuard(justSentRef.current, {+ value,+ replacesText: isTextReplacement(nativeEvent),+ isDeliberate: isDeliberateWrite(nativeEvent),+ isComposition: isCompositionWrite(nativeEvent),+ composerIsEmpty: composer.getState().text.length === 0,+ });+ justSentRef.current = result.guard;+ if (!result.accept) {+ return false;+ }}flushResourcesSync(() => {composer.setText(value);});+ return true;},- [aui],+ [aui, draftKeyRef, justSentRef],);const onCompositionStart = useCallback(() => {+ // Dictation and handwriting insert without a keydown, and a composition+ // starting after the send cannot be a write the send queued.+ if (justSentRef) {+ justSentRef.current = markSentTextGuardUserInput(justSentRef.current);+ }setCompositionState(true);- }, [setCompositionState]);+ }, [justSentRef, setCompositionState]);const onCompositionUpdate = useCallback(() => {refreshStuckTimer();@@ -3967,7 +4107,9 @@ function useImeComposerInputHandlers({const onCompositionEnd = useCallback((e: CompositionEvent<HTMLTextAreaElement>) => {setCompositionState(false);- setComposerText(e.currentTarget.value);+ if (!setComposerText(e.currentTarget.value, e.nativeEvent)) {+ e.preventDefault();+ }},[setComposerText, setCompositionState],);@@ -3975,7 +4117,9 @@ function useImeComposerInputHandlers({const onChange = useCallback((e: ChangeEvent<HTMLTextAreaElement>) => {setCompositionState(isNativeComposing(e.nativeEvent));- setComposerText(e.target.value);+ if (!setComposerText(e.target.value, e.nativeEvent)) {+ e.preventDefault();+ }},[setComposerText, setCompositionState],);@@ -3990,10 +4134,16 @@ function useImeComposerInputHandlers({const onKeyDown = useCallback((e: KeyboardEvent<HTMLTextAreaElement>) => {if (e.nativeEvent.isComposing || e.keyCode === 229) {+ // Deliberately NOT user input: picking a candidate in a composition the+ // send left open is that composition continuing. One begun after the+ // send is marked by compositionstart instead.composingRef.current = true;refreshStuckTimer();return;}+ if (justSentRef && isGuardRetiringKey(e)) {+ justSentRef.current = markSentTextGuardUserInput(justSentRef.current);+ }if (composingRef.current) {// Candidate-confirming Enter can arrive as non-composing; keep it gated.if (e.key === "Enter") {@@ -4015,7 +4165,7 @@ function useImeComposerInputHandlers({e.currentTarget.form?.requestSubmit();}},- [refreshStuckTimer, setCompositionState, submitOnEnter],+ [justSentRef, refreshStuckTimer, setCompositionState, submitOnEnter],);// On macOS, switching input methods (e.g. ABC → Pinyin) while the textareadiff --git a/studio/frontend/src/features/chat/utils/composer-send-guard.ts b/studio/frontend/src/features/chat/utils/composer-send-guard.tsnew file mode 100644index 00000000000..8fc5b9c80a8--- /dev/null+++ b/studio/frontend/src/features/chat/utils/composer-send-guard.ts@@ -0,0 +1,123 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/**+ * Refuses writes that put a just-sent message back into the composer: an event+ * the engine queued against the pre-send value (autocorrect commit, IME+ * finalise) or a draft autosave that raced the send. The next autosave makes+ * one stick, so the prompt sends and the text stays in the box.+ *+ * Retired by user intent, never by a clock: queue latency has no upper bound, so+ * a backgrounded page can deliver a stale write long after any window expired.+ * Typing retires it since a typed value differs, and a paste retires it+ * explicitly, being the one legitimate write identical to what was sent.+ */+export type SentTextGuard = {+ /** Values to refuse. The overlay send arms the wrapper and what was on screen. */+ readonly texts: readonly string[];+ /** Draft key the send cleared, so another thread's identical draft still restores. */+ readonly draftKey: string | null;+ /** A key has been pressed since the send. See markSentTextGuardUserInput. */+ readonly userInputSince: boolean;+};++export function armSentTextGuard(+ texts: readonly string[],+ draftKey: string | null,+): SentTextGuard {+ return {+ texts: texts.filter((text) => text.length > 0),+ draftKey,+ userInputSince: false,+ };+}++/**+ * Whether a keydown is the user starting to type again rather than part of the+ * send. Enter is excluded because the send arms the guard from inside that very+ * keydown, and a chord is excluded because it is a command, not a character.+ */+export function isGuardRetiringKey(event: {+ key: string;+ metaKey: boolean;+ ctrlKey: boolean;+ altKey?: boolean;+ getModifierState?: (key: "AltGraph") => boolean;+}): boolean {+ // AltGr types characters but Windows reports it as Ctrl+Alt, so the chord+ // check alone would drop every character produced with it. Both forms are+ // tested: some builds set the flags even while AltGraph reads true.+ const altGraph =+ event.getModifierState?.("AltGraph") === true ||+ (event.ctrlKey && event.altKey === true && event.key.length === 1);+ if (!altGraph && (event.metaKey || event.ctrlKey)) return false;+ if (event.key === "Enter" || event.key === "Escape" || event.key === "Tab") {+ return false;+ }+ // Modifiers alone are not typing; the character keydown follows them.+ return !["Shift", "Control", "Alt", "Meta", "CapsLock"].includes(event.key);+}++/**+ * A keydown, or a composition starting for dictation, handwriting or an IME.+ * The send's queued writes are delivered before either, so one proves they have+ * drained. Relaxes the equality check only, never the autocorrect rule or the+ * draft suppression, so it cannot widen into the original bug.+ */+export function markSentTextGuardUserInput(+ guard: SentTextGuard | null,+): SentTextGuard | null {+ if (guard === null || guard.userInputSince) return guard;+ return { ...guard, userInputSince: true };+}++/** Whether a draft restore is the sent text coming back under the same key. */+export function sentTextGuardBlocksDraft(+ guard: SentTextGuard | null,+ draft: string,+ draftKey: string | null,+): boolean {+ if (guard === null) return false;+ return guard.draftKey === draftKey && guard.texts.includes(draft);+}++export function applySentTextGuard(+ guard: SentTextGuard | null,+ write: {+ value: string;+ /**+ * An autocorrect commit, the engine rather than the user. It cannot start+ * from an empty composer, so on one it is stale, mutated value and all.+ */+ replacesText: boolean;+ /**+ * Undo, redo, or text brought in from elsewhere. A queued write never+ * reports one, so it applies even when it restores what was sent.+ */+ isDeliberate: boolean;+ /**+ * An IME composition write. Stale only when the composition began before+ * the send; one begun after raises compositionstart, which records user+ * input, so userInputSince separates the two.+ */+ isComposition: boolean;+ composerIsEmpty: boolean;+ },+): { accept: boolean; guard: SentTextGuard | null } {+ if (guard === null) return { accept: true, guard: null };+ if (write.isDeliberate) return { accept: true, guard: null };+ // Re-typing the whole prompt is only one write when it is one character, so+ // equality alone would swallow every retry of a "?" or a single emoji.+ if (guard.texts.includes(write.value)) {+ if (guard.userInputSince) return { accept: true, guard: null };+ return { accept: false, guard };+ }+ if (write.replacesText && write.composerIsEmpty) {+ return { accept: false, guard };+ }+ if (write.isComposition && write.composerIsEmpty && !guard.userInputSince) {+ return { accept: false, guard };+ }+ // Anything else is the user, so stop guarding rather than judge later writes.+ return { accept: true, guard: null };+}diff --git a/studio/frontend/tests/composer-send-guard.test.ts b/studio/frontend/tests/composer-send-guard.test.tsnew file mode 100644index 00000000000..45cbe1cbc9f--- /dev/null+++ b/studio/frontend/tests/composer-send-guard.test.ts@@ -0,0 +1,329 @@+// 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 {+ applySentTextGuard,+ armSentTextGuard,+ isGuardRetiringKey,+ markSentTextGuardUserInput,+ sentTextGuardBlocksDraft,+} from "../src/features/chat/utils/composer-send-guard.ts";++const PROMPT = "Simulate a Tesla coil in a workshop.";+const KEY = "chat-draft:thread-1";++const typed = (value: string) => ({+ value,+ replacesText: false,+ isDeliberate: false,+ isComposition: false,+ composerIsEmpty: false,+});+const replacement = (value: string, composerIsEmpty = true) => ({+ value,+ replacesText: true,+ isDeliberate: false,+ isComposition: false,+ composerIsEmpty,+});+// Undo, redo, paste, drop and yank all arrive this way.+const deliberate = (value: string) => ({+ value,+ replacesText: false,+ isDeliberate: true,+ isComposition: false,+ composerIsEmpty: true,+});+// An IME write. Finalisation converts the text, so equality never matches it.+const composing = (value: string) => ({+ value,+ replacesText: false,+ isDeliberate: false,+ isComposition: true,+ composerIsEmpty: true,+});+const armed = (texts: string[] = [PROMPT], key: string | null = KEY) =>+ armSentTextGuard(texts, key);++test("with nothing armed every write is applied", () => {+ assert.deepEqual(applySentTextGuard(null, typed(PROMPT)), {+ accept: true,+ guard: null,+ });+});++// The reported bug: the prompt sends, the text stays in the box.+test("a write carrying the just-sent text is refused", () => {+ assert.equal(applySentTextGuard(armed(), typed(PROMPT)).accept, false);+});++test("the guard survives a refusal, since an engine can queue several", () => {+ const first = applySentTextGuard(armed(), typed(PROMPT));+ assert.equal(applySentTextGuard(first.guard, typed(PROMPT)).accept, false);+});++// Event queue latency has no upper bound, so a stale write arriving long after+// the send must still be refused. Nothing here is time based.+test("a stale write is refused however late it arrives", () => {+ let guard = armed();+ for (let i = 0; i < 100; i += 1) {+ const result = applySentTextGuard(guard, typed(PROMPT));+ assert.equal(result.accept, false);+ guard = result.guard as ReturnType<typeof armed>;+ }+});++test("typing after a send is applied and retires the guard", () => {+ assert.deepEqual(applySentTextGuard(armed(), typed("a follow-up")), {+ accept: true,+ guard: null,+ });+});++// An attachment-only send depends on the clear going through.+test("empty texts are never armed, so clearing is never refused", () => {+ const guard = armSentTextGuard(["", ""], KEY);+ assert.deepEqual(guard.texts, []);+ assert.equal(applySentTextGuard(guard, typed("")).accept, true);+});++// An autocorrect commit mutates the text, so equality alone would let it back+// in. It cannot originate from an empty composer, which is what marks it stale.+test("a mutated replacement into an emptied composer is refused", () => {+ assert.equal(applySentTextGuard(armed(), replacement(`${PROMPT}!`)).accept, false);+});++test("a replacement once the user has typed again is applied", () => {+ assert.equal(+ applySentTextGuard(armed(), replacement("teh cat", false)).accept,+ true,+ );+});++// A deliberate re-paste is byte-identical to what was sent, so only the paste+// gesture itself can tell the two apart. The composer nulls the guard on paste,+// which is this state.+test("an identical re-paste is applied once the paste has retired the guard", () => {+ assert.deepEqual(applySentTextGuard(null, typed(PROMPT)), {+ accept: true,+ guard: null,+ });+});++// The image-edit send replaces what the user typed with a wrapper, so a late+// write carrying either one has to be refused.+test("both the wrapper and the visible text are guarded", () => {+ const guard = armed([`Apply this edit: ${PROMPT}`, PROMPT]);+ assert.equal(applySentTextGuard(guard, typed(PROMPT)).accept, false);+ assert.equal(+ applySentTextGuard(guard, typed(`Apply this edit: ${PROMPT}`)).accept,+ false,+ );+});++test("a draft holding the sent text is not restored", () => {+ assert.equal(sentTextGuardBlocksDraft(armed(), PROMPT, KEY), true);+});++// The composer outlives a thread switch, so text alone would hide an unrelated+// thread's identical draft.+test("another thread's identical draft still restores", () => {+ assert.equal(+ sentTextGuardBlocksDraft(armed(), PROMPT, "chat-draft:thread-2"),+ false,+ );+});++test("an unrelated draft is restored", () => {+ assert.equal(sentTextGuardBlocksDraft(armed(), "something else", KEY), false);+ assert.equal(sentTextGuardBlocksDraft(null, PROMPT, KEY), false);+});++// Undo after sending is how a user recovers a prompt to edit and resend. It+// restores exactly what was sent, so only the gesture tells it from a stale+// write, and the gesture is deliberate.+test("a deliberate undo restores the sent prompt and retires the guard", () => {+ assert.deepEqual(applySentTextGuard(armed(), deliberate(PROMPT)), {+ accept: true,+ guard: null,+ });+});++test("undo wins even over an armed wrapper pair", () => {+ const guard = armed([`Apply this edit: ${PROMPT}`, PROMPT]);+ assert.equal(applySentTextGuard(guard, deliberate(PROMPT)).accept, true);+});++// Autocorrect is the engine, not the user, so it stays refused.+test("an autocorrect commit is still refused after the undo carve-out", () => {+ assert.equal(+ applySentTextGuard(armed(), replacement(`${PROMPT}!`)).accept,+ false,+ );+});++// The image-edit send wraps what the user typed, and the wrapper is built from+// the trimmed text. A late DOM write carries the raw textarea value, so arming+// the trimmed form alone misses it whenever the instruction had whitespace.+test("the raw pre-send value is guarded, not just its trimmed form", () => {+ const raw = " make it brighter ";+ const guard = armSentTextGuard(+ [`Apply this edit: ${raw.trim()}`, raw, raw.trim()],+ KEY,+ );+ assert.equal(applySentTextGuard(guard, typed(raw)).accept, false);+ assert.equal(applySentTextGuard(guard, typed(raw.trim())).accept, false);+});++// Re-typing the sent prompt is normally several writes, and the first one+// already differs. A one-character prompt arrives whole in a single write, so+// equality alone swallowed it and kept the guard, blocking every retry.+test("re-typing a one-character prompt is applied", () => {+ const guard = markSentTextGuardUserInput(armed(["?"]));+ assert.deepEqual(applySentTextGuard(guard, typed("?")), {+ accept: true,+ guard: null,+ });+});++// The stale write is queued before the send, so it is delivered before any+// later keydown. Without one, equality still refuses it.+test("a stale write with no keystroke behind it is still refused", () => {+ assert.equal(applySentTextGuard(armed(["?"]), typed("?")).accept, false);+});++// The keystroke relaxes equality only. An autocorrect commit into an empty+// composer stays stale whatever the user pressed.+test("a keystroke does not let an autocorrect commit through", () => {+ const guard = markSentTextGuardUserInput(armed());+ assert.equal(+ applySentTextGuard(guard, replacement(`${PROMPT}!`)).accept,+ false,+ );+});++test("a keystroke does not unblock the raced draft", () => {+ const guard = markSentTextGuardUserInput(armed());+ assert.equal(sentTextGuardBlocksDraft(guard, PROMPT, KEY), true);+});++// Dictation, handwriting and IMEs insert without a keydown, so the composition+// they start is the boundary instead. A one-emoji prompt is the case that needs+// it, since the whole value arrives in a single committed write.+test("a composition started after the send lets its commit through", () => {+ const guard = markSentTextGuardUserInput(armed(["\u{1F642}"]));+ assert.deepEqual(applySentTextGuard(guard, typed("\u{1F642}")), {+ accept: true,+ guard: null,+ });+});++test("marking an unarmed guard is a no-op", () => {+ assert.equal(markSentTextGuardUserInput(null), null);+});++const key = (k: string, mods: { metaKey?: boolean; ctrlKey?: boolean } = {}) =>+ isGuardRetiringKey({+ key: k,+ metaKey: mods.metaKey ?? false,+ ctrlKey: mods.ctrlKey ?? false,+ });++// Enter is the send itself: the guard is armed from inside that keydown, so+// counting it would retire the guard before a single stale write could land.+test("the sending Enter is not a keystroke boundary", () => {+ assert.equal(key("Enter"), false);+ assert.equal(key("Enter", { metaKey: true }), false);+});++test("characters and IME keys are keystroke boundaries", () => {+ assert.equal(key("?"), true);+ assert.equal(key("a"), true);+ assert.equal(key("Process"), true);+ assert.equal(key("Backspace"), true);+});++// A chord is a command, and paste has its own carve-out already.+test("chords and bare modifiers are not keystroke boundaries", () => {+ assert.equal(key("v", { metaKey: true }), false);+ assert.equal(key("z", { ctrlKey: true }), false);+ assert.equal(key("Shift"), false);+ assert.equal(key("Meta"), false);+ assert.equal(key("Escape"), false);+ assert.equal(key("Tab"), false);+});++// Dragging the sent prompt back in, or yanking it back, carries exactly what+// was sent and fires no paste event, so the paste carve-out never sees it.+// Both were measured swallowed in Chromium, Firefox and WebKit alike.+test("a drop or a yank of the sent text is applied", () => {+ assert.deepEqual(applySentTextGuard(armed(), deliberate(PROMPT)), {+ accept: true,+ guard: null,+ });+});++test("a deliberate write wins over an armed wrapper pair", () => {+ const guard = armed([`Apply this edit: ${PROMPT}`, PROMPT]);+ assert.equal(applySentTextGuard(guard, deliberate(PROMPT)).accept, true);+});++// A composition still open when the send happened commits a converted value+// that matches no armed text. compositionstart is what separates it from one+// the user began afterwards.+test("a composition begun before the send is refused", () => {+ const guard = armed();+ assert.deepEqual(applySentTextGuard(guard, composing("\u65e5\u672c\u8a9e")), {+ accept: false,+ guard,+ });+});++test("a composition begun after the send is applied", () => {+ const guard = markSentTextGuardUserInput(armed());+ assert.deepEqual(applySentTextGuard(guard, composing("\u65e5\u672c\u8a9e")), {+ accept: true,+ guard: null,+ });+});++// AltGr is how a lot of layouts reach @, so a one-character prompt typed with+// it must retire the equality guard. Windows reports it as Ctrl+Alt, and some+// builds set those flags even while AltGraph reads true, so both forms count.+test("an AltGr character is a keystroke boundary", () => {+ assert.equal(+ isGuardRetiringKey({+ key: "@",+ metaKey: false,+ ctrlKey: true,+ altKey: true,+ getModifierState: (k: "AltGraph") => k === "AltGraph",+ }),+ true,+ );+ assert.equal(+ isGuardRetiringKey({ key: "@", metaKey: false, ctrlKey: true, altKey: true }),+ true,+ );+});++test("a real Ctrl chord is still not a keystroke boundary", () => {+ assert.equal(+ isGuardRetiringKey({+ key: "a",+ metaKey: false,+ ctrlKey: true,+ altKey: false,+ getModifierState: () => false,+ }),+ false,+ );+ // Ctrl+Alt on a named key is a shortcut, not a character.+ assert.equal(+ isGuardRetiringKey({ key: "Delete", metaKey: false, ctrlKey: true, altKey: true }),+ false,+ );+});diff --git a/tests/studio/test_multi_chat_prompt_queue_contract.py b/tests/studio/test_multi_chat_prompt_queue_contract.pyindex 3af7829d4b1..2ab1100d01c 100644--- a/tests/studio/test_multi_chat_prompt_queue_contract.py+++ b/tests/studio/test_multi_chat_prompt_queue_contract.py@@ -163,7 +163,10 @@ def test_composer_only_queues_behind_the_current_chat():assert "livePreStreamRunActive" in submitassert "liveThreadIsRunning || livePreStreamRunActive" in submitassert "startHydratedPromptQueue(" in submit- assert "aui.composer().getState().text.trim() !== queuedPrompt" in submit+ # Read into a local first: the send guard arms on the untrimmed value too,+ # since that is what a late DOM write carries.+ assert "const cleared = aui.composer().getState().text" in submit+ assert "cleared.trim() !== queuedPrompt" in submitassert "promptQueueStartPendingRef.current" in THREADassert "promptQueueStartPendingRef.current.has(reservationKey)" in THREADassert "promptQueueStartPendingRef.current.delete(reservationKey)" in THREAD