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
Thread browser harnesses: reach Delete through the More menu, and attack Copy in the dismissal probe (#12827)
Daniel Hanb21a25e77a59
diff --git a/.github/workflows/studio-frontend-ci.yml b/.github/workflows/studio-frontend-ci.ymlindex b6ff2f3e8ad..254d736b1e9 100644--- a/.github/workflows/studio-frontend-ci.yml+++ b/.github/workflows/studio-frontend-ci.yml@@ -508,7 +508,7 @@ jobs:PW_ART_DIR: logs/playwright_heavy_threadrun: python3 tests/studio/playwright_heavy_thread.py- # A failure means dismissal triggered an unconfirmed delete.+ # A failure means the click that dismissed a menu also reached the control under it.- name: Browser check for non-modal menu dismissalworking-directory: ${{ github.workspace }}run: python3 tests/studio/probe_dismiss_guard.py --label ci --engine chromiumdiff --git a/tests/studio/playwright_heavy_thread.py b/tests/studio/playwright_heavy_thread.pyindex bcdd31d8ec1..aefd4024711 100644--- a/tests/studio/playwright_heavy_thread.py+++ b/tests/studio/playwright_heavy_thread.py@@ -600,11 +600,45 @@ async (timeoutMs) => {}"""+# Delete is the last item of the reply's More menu (#12735 took it off the action bar). The menu is+# opened and the item found BEFORE the clock starts, so the window still holds only what selecting+# Delete costs: Radix closing the menu, and the message leaving the thread. Opening the menu is the+# `menu` action's number already. The trigger opens on `pointerdown`, as MENU_JS explains; an item+# selects on `click`.DELETE_JS = """async (timeoutMs) => {const api = window.__heavyThread;- const button = api.actionButton("Delete message");- if (!button) return null;+ const trigger = api.actionButton("More");+ if (!trigger) return null;+ const content = () => document.querySelector(".aui-action-bar-more-content");+ // The portal mounting is a change to body's children, so the lookup runs on that mutation and+ // not once per frame while the menu is still on its way.+ let menu = content();+ const watcher = new MutationObserver(() => { menu = content(); });+ watcher.observe(document.body, { childList: true, subtree: false });+ const pointer = {+ bubbles: true, cancelable: true, composed: true,+ button: 0, pointerId: 1, pointerType: "mouse", isPrimary: true,+ };+ trigger.dispatchEvent(new PointerEvent("pointerdown", { ...pointer, buttons: 1 }));+ trigger.dispatchEvent(new PointerEvent("pointerup", { ...pointer, buttons: 0 }));+ const opening = performance.now();+ while (!menu && performance.now() - opening < timeoutMs) await window.__nextPaint();+ watcher.disconnect();+ const item = menu+ ? Array.from(menu.querySelectorAll(".aui-action-bar-more-item")).find(+ (candidate) => (candidate.textContent ?? "").trim() === "Delete",+ )+ : null;+ if (!item) {+ // A menu this action opened and could not use would sit over the next action.+ if (menu) {+ document.dispatchEvent(+ new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true }),+ );+ }+ return null;+ }// The last assistant message. That is the cheapest delete on the React side -- one subtree// unmounts -- so this column under-measures reconciliation, though the export/rebuild/import// half is O(messages) wherever the target sits.@@ -612,7 +646,7 @@ async (timeoutMs) => {const before = api.messageCount();window.__hv.begin();const started = performance.now();- button.click();+ item.click();let ms = null;// isConnected on the captured node is O(1). Re-counting [data-role] every frame would put an// O(messages) query inside the window being timed, growing like the signal.diff --git a/tests/studio/playwright_thread_weight.py b/tests/studio/playwright_thread_weight.pyindex b19e781d415..0ee9d914b14 100644--- a/tests/studio/playwright_thread_weight.py+++ b/tests/studio/playwright_thread_weight.py@@ -304,18 +304,47 @@ async (timeoutMs) => {}"""+# Delete is the last item of the reply's More menu (#12735 took it off the action bar). The menu is+# opened and the item found before the clock starts, so the number is still what selecting Delete+# costs. The trigger opens on `pointerdown`; an item selects on `click`.DELETE_JS = """async (timeoutMs) => {const api = window.__threadWeight;- const button = api.actionButton("Delete message");- if (!button) return null;+ const trigger = api.actionButton("More");+ if (!trigger) return null;+ const content = () => document.querySelector(".aui-action-bar-more-content");+ let menu = content();+ const watcher = new MutationObserver(() => { menu = content(); });+ watcher.observe(document.body, { childList: true, subtree: false });+ const pointer = {+ bubbles: true, cancelable: true, composed: true,+ button: 0, pointerId: 1, pointerType: "mouse", isPrimary: true,+ };+ trigger.dispatchEvent(new PointerEvent("pointerdown", { ...pointer, buttons: 1 }));+ trigger.dispatchEvent(new PointerEvent("pointerup", { ...pointer, buttons: 0 }));+ const opening = performance.now();+ while (!menu && performance.now() - opening < timeoutMs) await window.__nextPaint();+ watcher.disconnect();+ const item = menu+ ? Array.from(menu.querySelectorAll(".aui-action-bar-more-item")).find(+ (candidate) => (candidate.textContent ?? "").trim() === "Delete",+ )+ : null;+ if (!item) {+ if (menu) {+ document.dispatchEvent(+ new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true }),+ );+ }+ return null;+ }// The last assistant message. That is the cheapest delete on the React side -- one subtree// unmounts -- so this column under-measures reconciliation, though the export/rebuild/import// half is O(messages) wherever the target sits.const target = api.lastAssistantMessage();const before = api.messageCount();const started = performance.now();- button.click();+ item.click();// isConnected on the captured node is O(1). Re-counting [data-role] every frame would put an// O(messages) query inside the window being timed, growing like the signal.while (performance.now() - started < timeoutMs) {diff --git a/tests/studio/probe_dismiss_guard.py b/tests/studio/probe_dismiss_guard.pyindex d3e73df131e..fbad6cac2f2 100644--- a/tests/studio/probe_dismiss_guard.py+++ b/tests/studio/probe_dismiss_guard.py@@ -34,7 +34,7 @@ The guard must swallow too little nowhere:release does not clear, so the click still fires; Blink and WebKit gate it on theshared `:active` state, which the release does clear, so no click is everdispatched and the case cannot fail there however broken the guard is.- touch_hold_ a finger presses and HOLDS the unconfirmed "Delete message" button, a MOUSE+ touch_hold_ a finger presses and HOLDS the reply's Copy button, a MOUSEsecond_ press lands inside the still-open menu, then the finger lifts. Radix defers apointer touch dismissal to the resulting click, so the menu is still there for a secondpointer to land in, and every early return in the guard's `pointerdown` handler@@ -50,7 +50,7 @@ The guard must swallow too little nowhere:for the swallow-too-much direction.dismiss_then_ click the button to dismiss, then press Space. The swallowed press must movespace focus off the dangerous control and back to the menu trigger. Space then reopens- the menu instead of activating Delete. Discriminates on chromium, firefox and+ the menu instead of activating Copy. Discriminates on chromium, firefox andwebkit. The modal shape cannot reach it, because with `pointer-events: none` onthe body the press lands on `HTML` and focus never moves off `BODY`.@@ -139,16 +139,36 @@ async () => {}"""+# The control under attack is the reply's Copy button: always on the action bar, and harmless when+# a broken guard lets a click through. (It was Delete until #12735 moved Delete into the More menu,+# where a dismissal cannot reach it.) Whether a click reached it is counted on `window`, bubble+# phase: the guard swallows on `document` in the capture phase with stopPropagation, so a swallowed+# click never gets there and one that slipped past always does, however React re-renders the button.FACTS_JS = """() => {const api = window.__heavyThread;- const del = api.actionButton("Delete message");- const r = del ? del.getBoundingClientRect() : null;+ const target = api.actionButton("Copy");+ if (!window.__dismissProbeTarget) {+ window.__dismissProbeTarget = { clicks: 0 };+ window.addEventListener("click", (event) => {+ const copy = window.__heavyThread.actionButton("Copy");+ if (copy && event.target instanceof Node && copy.contains(event.target)) {+ window.__dismissProbeTarget.clicks += 1;+ }+ });+ }+ const r = target ? target.getBoundingClientRect() : null;+ const x = r ? r.x + r.width / 2 : 0;+ const y = r ? r.y + r.height / 2 : 0;+ const hit = r ? document.elementFromPoint(x, y) : null;return {menuOpen: Boolean(document.querySelector(".aui-action-bar-more-content")),bodyPointerEvents: getComputedStyle(document.body).pointerEvents,- deleteRect: r ? { x: r.x + r.width / 2, y: r.y + r.height / 2 } : null,- assistantMessages: document.querySelectorAll('[data-role="assistant"]').length,+ targetRect: r ? { x, y } : null,+ // Nothing else may be painted over the spot the attack presses, the open menu included, or+ // the case would be testing a click into whatever covers it.+ targetUncovered: Boolean(hit && target && target.contains(hit)),+ targetClicks: window.__dismissProbeTarget.clicks,};}"""@@ -290,16 +310,37 @@ async def one_case(engine: str = "chromium",context = None,) -> dict:- """Open the menu, attack the Delete button one way, report whether it fired."""+ """Open the menu, attack the Copy button one way, report whether the click reached it."""+ await hover_last_assistant(page)+ # Positive control: a direct click with no menu open must be counted, or a zero below would+ # mean only that the counter cannot see clicks.+ control = await page.evaluate(FACTS_JS)+ if not control["targetRect"]:+ return {"case": case, "error": "no Copy button"}+ await page.mouse.click(control["targetRect"]["x"], control["targetRect"]["y"])+ await page.wait_for_timeout(200)+ counted = (await page.evaluate(FACTS_JS))["targetClicks"] - control["targetClicks"]+ if counted != 1:+ return {+ "case": case,+ "error": f"a direct click on Copy was counted {counted} times, not once",+ }+ # The control click focused Copy; the focus cases below must start where they always did.+ await page.evaluate("() => document.activeElement && document.activeElement.blur()")await hover_last_assistant(page)opened = await page.evaluate(OPEN_MENU_JS)if not opened.get("ok"):return {"case": case, "error": "menu never opened"}before = await page.evaluate(FACTS_JS)before_space = None- rect = before["deleteRect"]+ rect = before["targetRect"]if not rect:- return {"case": case, "error": "no Delete button"}+ return {"case": case, "error": "no Copy button"}+ if not before["targetUncovered"]:+ return {+ "case": case,+ "error": "the open menu covers the Copy button, so a press there is not a dismissal",+ }x, y = rect["x"], rect["y"]if case == "quick":await page.mouse.move(x, y)@@ -357,7 +398,7 @@ async def one_case(before_space = await page.evaluate(FOCUS_FACTS_JS)await page.keyboard.press("Space")elif case == "dismiss_then_space":- # A swallowed dismissal must not leave Delete focused for Space activation.+ # A swallowed dismissal must not leave Copy focused for Space activation.await page.mouse.click(x, y)await page.wait_for_timeout(300)before_space = await page.evaluate(FOCUS_FACTS_JS)@@ -399,7 +440,7 @@ async def one_case("composerText": typed[-8:],"menuClosed": not after["menuOpen"],"lostComposerFocus": not typed.endswith("zz"),- "deleted": after["assistantMessages"] < before["assistantMessages"],+ "fired": after["targetClicks"] > before["targetClicks"],}elif case == "touch":await page.touchscreen.tap(x, y)@@ -454,9 +495,9 @@ async def one_case("case": case,"concurrentPointers": state["downs"],"menuOpenUnderSecondPointer": held["menuOpen"],- "assistantMessagesBefore": before["assistantMessages"],- "assistantMessagesAfter": after["assistantMessages"],- "deleted": after["assistantMessages"] < before["assistantMessages"],+ "targetClicksBefore": before["targetClicks"],+ "targetClicksAfter": after["targetClicks"],+ "fired": after["targetClicks"] > before["targetClicks"],"menuClosed": not after["menuOpen"],"clicksSeen": state["clicks"],"clicksDelivered": state["delivered"],@@ -487,7 +528,7 @@ async def one_case("case": case,"tappedTag": spot.get("tag"),"menuClosed": not after["menuOpen"],- "deleted": after["assistantMessages"] < before["assistantMessages"],+ "fired": after["targetClicks"] > before["targetClicks"],}elif case == "touch_trigger":# Tapping the trigger must still close the menu.@@ -504,7 +545,7 @@ async def one_case(return {"case": case,"menuClosed": not after["menuOpen"],- "deleted": after["assistantMessages"] < before["assistantMessages"],+ "fired": after["targetClicks"] > before["targetClicks"],}elif case in ("rightclick_then_click", "dragoff_then_click"):spot = await page.evaluate(WATCH_NEUTRAL_JS, False)@@ -578,9 +619,9 @@ async def one_case(result = {"case": case,"bodyPointerEvents": before["bodyPointerEvents"],- "assistantMessagesBefore": before["assistantMessages"],- "assistantMessagesAfter": after["assistantMessages"],- "deleted": after["assistantMessages"] < before["assistantMessages"],+ "targetClicksBefore": before["targetClicks"],+ "targetClicksAfter": after["targetClicks"],+ "fired": after["targetClicks"] > before["targetClicks"],"menuClosed": not after["menuOpen"],}if before_space is not None:@@ -657,7 +698,7 @@ def main() -> int:skipped = [(c["case"], c["skipped"]) for c in result["cases"] if c.get("skipped")]for case, why in skipped:print(f"[probe] SKIPPED {case}: {why}", flush = True)- deleted = [c["case"] for c in result["cases"] if c.get("deleted")]+ fired = [c["case"] for c in result["cases"] if c.get("fired")]stuck = [c["case"]for c in result["cases"]@@ -685,9 +726,9 @@ def main() -> int:if over:print(f"[probe] FAIL: the guard swallowed a click it should not have: {over}", flush = True)broken = broken + over- if deleted:+ if fired:print(- f"[probe] FAIL: dismissing the menu also deleted a message via {deleted}",+ f"[probe] FAIL: dismissing the menu also clicked the control underneath via {fired}",flush = True,)if broken:@@ -700,7 +741,7 @@ def main() -> int:f"and reopen the menu: {unsafe_space}",flush = True,)- if deleted or broken or stuck or unsafe_space:+ if fired or broken or stuck or unsafe_space:return 1print("[probe] PASS: no dismissal variant reached the control underneath", flush = True)return 0diff --git a/tests/studio/test_thread_harness_controls_exist.py b/tests/studio/test_thread_harness_controls_exist.pynew file mode 100644index 00000000000..20d66ed74a2--- /dev/null+++ b/tests/studio/test_thread_harness_controls_exist.py@@ -0,0 +1,108 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Every action-bar control the thread browser harnesses ask for is still rendered there.++#12735 took Delete off the assistant action bar and made it the last item of the More menu.+playwright_heavy_thread.py kept asking for a "Delete message" button, so its delete action could+not run, and probe_dismiss_guard.py kept attacking that button, so every one of its cases would+have errored. Both sit behind earlier steps of the same CI job, which hid the breakage until those+steps went green. This reads the labels the harnesses ask for and requires each to be rendered by+the assistant action bar in thread.tsx, so the next move of a control fails here, with its name.+"""++from __future__ import annotations++import re+from pathlib import Path++REPO = Path(__file__).resolve().parents[2]+THREAD_TSX = REPO / "studio" / "frontend" / "src" / "components" / "assistant-ui" / "thread.tsx"+HARNESSES = (+ "tests/studio/playwright_heavy_thread.py",+ "tests/studio/playwright_thread_weight.py",+ "tests/studio/probe_dismiss_guard.py",+)+++def _component_body(tsx: str, name: str) -> str | None:+ """The source of a component defined in thread.tsx, `const X: FC = ...` or `function X(`."""+ match = re.search(rf"^(?:const {name}\b[^\n]*=>\s*\{{|function {name}\()", tsx, re.M)+ if not match:+ return None+ end = tsx.find("\n}", match.end())+ return tsx[match.start() : end if end != -1 else len(tsx)]+++def _assistant_bar_source(tsx: str) -> str:+ """AssistantActionBar and every thread.tsx component it renders, transitively.++ The harnesses act on the last ASSISTANT message, so a control only counts if the assistant+ bar renders it: a whole-file search would still find a label in the user message's bar.+ """+ seen: dict[str, str] = {}+ queue = ["AssistantActionBar"]+ while queue:+ name = queue.pop()+ if name in seen:+ continue+ body = _component_body(tsx, name)+ if body is None:+ continue+ seen[name] = body+ queue.extend(re.findall(r"<([A-Z][A-Za-z0-9]*)\b(?!\.)", body))+ assert "AssistantActionBar" in seen, "could not find AssistantActionBar in thread.tsx"+ return "\n".join(seen.values())+++def _asked_for() -> tuple[dict[str, set[str]], dict[str, set[str]]]:+ """Bar buttons (`actionButton("X")`) and More-menu items (`.trim() === "X"`) per harness."""+ buttons: dict[str, set[str]] = {}+ items: dict[str, set[str]] = {}+ for rel in HARNESSES:+ text = (REPO / rel).read_text(encoding = "utf-8")+ buttons[rel] = set(re.findall(r"\bactionButton\(\s*[\"']([^\"']+)[\"']\s*\)", text))+ items[rel] = set(re.findall(r"\.trim\(\)\s*===\s*\"([^\"]+)\"", text))+ return buttons, items+++def _rendered(tsx: str) -> tuple[set[str], set[str]]:+ bar = _assistant_bar_source(tsx)+ tooltips = set(re.findall(r"tooltip=\"([^\"]+)\"", bar))+ # An item's label is its last line of text before the closing tag. Its attributes can hold+ # arrow functions, so the opening tag cannot be skipped with a `[^>]*` match.+ menu_items = set()+ for body in re.findall(+ r"<ActionBarMorePrimitive\.Item\b([\s\S]*?)</ActionBarMorePrimitive\.Item>", bar+ ):+ lines = [line.strip() for line in body.splitlines() if line.strip()]+ if lines and not lines[-1].startswith(("<", "{", "/")):+ menu_items.add(lines[-1])+ return tooltips, menu_items+++def test_the_scan_reads_the_controls_the_harnesses_use():+ buttons, items = _asked_for()+ assert {"More"} <= buttons["tests/studio/playwright_heavy_thread.py"]+ assert {"More", "Copy"} <= buttons["tests/studio/probe_dismiss_guard.py"]+ assert "Delete" in items["tests/studio/playwright_heavy_thread.py"]+ assert "Delete" in items["tests/studio/playwright_thread_weight.py"]+ tooltips, menu_items = _rendered(THREAD_TSX.read_text(encoding = "utf-8"))+ assert {"Copy", "More"} <= tooltips and "Delete" in menu_items, (+ "parsed fewer controls out of thread.tsx than the assistant bar renders; "+ "the check below would pass on nothing"+ )+++def test_every_control_a_harness_asks_for_is_still_rendered():+ tooltips, menu_items = _rendered(THREAD_TSX.read_text(encoding = "utf-8"))+ buttons, items = _asked_for()+ missing = {+ rel: sorted(buttons[rel] - tooltips) + sorted(items[rel] - menu_items)+ for rel in HARNESSES+ if (buttons[rel] - tooltips) or (items[rel] - menu_items)+ }+ assert not missing, (+ f"these harnesses ask for controls the assistant action bar in thread.tsx no longer "+ f"renders as a tooltip or a More-menu item, so the action would not run: {missing}"+ )