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.

Queue a parked send when a run started while it waited (#9810)

Daniel Han788ef7127778
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index cbaf65f90b6..ff613172cbc 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -4186,24 +4186,63 @@ const Composer: FC<{
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.
+ // 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 ||
+ hasPreStreamRunReservation(preStreamThreadIds);
+ // A parked send is a submit arriving late, so mirror handleSubmit's
+ // branches. Sending regardless is how a message vanished: on a throttled
+ // browser a follow-up parked 786 ms in was released 236 ms later with
+ // the first turn still streaming, went to sendReservedComposer(), and
+ // was refused by the runtime -- neither queued nor sent, and the wait
+ // toast already dismissed above, so nothing on screen said so.
+ //
+ // Research refuses every submit and swaps Send for Stop research, so a
+ // release here would start a turn from a state where input is disabled.
+ if (isResearchActive) {
+ return;
+ }
+ if (waitForCurrentRun) {
+ // Queueing on the project new-chat composer binds the follow-up to a
+ // thread that does not exist yet.
+ if (disableQueue) {
+ toast.error("Wait for the current response to finish");
+ return;
+ }
+ // queueComposerText clears the draft from its onStarted callback, so a
+ // queue that never starts leaves the text recoverable.
+ if (canQueueCurrentPrompt) {
+ queueComposerText(true);
+ return;
+ }
+ // A long paste lives in an attachment, so queueing the text alone
+ // queues nothing when that is all there is.
+ if (canQueuePastedTextPrompt && queuePastedTextPrompt(true)) {
+ return;
+ }
+ // Nothing queueable while a run is live: keep it and say why. Sending
+ // would push the attachment into the running thread.
+ if (overlay || hasAttachments || hasPendingAudio) {
+ toast.error("Wait for the current response to finish", {
+ description:
+ "Only text prompts can be queued while a response is running or the prompt queue is active.",
+ });
+ }
+ return;
+ }
+ // Nothing running: the chord still queues up front, as it does live.
+ if (forceQueue && !disableQueue) {
if (canQueueCurrentPrompt) {
- queueComposerText(waitForCurrentRun);
+ queueComposerText(false);
return;
}
- if (canQueuePastedTextPrompt && queuePastedTextPrompt(waitForCurrentRun)) {
+ if (canQueuePastedTextPrompt && queuePastedTextPrompt(false)) {
return;
}
- // Nothing queueable: send, as this path did before it carried intent.
}
+ clearStoredDraft();
sendReservedComposer();
}
}, [
@@ -4221,6 +4260,12 @@ const Composer: FC<{
queueComposerText,
queuePastedTextPrompt,
sendReservedComposer,
+ preStreamThreadIds,
+ disableQueue,
+ isResearchActive,
+ overlay,
+ hasAttachments,
+ hasPendingAudio,
]);
// Drop any queued send + toast on unmount (e.g. thread switch).
diff --git a/tests/studio/playwright_chat_ui.py b/tests/studio/playwright_chat_ui.py
index be3f30db5bc..787282ad6c6 100644
--- a/tests/studio/playwright_chat_ui.py
+++ b/tests/studio/playwright_chat_ui.py
@@ -26,7 +26,7 @@ from _playwright_robust import ( # noqa: E402
install_wall_clock_watchdog,
is_benign_console_error,
is_benign_page_error,
- recover_or_replace_page,
+ recover_or_replace_page as _robust_recover_or_replace_page,
robust_evaluate,
wait_for_health,
click_forced,
@@ -65,6 +65,12 @@ PERMISSION_ONLY = os.environ.get("STUDIO_UI_PERMISSION_ONLY", "0") == "1"
PLAYWRIGHT_BROWSER = os.environ.get("STUDIO_PLAYWRIGHT_BROWSER", "chromium").lower()
PLAYWRIGHT_CHANNEL = os.environ.get("STUDIO_PLAYWRIGHT_CHANNEL") or None
+# Render like the 4 vCPU boxes users and Kaggle sessions actually run on. The
+# rapid-submit step passes unthrottled here and fails at 4x and 8x, which is how
+# the parked-send bug was finally reproduced off Kaggle. Off unless set, and
+# Chromium only, since it is delivered over CDP.
+CPU_THROTTLE = float(os.environ.get("STUDIO_UI_CPU_THROTTLE", "0") or 0)
+
# Per-fetch budget; /api/inference/load is the slowest (cold-cache GGUF load).
FETCH_TIMEOUT_MS = int(os.environ.get("STUDIO_UI_FETCH_TIMEOUT_MS", "30000"))
LOAD_FETCH_TIMEOUT_MS = int(os.environ.get("STUDIO_UI_LOAD_TIMEOUT_MS", "180000"))
@@ -84,6 +90,44 @@ def fail(m):
raise AssertionError(f"[ui] FAIL: {m}")
+def apply_cpu_throttle(ctx, page):
+ """Throttle this page, if the option is set. No-op otherwise."""
+ if CPU_THROTTLE <= 1:
+ return page
+ ctx.new_cdp_session(page).send("Emulation.setCPUThrottlingRate", {"rate": CPU_THROTTLE})
+ info(f"CPU throttled {CPU_THROTTLE}x")
+ return page
+
+
+def new_throttled_page(ctx):
+ """Every page this driver opens, with the settings common to all of them.
+
+ The throttle is scoped to the page TARGET, so a page opened directly runs
+ at full speed and the steps after it pass under exactly the conditions the
+ throttle exists to reproduce. The 60s default rides along for the reason it
+ always did: macos-14 renders, webfonts and lazy routes crowd 30s.
+ """
+ page = ctx.new_page()
+ page.set_default_timeout(60_000)
+ apply_cpu_throttle(ctx, page)
+ return page
+
+
+def recover_or_replace_page(page, ctx, **kwargs):
+ """The shared recovery, with the throttle carried onto a replacement page.
+
+ `Emulation.setCPUThrottlingRate` is scoped to the PAGE TARGET, so a page
+ from `ctx.new_page()` runs at full speed however the option was set, and
+ every remaining step would pass under exactly the conditions the throttle
+ exists to reproduce. Wrapping the import rather than each call site means a
+ fourth recovery point cannot forget it.
+ """
+ replacement = _robust_recover_or_replace_page(page, ctx, **kwargs)
+ if replacement is not page:
+ apply_cpu_throttle(ctx, replacement)
+ return replacement
+
+
def expected_default_model():
override = os.environ.get("EXPECTED_DEFAULT_MODEL")
if override:
@@ -660,6 +704,13 @@ with sync_playwright() as p:
launch_kwargs["channel"] = PLAYWRIGHT_CHANNEL
elif PLAYWRIGHT_CHANNEL:
fail("STUDIO_PLAYWRIGHT_CHANNEL requires chromium")
+ if CPU_THROTTLE > 1 and PLAYWRIGHT_BROWSER != "chromium":
+ # Refused here rather than at the call: `new_cdp_session` is Chromium
+ # only, so firefox/webkit would abort mid-run with a Playwright error
+ # about CDP that says nothing about the option that caused it. Both are
+ # supported browsers, so this pairing is reachable from the documented
+ # environment alone.
+ fail(f"STUDIO_UI_CPU_THROTTLE requires chromium, not {PLAYWRIGHT_BROWSER}")
browser = browser_type.launch(**launch_kwargs)
ctx = browser.new_context(
viewport = {"width": 1280, "height": 900},
@@ -680,10 +731,7 @@ with sync_playwright() as p:
else None
),
)
- page = ctx.new_page()
- # 60s default (was 30s): the macos-14 runners are slow enough that
- # renders/webfonts/lazy routes routinely crowd 30s.
- page.set_default_timeout(60_000)
+ page = new_throttled_page(ctx)
page_errors = []
page.on("pageerror", lambda e: page_errors.append(str(e)))
console_errors: list[str] = []
@@ -2194,8 +2242,7 @@ with sync_playwright() as p:
)
except Exception as exc:
info(f"WARN clearing stale auth tokens failed: {exc!r}")
- _fresh_page = ctx.new_page()
- _fresh_page.set_default_timeout(60_000)
+ _fresh_page = new_throttled_page(ctx)
_fresh_page.on("pageerror", lambda e: page_errors.append(str(e)))
_fresh_page.on("console", _on_console)
try:
diff --git a/tests/studio/test_chat_ui_driver_cpu_throttle.py b/tests/studio/test_chat_ui_driver_cpu_throttle.py
new file mode 100644
index 00000000000..3c85a655e2f
--- /dev/null
+++ b/tests/studio/test_chat_ui_driver_cpu_throttle.py
@@ -0,0 +1,142 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""`STUDIO_UI_CPU_THROTTLE` is delivered over CDP, so it is Chromium only.
+
+firefox and webkit are documented as supported, so the pairing is reachable
+from the environment alone and `new_cdp_session` raises a CDP error that never
+names the option. The driver refuses it before launch, as it already does for
+`STUDIO_PLAYWRIGHT_CHANNEL`.
+
+Comments are stripped before every match: this file's own prose says
+"chromium", and a guard its neighbouring comment satisfies passes while the
+code is gone.
+"""
+
+import ast
+import re
+from pathlib import Path
+
+
+DRIVER_PATH = Path(__file__).resolve().parent / "playwright_chat_ui.py"
+DRIVER = DRIVER_PATH.read_text(encoding = "utf-8")
+
+
+def _code_only(source: str) -> str:
+ """The source with comments and string literals removed."""
+ stripped = re.sub(r"(?m)#[^\n]*", "", source)
+ return re.sub(r'("""|\'\'\')(?:.|\n)*?\1', "", stripped)
+
+
+CODE = _code_only(DRIVER)
+
+
+def test_the_throttle_is_read_once_into_a_module_constant():
+ """Read at the launch site instead and the refusal cannot see it."""
+ assert "STUDIO_UI_CPU_THROTTLE" in CODE
+ assert re.search(r"(?m)^CPU_THROTTLE\s*=", CODE), (
+ "the throttle is no longer a module constant, so the pre-launch "
+ "refusal below cannot be reading the same value the driver applies"
+ )
+
+
+def test_a_non_chromium_browser_refuses_the_throttle():
+ refusal = re.search(
+ r"if\s+CPU_THROTTLE\s*>\s*1\s+and\s+PLAYWRIGHT_BROWSER\s*!=\s*"
+ r"[\"']chromium[\"']\s*:(?P<body>(?:\n[ \t]+.*)+)",
+ CODE,
+ )
+ assert refusal, (
+ "nothing refuses STUDIO_UI_CPU_THROTTLE on firefox/webkit, so the run "
+ "aborts inside new_cdp_session with a message about CDP"
+ )
+ assert "fail(" in refusal.group("body"), (
+ "the combination is detected and not refused; a warning would let the "
+ "run continue unthrottled and report a pass that proves nothing"
+ )
+
+
+def test_the_refusal_precedes_the_first_page():
+ """Order is the point: after a page exists it is not a refusal.
+
+ Read against the launch function, not the file: the CDP call lives in a
+ helper near the top, so file order says nothing about what runs first.
+ """
+ launch = CODE[CODE.index("browser_type = getattr(p, PLAYWRIGHT_BROWSER)") :]
+ guard = launch.index("CPU_THROTTLE > 1 and PLAYWRIGHT_BROWSER")
+ first_page = launch.index("new_throttled_page(ctx)")
+ assert guard < first_page, (
+ "a page is created before the unsupported-browser check, so firefox "
+ "and webkit reach the CDP call and raise"
+ )
+
+
+def test_every_page_the_driver_opens_goes_through_one_factory():
+ """A page opened directly is a page that is never throttled.
+
+ The relogin path's own fresh page ran at full speed, so the steps after it
+ passed under a driver reporting itself throttled -- a false pass in
+ precisely the slow case the option exists to create.
+ """
+ factory = re.search(
+ r"def new_throttled_page\([^)]*\):(?P<body>(?:\n(?:[ \t].*)?)+?)(?=\ndef |\nclass |\Z)",
+ CODE,
+ )
+ assert factory, "no new_throttled_page factory"
+ body = factory.group("body")
+ assert "ctx.new_page()" in body and "apply_cpu_throttle" in body
+ assert "set_default_timeout(60_000)" in body, (
+ "the factory drops the 60s default the direct call sites carried, so "
+ "the macos-14 runners go back to timing out on ordinary renders"
+ )
+ outside = CODE.replace(body, "", 1)
+ assert "new_page()" not in outside, (
+ "a page is still opened outside new_throttled_page, so it runs "
+ "unthrottled for every step that follows it"
+ )
+
+
+def test_the_cdp_call_has_exactly_one_owner():
+ assert CODE.count("new_cdp_session") == 1, (
+ "a second CDP session would sit outside apply_cpu_throttle, so the "
+ "refusal and the recovery path would both miss it"
+ )
+ owner = re.search(
+ r"def apply_cpu_throttle\([^)]*\):(?P<body>(?:\n(?:[ \t].*)?)+?)(?=\ndef |\nclass |\Z)",
+ CODE,
+ )
+ assert owner and "new_cdp_session" in owner.group(
+ "body"
+ ), "the throttle is applied somewhere other than apply_cpu_throttle"
+
+
+def test_a_replacement_page_is_throttled_again():
+ """A page replaced after a renderer death must be throttled again."""
+ assert "recover_or_replace_page as _robust_recover_or_replace_page" in CODE, (
+ "the shared helper is imported under its own name, so the call sites "
+ "bypass the wrapper that re-throttles a replacement page"
+ )
+ wrapper = re.search(
+ r"def recover_or_replace_page\([^)]*\):(?P<body>(?:\n(?:[ \t].*)?)+?)"
+ r"(?=\ndef |\nclass |\Z)",
+ CODE,
+ )
+ assert wrapper, "no local recover_or_replace_page wrapper"
+ body = wrapper.group("body")
+ assert "_robust_recover_or_replace_page" in body
+ assert "apply_cpu_throttle" in body, (
+ "the wrapper does not re-apply the throttle, so a replaced page runs "
+ "unthrottled for the rest of the driver"
+ )
+ assert "is not page" in body, (
+ "the throttle is re-applied unconditionally; only a REPLACEMENT page "
+ "needs it, and a fresh CDP session per recovery is not free"
+ )
+ assert "_robust_recover_or_replace_page(" not in CODE.replace(body, "", 1).replace(
+ "recover_or_replace_page as _robust_recover_or_replace_page", "", 1
+ ), "a call site reaches the shared helper directly, skipping the wrapper"
+
+
+def test_the_driver_still_parses():
+ """The regexes above are read against real source, not a fixture."""
+ ast.parse(DRIVER)
diff --git a/tests/studio/test_multi_chat_prompt_queue_contract.py b/tests/studio/test_multi_chat_prompt_queue_contract.py
index 5d92a3b5112..a73e9c64686 100644
--- a/tests/studio/test_multi_chat_prompt_queue_contract.py
+++ b/tests/studio/test_multi_chat_prompt_queue_contract.py
@@ -297,6 +297,101 @@ def test_composer_only_queues_behind_the_current_chat():
), "queue failure notification must not depend on a direct-send reservation"
+def test_a_send_parked_on_the_settings_gate_queues_if_a_run_started_meanwhile():
+ """The park is not the bug; releasing it into a running thread is.
+
+ A submit that lands while a new chat's settings are pairing is parked with
+ a "Loading this chat's settings" toast. When the gate closes, the release
+ used to call `sendReservedComposer()` for anything that had not asked for
+ the queue with Cmd/Ctrl+Enter -- even when a run had started in the
+ meantime. The runtime refuses a send on a running thread, so the message
+ was neither queued nor sent, and the wait toast had already been dismissed
+ a few lines above: nothing on screen said the prompt was gone.
+
+ Measured, not reasoned about. With the browser under an 8x CDP CPU
+ throttle, so a build box renders like the 4 vCPU machines this shows up
+ on, the app's own trace reads:
+
+ +786 ms submit -> settingsPending (parked)
+ +10480 release text="..." running=true (gate closed 236 ms later)
+ +10482 release:sendReservedComposer
+
+ and 90 seconds later: one user bubble, one /v1/chat/completions request,
+ the prompt still sitting in the composer, no queue chip, no toast.
+
+ The `forceQueue` branch already re-read `isRunning` for exactly this
+ reason, in a comment that describes the bug in the branch beside it. The
+ rule below is that the run check governs BOTH.
+ """
+ release = _between(
+ THREAD,
+ "// Fire the parked send once indexing clears",
+ "// Drop any queued send + toast on unmount",
+ )
+ code = re.sub(r"//[^\n]*", "", release)
+ assert "const waitForCurrentRun =" in code
+ assert "aui.thread().getState().isRunning" in code, (
+ "the release no longer asks whether a run started while the send was "
+ "parked, so a parked prompt is sent into a streaming thread again"
+ )
+ # A pre-stream reservation is a run that has been accepted and has not
+ # reached isRunning yet. handleSubmit treats it as running; so must this,
+ # or the same prompt is lost in a narrower window.
+ assert "hasPreStreamRunReservation(preStreamThreadIds)" in code
+
+ # The gate on the queue branches, which is the fix itself: an active run
+ # governs the release, not the Cmd/Ctrl+Enter intent.
+ running = code.index("if (waitForCurrentRun) {")
+ branch = code[running : code.index("if (forceQueue && !disableQueue) {")]
+ assert "queueComposerText(true);" in branch, (
+ "the release no longer queues behind the run that started while the "
+ "send was parked, so the prompt goes back to being dropped silently"
+ )
+ # Every refusal handleSubmit makes, made here too. A parked send is the
+ # same submit arriving late, so a branch it does not mirror is a state the
+ # UI forbids being reachable through the settings gate.
+ for rule, why in (
+ (
+ "if (disableQueue) {",
+ "the project new-chat composer can queue again, binding the "
+ "follow-up to a thread that does not exist yet",
+ ),
+ (
+ "Only text prompts can be queued",
+ "a parked send carrying an attachment falls through to a direct "
+ "send while a run is live, which is the collision this branch "
+ "exists to avoid",
+ ),
+ ):
+ assert rule in branch, f"{why} (missing: {rule!r})"
+ assert "sendReservedComposer" not in branch, (
+ "the running branch still reaches a direct send; nothing that cannot "
+ "be queued may be dispatched into a streaming thread"
+ )
+
+ # Research disables input outright -- handleSubmit returns before anything
+ # else and the UI shows Stop research instead of Send.
+ research = code.index("if (isResearchActive) {")
+ assert research < running, (
+ "the research refusal is not ahead of the queue path, so a prompt "
+ "parked before research began starts a turn while it is still active"
+ )
+ assert "isResearchActive," in code, "isResearchActive is missing from the deps"
+ assert "disableQueue," in code, "disableQueue is missing from the effect deps"
+
+ # The draft outlives every path that does not complete. queueComposerText
+ # clears it from its own onStarted callback, so clearing it up front loses
+ # the text whenever the queue does not start -- a null target, an
+ # invalidated start -- and after the composer is replaced it is gone.
+ assert code.index("clearStoredDraft();") > code.index("if (forceQueue && !disableQueue) {"), (
+ "the stored draft is cleared before the queue and refusal paths, so a "
+ "prompt that is neither queued nor sent cannot be recovered"
+ )
+ # Unchanged: with nothing running the chord still queues, and an ordinary
+ # send still sends. A fix that stopped sending would strand that case.
+ assert "sendReservedComposer();" in code
+
+
def test_queued_settings_are_thread_scoped_without_cross_chat_fallback():
target = _between(
THREAD,