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 menu dismissal deleting a chat message (#9243)
Maheswar Kumar746ad086d80e
diff --git a/.github/workflows/studio-frontend-ci.yml b/.github/workflows/studio-frontend-ci.ymlindex 0020ab64b46..38cadfbfd52 100644--- a/.github/workflows/studio-frontend-ci.yml+++ b/.github/workflows/studio-frontend-ci.yml@@ -22,6 +22,7 @@ on:- 'tests/studio/playwright_chat_autoscroll.py'- 'tests/studio/playwright_research_freeze.py'- 'tests/studio/playwright_heavy_thread.py'+ - 'tests/studio/probe_dismiss_guard.py'- 'tests/studio/playwright_settings_tabs.py'- 'tests/studio/playwright_stream_pacing.py'# Shared lifecycle helpers, and the contract tests that keep verdicts from going unread.@@ -398,6 +399,11 @@ jobs:PW_ART_DIR: logs/playwright_heavy_threadrun: python3 tests/studio/playwright_heavy_thread.py+ # A failure means dismissal triggered an unconfirmed delete.+ - name: Browser check for non-modal menu dismissal+ working-directory: ${{ github.workspace }}+ run: python3 tests/studio/probe_dismiss_guard.py --label ci --engine chromium+# The settings panels are fetched on first view, so only a browser can answer whether# every tab renders and deep-opens land (and abandoned ones do not come back).- name: Browser smoke for the settings tab panels@@ -436,13 +442,12 @@ jobs:uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1with:name: studio-frontend-smoke-artifacts- # Four of the five smokes write logs/playwright-<name>; the settings smoke writes a- # JSON report instead, under its own name, so a bare playwright-* glob uploaded- # everything EXCEPT the report of the smoke that had just failed.+ # Include the settings and dismissal probe reports as well as playwright-* logs.path: |logs/playwright-*logs/settings_tabs_report.jsonlogs/settings_tabs_blocked_report.json+ logs/pw/retention-days: 3if-no-files-found: ignorediff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex 47ef9ffbcf0..9f49fcd1ead 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -227,6 +227,7 @@ import { useVoiceSettingsStore } from "@/features/settings/stores/voice-settingsimport { applyQwenThinkingParams } from "@/features/chat/utils/qwen-params";import { isTauri } from "@/lib/api-base";import { copyToClipboard } from "@/lib/copy-to-clipboard";+import { MenuDismissGuard } from "@/lib/menu-dismiss-guard";import { MicIcon } from "@/lib/mic-icon";import { downloadFile, isDownloadCancelled } from "@/lib/native-files";import { toast } from "@/lib/toast";@@ -7521,6 +7522,8 @@ const AssistantActionBar: FC = () => {onCloseAutoFocus={(e) => e.preventDefault()}className="aui-action-bar-more-content z-50 min-w-32 overflow-hidden rounded-[21px] bg-popover px-[9px] py-2 text-popover-foreground shadow-[0_2px_8px_-2px_rgba(0,0,0,0.16)] dark:shadow-none">+ {/* Prevent an outside dismissal from triggering Delete. */}+ <MenuDismissGuard /><ActionBarMorePrimitive.Itemdisabled={forkDisabled}onSelect={() => void forkMessage()}diff --git a/studio/frontend/src/lib/menu-dismiss-guard.tsx b/studio/frontend/src/lib/menu-dismiss-guard.tsxnew file mode 100644index 00000000000..9282183dee1--- /dev/null+++ b/studio/frontend/src/lib/menu-dismiss-guard.tsx@@ -0,0 +1,15 @@+// 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 type { FC } from "react";++import { useDismissingClickGuard } from "@/lib/menu-dismiss";++/**+ * Marker mounted inside non-modal menu content. The lifetime is mount-scoped: exit-animated+ * content can outlive the open state, so animated menus must add explicit open-state gating.+ */+export const MenuDismissGuard: FC = () => {+ useDismissingClickGuard();+ return null;+};diff --git a/studio/frontend/src/lib/menu-dismiss.ts b/studio/frontend/src/lib/menu-dismiss.tsnew file mode 100644index 00000000000..8d73398b577--- /dev/null+++ b/studio/frontend/src/lib/menu-dismiss.ts@@ -0,0 +1,198 @@+// 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 { useEffect } from "react";++/**+ * Swallow the outside click that dismisses a non-modal menu before it activates an adjacent+ * control. Capture on `document` precedes React and Radix; module state survives content unmount+ * until the owed click, cancel, blur, new gesture, or release grace. Pointer identity, keyboard+ * activation, and focus are tracked, and touch dismissal is re-raised after the swallowed click.+ */++/** Menu and popper surfaces are selections, not dismissals. */+const MENU_SURFACE =+ '[role="menu"],[role="menuitem"],[data-radix-popper-content-wrapper]';++/** Shared state survives menu-content unmount during dismissal. */+let armed = false;+let graceTimer: number | undefined;+/** Touch dismissal is deferred by Radix until the resulting click. */+let armedByTouch = false;+/** Tracks whether the guarded pointer still owes a click. */+let pointerIsDown = false;+/** Only the armed pointer may end the guarded gesture. */+let armedPointerId: number | undefined;+/** Space activates on keyup; Enter activates on keydown. */+let activationKeyIsDown = false;+/** The pointer click was handled; a held Space keyup still owes one click. */+let keyboardOnly = false;+/** Used to undo focus taken by the swallowed press. */+let armedPressTarget: Node | undefined;+let focusBeforePress: Element | null = null;++/** Maximum post-release click delay. */+const CLICK_GRACE_MS = 500;++/** Keys that activate on keyup. */+const isActivationKey = (event: KeyboardEvent): boolean =>+ event.key === " " || event.key === "Spacebar";++const disarmOnKey = (event: KeyboardEvent): void => {+ if (isActivationKey(event)) {+ activationKeyIsDown = true;+ return;+ }+ if (pointerIsDown) return;+ disarmAndReleaseFocus();+};++const disarmOnActivationKeyUp = (event: KeyboardEvent): void => {+ if (!isActivationKey(event)) return;+ activationKeyIsDown = false;+ if (pointerIsDown) return;+ if (graceTimer !== undefined) window.clearTimeout(graceTimer);+ graceTimer = window.setTimeout(disarmAndReleaseFocus, 0);+};++const disarm = (): void => {+ if (graceTimer !== undefined) {+ window.clearTimeout(graceTimer);+ graceTimer = undefined;+ }+ if (!armed) return;+ armed = false;+ pointerIsDown = false;+ armedPointerId = undefined;+ activationKeyIsDown = false;+ keyboardOnly = false;+ armedPressTarget = undefined;+ focusBeforePress = null;+ document.removeEventListener("pointerdown", disarmOnNewPointerDown, true);+ document.removeEventListener("click", swallowClick, true);+ document.removeEventListener("pointerup", startGrace, true);+ document.removeEventListener("pointercancel", disarmOnPointerCancel, true);+ document.removeEventListener("keydown", disarmOnKey, true);+ document.removeEventListener("keyup", disarmOnActivationKeyUp, true);+ window.removeEventListener("blur", disarmAndReleaseFocus);+};++/** The release or cancel of a pointer that is not the one the guard armed for. */+const isAnotherPointer = (event: PointerEvent): boolean =>+ armedPointerId !== undefined && event.pointerId !== armedPointerId;++const disarmOnPointerCancel = (event: PointerEvent): void => {+ if (isAnotherPointer(event)) return;+ disarmAndReleaseFocus();+};++function startGrace(event: PointerEvent): void {+ if (isAnotherPointer(event)) return;+ pointerIsDown = false;+ if (graceTimer !== undefined) window.clearTimeout(graceTimer);+ if (activationKeyIsDown) {+ graceTimer = undefined;+ return;+ }+ graceTimer = window.setTimeout(disarmAndReleaseFocus, CLICK_GRACE_MS);+}++/** Anything the user types into. Dismissing a menu by clicking into it must leave the caret. */+const TEXT_ENTRY = "input,textarea,select";++function releaseFocusTakenByTheGuardedPress(): void {+ // Swallowing the click is not enough: blur only focus acquired by this guarded press, so a+ // later Space key cannot activate the dismissed control.+ const active = document.activeElement;+ if (!(active instanceof HTMLElement)) return;+ if (active === focusBeforePress) return;+ if (active.isContentEditable || active.matches(TEXT_ENTRY)) return;+ if (!(armedPressTarget instanceof Node)) return;+ if (!active.contains(armedPressTarget)) return;+ active.blur();+}++/** Retire a gesture that produced no click without leaving its pressed control focused. */+function disarmAndReleaseFocus(): void {+ releaseFocusTakenByTheGuardedPress();+ disarm();+}++/** A new pointer supersedes an uncompleted gesture. */+function disarmOnNewPointerDown(event: PointerEvent): void {+ if (pointerIsDown && isAnotherPointer(event)) return;+ disarmAndReleaseFocus();+}++function swallowClick(event: Event): void {+ const keyboardGenerated = (event as MouseEvent).detail === 0;+ if (keyboardOnly) {+ disarm();+ if (!keyboardGenerated) return;+ event.stopPropagation();+ event.preventDefault();+ return;+ }+ if (pointerIsDown && keyboardGenerated) {+ event.stopPropagation();+ event.preventDefault();+ return;+ }+ if (activationKeyIsDown && !keyboardGenerated && !armedByTouch) {+ keyboardOnly = true;+ event.stopPropagation();+ event.preventDefault();+ releaseFocusTakenByTheGuardedPress();+ return;+ }+ const touch = armedByTouch;+ event.stopPropagation();+ event.preventDefault();+ releaseFocusTakenByTheGuardedPress();+ disarm();+ if (!touch) return;+ // Radix defers touch dismissal to a document click. Re-raise a non-bubbling synthetic click+ // after removing this guard so Radix can close the menu without re-entering the swallower.+ document.dispatchEvent(new MouseEvent("click", { bubbles: false }));+}++const arm = (touch: boolean, pointerId: number, pressTarget: Node): void => {+ if (armed) return;+ armed = true;+ armedByTouch = touch;+ pointerIsDown = true;+ armedPointerId = pointerId;+ activationKeyIsDown = false;+ keyboardOnly = false;+ armedPressTarget = pressTarget;+ focusBeforePress = document.activeElement;+ document.addEventListener("pointerdown", disarmOnNewPointerDown, true);+ document.addEventListener("click", swallowClick, true);+ document.addEventListener("pointerup", startGrace, true);+ document.addEventListener("pointercancel", disarmOnPointerCancel, true);+ document.addEventListener("keydown", disarmOnKey, true);+ document.addEventListener("keyup", disarmOnActivationKeyUp, true);+ window.addEventListener("blur", disarmAndReleaseFocus);+};++/** Install the watcher for one open menu. */+export function installDismissingClickGuard(): () => void {+ const onPointerDown = (event: PointerEvent): void => {+ if (armed && pointerIsDown && event.pointerId !== armedPointerId) return;+ disarmAndReleaseFocus();+ if (event.button !== 0) return;+ const target = event.target;+ if (!(target instanceof Element)) return;+ if (target.closest(MENU_SURFACE)) return;+ arm(event.pointerType === "touch", event.pointerId, target);+ };+ document.addEventListener("pointerdown", onPointerDown, true);+ return () => {+ document.removeEventListener("pointerdown", onPointerDown, true);+ };+}++/** Mount the guard inside an open non-modal menu's content. */+export function useDismissingClickGuard(): void {+ useEffect(installDismissingClickGuard, []);+}diff --git a/studio/frontend/tests/nonmodal-menu-dismiss-guard.test.ts b/studio/frontend/tests/nonmodal-menu-dismiss-guard.test.tsnew file mode 100644index 00000000000..a37cdd1a8f3--- /dev/null+++ b/studio/frontend/tests/nonmodal-menu-dismiss-guard.test.ts@@ -0,0 +1,163 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Verify that every explicit non-modal menu is guarded or documented as exempt.++import assert from "node:assert/strict";+import { readFileSync, readdirSync, statSync } from "node:fs";+import path from "node:path";+import test from "node:test";+import { fileURLToPath } from "node:url";++const SRC = fileURLToPath(new URL("../src/", import.meta.url));++const TAG_NAME = /^<([A-Za-z0-9_.]+)/;+const GUARD = /<MenuDismissGuard\s*\/>/;++/** Explicit non-modal menus that intentionally remain unguarded. */+const UNGUARDED = new Map<string, string>([+ [+ "components/app-sidebar.tsx <DropdownMenu>",+ "the sidebar's More flyout opens on POINTER ENTER and stays open for 180ms after the pointer " ++ "leaves, so an unconditional swallow eats an ordinary click on the nav row the pointer was " ++ "heading for. A press pins it open too, and that path could take one, but the flyout has " ++ "been non-modal since #6763 rather than since #8992, so it is a defect of its own.",+ ],+]);++/** Find all TSX sources. */+function sources(dir: string, found: string[] = []): string[] {+ for (const entry of readdirSync(dir)) {+ const full = path.join(dir, entry);+ if (statSync(full).isDirectory()) {+ sources(full, found);+ } else if (entry.endsWith(".tsx")) {+ found.push(full);+ }+ }+ return found;+}++/** Find an opening tag with an exact name. */+function openingTagAt(source: string, tag: string, from: number): number {+ let at = source.indexOf(`<${tag}`, from);+ while (at !== -1) {+ const next = source[at + tag.length + 1] ?? "";+ if (next === "" || !/[A-Za-z0-9_.]/.test(next)) return at;+ at = source.indexOf(`<${tag}`, at + 1);+ }+ return -1;+}++/** Return the element carrying `modal={false}`. */+function element(source: string, at: number): { tag: string; body: string } {+ const open = source.lastIndexOf("<", at);+ if (open === -1) {+ throw new Error("modal={false} outside any element");+ }+ const tag = TAG_NAME.exec(source.slice(open))?.[1];+ if (!tag) {+ throw new Error("no tag name at the element carrying modal={false}");+ }+ let depth = 0;+ let i = open;+ while (i < source.length) {+ const nextOpen = openingTagAt(source, tag, i + 1);+ const nextClose = source.indexOf(`</${tag}>`, i + 1);+ if (nextClose === -1) {+ break;+ }+ if (nextOpen !== -1 && nextOpen < nextClose) {+ depth++;+ i = nextOpen;+ continue;+ }+ if (depth === 0) {+ return { tag, body: source.slice(open, nextClose) };+ }+ depth--;+ i = nextClose;+ }+ throw new Error(`unbalanced <${tag}> around the menu at offset ${at}`);+}++/** Normalize separators for stable exemption keys. */+const relativeId = (file: string): string =>+ path.relative(SRC, file).split(path.sep).join("/");++/** Collect each explicit non-modal menu and its body. */+function nonModalMenus(): { id: string; body: string }[] {+ const menus: { id: string; body: string }[] = [];+ for (const file of sources(SRC)) {+ const source = readFileSync(file, "utf8");+ let at = source.indexOf("modal={false}");+ while (at !== -1) {+ const { tag, body } = element(source, at);+ menus.push({ id: `${relativeId(file)} <${tag}>`, body });+ at = source.indexOf("modal={false}", at + 1);+ }+ }+ return menus;+}++test("every non-modal menu either mounts MenuDismissGuard or is a listed exception", () => {+ const menus = nonModalMenus();+ // Require at least one menu so an empty sweep cannot pass.+ assert.ok(+ menus.length >= 2,+ `only found ${menus.length} non-modal menus; the sweep is not reaching the tree`,+ );+ const offenders = menus+ .filter(({ id, body }) => !GUARD.test(body) && !UNGUARDED.has(id))+ .map(({ id }) => id);+ assert.deepEqual(+ offenders,+ [],+ `a non-modal menu with no guard lets the press that dismisses it fire whatever is underneath. Add the guard, or list it in UNGUARDED with the reason. Offenders: ${offenders.join(", ")}`,+ );+});++test("the exception list does not outlive the menus it excuses", () => {+ const ids = new Set(nonModalMenus().map(({ id }) => id));+ for (const id of UNGUARDED.keys()) {+ assert.ok(+ ids.has(id),+ `${id} is excused from the guard but is no longer a non-modal menu; drop the entry`,+ );+ }+});++test("the element scan does not confuse a tag with one that merely starts the same", () => {+ // Exact tag matching prevents trigger prefixes from unbalancing the scan.+ const source = [+ "<DropdownMenu modal={false}>",+ " <DropdownMenuTrigger />",+ "</DropdownMenu>",+ "<MenuDismissGuard />",+ ].join("\n");+ const { tag, body } = element(source, source.indexOf("modal={false}"));+ assert.equal(tag, "DropdownMenu");+ assert.ok(+ !GUARD.test(body),+ "the scan ran past the menu's own closing tag and swallowed the next element",+ );+});++test("menu ids are separator-independent", () => {+ // Normalize Windows paths before matching exemptions.+ for (const { id } of nonModalMenus()) {+ assert.ok(!id.includes("\\"), `${id} carries a host separator`);+ }+});++test("the guard component is what mounts the watcher", () => {+ const guard = readFileSync(+ path.join(SRC, "lib/menu-dismiss-guard.tsx"),+ "utf8",+ );+ assert.match(+ guard,+ /useDismissingClickGuard\(\)/,+ "MenuDismissGuard must install the document watcher, or every mount above is decoration",+ );+});diff --git a/studio/frontend/tests/nonmodal-menu-second-pointer.test.ts b/studio/frontend/tests/nonmodal-menu-second-pointer.test.tsnew file mode 100644index 00000000000..26dbd4ae5d0--- /dev/null+++ b/studio/frontend/tests/nonmodal-menu-second-pointer.test.ts@@ -0,0 +1,434 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Pin the multi-pointer ordering and release grace period with a deterministic fake DOM.++import assert from "node:assert/strict";+import test from "node:test";++type Listener = (event: FakeEvent) => void;++interface FakeEvent {+ type: string;+ target?: unknown;+ detail?: number;+ button?: number;+ pointerId?: number;+ pointerType?: string;+ key?: string;+ stopped?: boolean;+ prevented?: boolean;+ stopPropagation?: () => void;+ preventDefault?: () => void;+}++class FakeNode {}++/** Minimal `closest` implementation for the guard's menu check. */+class FakeElement extends FakeNode {+ inMenu: boolean;+ readonly parent?: FakeElement;+ readonly textEntry: boolean;+ constructor(inMenu: boolean, parent?: FakeElement, textEntry = false) {+ super();+ this.inMenu = inMenu;+ this.parent = parent;+ this.textEntry = textEntry;+ }+ closest(): FakeElement | null {+ if (this.inMenu) return this;+ for (let node = this.parent; node; node = node.parent) {+ if (node.inMenu) return node;+ }+ return null;+ }+ contains(candidate: unknown): boolean {+ for (+ let node = candidate instanceof FakeElement ? candidate : undefined;+ node;+ node = node.parent+ ) {+ if (node === this) return true;+ }+ return false;+ }+ matches(): boolean {+ return this.textEntry;+ }+}++class FakeHTMLElement extends FakeElement {+ isContentEditable = false;+ blurCount = 0;+ blur(): void {+ this.blurCount += 1;+ if (fakeDocument.activeElement === this) fakeDocument.activeElement = null;+ }+}++class FakeMouseEvent implements FakeEvent {+ detail = 0;+ type: string;+ constructor(type: string) {+ this.type = type;+ }+}++class FakeDocument {+ private readonly capturing = new Map<string, Listener[]>();+ private readonly bubbling = new Map<string, Listener[]>();+ activeElement: unknown = null;++ addEventListener(type: string, fn: Listener, capture?: boolean): void {+ const bucket = capture ? this.capturing : this.bubbling;+ const list = bucket.get(type) ?? [];+ if (!list.includes(fn)) list.push(fn);+ bucket.set(type, list);+ }++ removeEventListener(type: string, fn: Listener, capture?: boolean): void {+ const bucket = capture ? this.capturing : this.bubbling;+ const list = bucket.get(type);+ if (!list) return;+ const at = list.indexOf(fn);+ if (at >= 0) list.splice(at, 1);+ }++ /** Dispatch capture then bubble listeners. */+ dispatchEvent(event: FakeEvent): void {+ event.stopped = false;+ event.prevented = false;+ event.stopPropagation = () => {+ event.stopped = true;+ };+ event.preventDefault = () => {+ event.prevented = true;+ };+ for (const phase of [this.capturing, this.bubbling]) {+ for (const fn of [...(phase.get(event.type) ?? [])]) {+ if (event.stopped) return;+ fn(event);+ }+ if (event.stopped) return;+ }+ }+}++/** Deterministic timer clock. */+class FakeWindow {+ private next = 1;+ private readonly timers = new Map<number, { at: number; fn: () => void }>();+ private now = 0;+ private readonly windowListeners = new Map<string, Listener[]>();++ setTimeout(fn: () => void, ms: number): number {+ const id = this.next++;+ this.timers.set(id, { at: this.now + ms, fn });+ return id;+ }+ clearTimeout(id: number | undefined): void {+ if (id !== undefined) this.timers.delete(id);+ }+ addEventListener(type: string, fn: Listener): void {+ const list = this.windowListeners.get(type) ?? [];+ if (!list.includes(fn)) list.push(fn);+ this.windowListeners.set(type, list);+ }+ removeEventListener(type: string, fn: Listener): void {+ const list = this.windowListeners.get(type);+ if (!list) return;+ const at = list.indexOf(fn);+ if (at >= 0) list.splice(at, 1);+ }+ dispatchEvent(event: FakeEvent): void {+ for (const fn of [...(this.windowListeners.get(event.type) ?? [])]) fn(event);+ }+ advance(ms: number): void {+ this.now += ms;+ for (const [id, timer] of [...this.timers]) {+ if (timer.at <= this.now) {+ this.timers.delete(id);+ timer.fn();+ }+ }+ }+}++const fakeDocument = new FakeDocument();+const fakeWindow = new FakeWindow();++const globals = globalThis as unknown as Record<string, unknown>;+globals.document = fakeDocument;+globals.window = fakeWindow;+globals.Node = FakeNode;+globals.Element = FakeElement;+globals.HTMLElement = FakeHTMLElement;+globals.MouseEvent = FakeMouseEvent;++const { installDismissingClickGuard } = await import(+ "../src/lib/menu-dismiss.ts"+);++const OUTSIDE = new FakeHTMLElement(false);+const INSIDE_MENU = new FakeHTMLElement(true);++const down = (+ pointerId: number,+ pointerType: string,+ target: unknown,+): void => {+ fakeDocument.dispatchEvent({+ type: "pointerdown",+ pointerId,+ pointerType,+ button: 0,+ target,+ });+};+const up = (pointerId: number, pointerType: string): void => {+ fakeDocument.dispatchEvent({ type: "pointerup", pointerId, pointerType });+};++/** Dispatch a target click and report whether it reached bubble listeners. */+function clickReachedTheControl(target: unknown): boolean {+ let delivered = false;+ const watch = (event: FakeEvent): void => {+ if (event.target === target) delivered = true;+ };+ fakeDocument.addEventListener("click", watch, false);+ try {+ fakeDocument.dispatchEvent({ type: "click", detail: 1, target });+ } finally {+ fakeDocument.removeEventListener("click", watch, false);+ }+ return delivered;+}++/** Install a guard for one isolated test. */+function withOpenMenu(body: () => void): void {+ const remove = installDismissingClickGuard();+ try {+ body();+ } finally {+ remove();+ down(999, "mouse", INSIDE_MENU);+ up(999, "mouse");+ fakeWindow.advance(5000);+ }+}++test("a second pointer's release does not retire the gesture that armed the guard", () => {+ withOpenMenu(() => {+ // A finger holds a control outside the menu; touch dismissal is deferred to its click.+ down(11, "touch", OUTSIDE);+ // A mouse presses and releases inside the still-open menu.+ down(22, "mouse", INSIDE_MENU);+ up(22, "mouse");+ // Advance beyond CLICK_GRACE_MS while the finger remains down.+ fakeWindow.advance(900);+ assert.equal(+ clickReachedTheControl(OUTSIDE),+ false,+ "the held finger's compatibility click reached the control underneath: a second " ++ "pointer's pointerup retired a gesture that was never released",+ );+ });+});++test("a second pointer's cancel does not retire it either", () => {+ withOpenMenu(() => {+ down(11, "touch", OUTSIDE);+ down(22, "mouse", INSIDE_MENU);+ fakeDocument.dispatchEvent({+ type: "pointercancel",+ pointerId: 22,+ pointerType: "mouse",+ });+ fakeWindow.advance(900);+ assert.equal(+ clickReachedTheControl(OUTSIDE),+ false,+ "a second pointer being cancelled disarmed a guard whose own pointer was still down",+ );+ });+});++// ---------------------------------------------------------------------------+// and the other direction, which is just as broken and looks identical from outside+// ---------------------------------------------------------------------------++test("the armed pointer's OWN release still starts the bound", () => {+ withOpenMenu(() => {+ down(11, "mouse", OUTSIDE);+ up(11, "mouse");+ fakeWindow.advance(900);+ assert.equal(+ clickReachedTheControl(OUTSIDE),+ true,+ "a gesture that produced no click must not leave the swallower armed for an unrelated " ++ "one; filtering by pointer id must not cost the bound its own release",+ );+ });+});++test("the armed pointer's own click is still swallowed, once", () => {+ withOpenMenu(() => {+ down(11, "mouse", OUTSIDE);+ up(11, "mouse");+ assert.equal(+ clickReachedTheControl(OUTSIDE),+ false,+ "the dismissing click is the one click this guard exists to eat",+ );+ assert.equal(+ clickReachedTheControl(OUTSIDE),+ true,+ "and exactly one: the click after it is the user's",+ );+ });+});++test("a new gesture supersedes an armed no-click gesture after menu cleanup", () => {+ const remove = installDismissingClickGuard();+ try {+ down(11, "mouse", OUTSIDE);+ up(11, "mouse");+ // The first gesture produced no click, but the swallower remains armed during grace.+ remove();++ down(12, "mouse", OUTSIDE);+ up(12, "mouse");+ assert.equal(+ clickReachedTheControl(OUTSIDE),+ true,+ "the first click of a new gesture was swallowed after the menu's watcher unmounted",+ );+ } finally {+ remove();+ fakeWindow.advance(5000);+ }+});++test("the armed pointer's own cancel still disarms", () => {+ withOpenMenu(() => {+ down(11, "touch", OUTSIDE);+ fakeDocument.dispatchEvent({+ type: "pointercancel",+ pointerId: 11,+ pointerType: "touch",+ });+ assert.equal(+ clickReachedTheControl(OUTSIDE),+ true,+ "a cancelled gesture produces no click of its own, so the guard must not survive it",+ );+ });+});++test("a drag-retargeted click releases the control focused by the guarded press", () => {+ withOpenMenu(() => {+ const clickAncestor = new FakeHTMLElement(false);+ const button = new FakeHTMLElement(false, clickAncestor);+ const icon = new FakeElement(false, button);+ fakeDocument.activeElement = INSIDE_MENU;++ down(11, "mouse", icon);+ // Pointerdown's default action runs after the capture listener and focuses the button.+ fakeDocument.activeElement = button;+ up(11, "mouse");++ assert.equal(+ clickReachedTheControl(clickAncestor),+ false,+ "the drag-retargeted click must still be swallowed",+ );+ assert.equal(+ button.blurCount,+ 1,+ "focus cleanup must use the original press target, not the retargeted click ancestor",+ );+ });+});++test("focus moved elsewhere during the gesture is preserved", () => {+ withOpenMenu(() => {+ const clickAncestor = new FakeHTMLElement(false);+ const pressedButton = new FakeHTMLElement(false, clickAncestor);+ const icon = new FakeElement(false, pressedButton);+ const appFocusedControl = new FakeHTMLElement(false);+ fakeDocument.activeElement = INSIDE_MENU;++ down(11, "mouse", icon);+ fakeDocument.activeElement = appFocusedControl;+ up(11, "mouse");+ clickReachedTheControl(clickAncestor);++ assert.equal(+ appFocusedControl.blurCount,+ 0,+ "the guard must not blur focus the app moved away from the pressed control",+ );+ });+});++test("a control focused before the guarded press is preserved", () => {+ withOpenMenu(() => {+ const button = new FakeHTMLElement(false);+ fakeDocument.activeElement = button;++ down(11, "mouse", button);+ up(11, "mouse");+ assert.equal(clickReachedTheControl(button), false);++ assert.equal(button.blurCount, 0, "the press did not acquire this existing focus");+ assert.equal(fakeDocument.activeElement, button);+ });+});++test("window blur retires the guard and releases press-acquired focus", () => {+ withOpenMenu(() => {+ const button = new FakeHTMLElement(false);+ fakeDocument.activeElement = INSIDE_MENU;++ down(11, "mouse", button);+ fakeDocument.activeElement = button;+ fakeWindow.dispatchEvent({ type: "blur" });++ assert.equal(button.blurCount, 1);+ assert.equal(+ clickReachedTheControl(button),+ true,+ "a guard retired on window blur must not swallow a later click",+ );+ });+});++test("a no-click grace timeout also releases press-acquired focus", () => {+ withOpenMenu(() => {+ const button = new FakeHTMLElement(false);+ fakeDocument.activeElement = INSIDE_MENU;++ down(11, "mouse", button);+ fakeDocument.activeElement = button;+ up(11, "mouse");+ fakeWindow.advance(900);++ assert.equal(button.blurCount, 1);+ assert.equal(clickReachedTheControl(button), true);+ });+});++test("text-entry focus acquired by the guarded press is preserved", () => {+ withOpenMenu(() => {+ const input = new FakeHTMLElement(false, undefined, true);+ fakeDocument.activeElement = INSIDE_MENU;++ down(11, "mouse", input);+ fakeDocument.activeElement = input;+ up(11, "mouse");+ assert.equal(clickReachedTheControl(input), false);++ assert.equal(input.blurCount, 0, "typing focus must keep its caret");+ assert.equal(fakeDocument.activeElement, input);+ });+});diff --git a/tests/studio/probe_dismiss_guard.py b/tests/studio/probe_dismiss_guard.pynew file mode 100644index 00000000000..53e157cd737--- /dev/null+++ b/tests/studio/probe_dismiss_guard.py@@ -0,0 +1,668 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Does the non-modal menu dismissal guard stop exactly the right click, and only that one?++The easy case is one `page.mouse.click`, a press and a release in the same tick, and every+version of the guard passes it. These are the cases that separate them. Each was checked against a DELIBERATELY BROKEN tree+before its green was trusted; where a case does not discriminate, that is said here rather than+left to be assumed.++The guard must swallow too little nowhere:++ quick press and release in one tick. Control case.+ held press, wait past any fixed deadline, release. A guard armed from Radix's+ `onPointerDownOutside` and disarmed by a 300 ms timer is gone by the time the+ browser synthesises `click`. Discriminates: chromium, webkit, firefox.+ busy press, block the main thread, release. The same outcome from a normal-length+ press, which is what a heavy thread produces on its own. Flaky as a detector:+ it reproduced on one chromium run and not the next, so `held` is the reliable+ one and this is kept only as a second look.+ touch tap. `usePointerDownOutside` in react-dismissable-layer 1.1.11 defers to the+ resulting `click` when `pointerType === "touch"`, on `ownerDocument`, bubble+ phase, and React 19 delegates to the root container inside document, so the+ control's `onClick` has already run. Discriminates: chromium, webkit.+ held_enter press, press Enter while still holding, release. The press focuses the button,+ so Enter activates it and the browser fires a keyboard-generated click with the+ pointer still down. A guard that spends itself on that has nothing left for the+ click the release synthesises. Discriminates: chromium.+ held_space press, hold Space, RELEASE THE POINTER, then release Space. Space activates a+ focused control on its keyup, so its click arrives after the pointer's own, on a+ guard that has already spent itself. Discriminates: FIREFOX ONLY, and that is a+ property of the engines rather than of the harness. Gecko tracks the pending+ activation on its own `HTML_ELEMENT_ACTIVE_FOR_KEYBOARD` flag, which the mouse+ release does not clear, so the click still fires; Blink and WebKit gate it on the+ shared `:active` state, which the release does clear, so no click is ever+ dispatched 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+ second_ press lands inside the still-open menu, then the finger lifts. Radix defers a+ pointer touch dismissal to the resulting click, so the menu is still there for a second+ pointer to land in, and every early return in the guard's `pointerdown` handler+ gave the guard up without rearming it. Discriminates: chromium. Needs two+ pointers alive at once, so it is CDP-only and reports itself skipped elsewhere+ rather than passing vacuously; it asserts both pointers were live before it+ trusts any verdict. TWO FINGERS cannot reach this and the case does not try:+ measured with real CDP multi-touch, two active touch points suppress every+ compatibility mouse event for the rest of the gesture, so the held finger's+ release delivers no click to swallow in the first place. This case watches the+ swallow-too-little direction only: the second pointer's own press raises no+ `click` while a touch point is live, on either tree, so it cannot also stand in+ for the swallow-too-much direction.+ dismiss_then_ click the button to dismiss, then press Space, the key a reader uses to scroll.+ space No click is involved for the guard to swallow: the press it DID swallow left the+ button focused, and a focused button activates on Space. Discriminates on+ chromium, firefox and webkit. The modal shape cannot reach it, because with+ `pointer-events: none` on the body the press lands on `HTML` and focus never+ moves off `BODY`.++and too much nowhere:++ dismiss_on_ dismiss the menu by clicking INTO the composer, then type. Releasing the focus a+ composer swallowed press took must not take the caret with it. Discriminates against a+ guard that blurs unconditionally.++ select a click INSIDE the menu must still reach its item.+ second_click dismiss on neutral ground, then click again. Exactly one click is the menu's.+ rightclick_ a right click raises `contextmenu` and no `click`, so a guard with no upper+ then_click bound stays armed and eats the user's next real click. Discriminates.+ dragoff_ press, drag out, release. Does NOT discriminate today: a click still fires at+ then_click the common ancestor, so this passes with and without the bound. Kept as a+ cheap watch on a different shape, not offered as evidence.+ touch_neutral a tap on a spot that CANNOT take focus, with the menu open. The capture-phase+ swallow denies Radix its deferred touch dismissal, and when the tapped element+ is focusable `useFocusOutside` closes the menu anyway, which is exactly how an+ earlier version of the guard looked correct while leaving the menu open on+ plain background. The neutral spot is grid-searched for a genuinely+ non-focusable element and the probe FAILS rather than falling back if none+ exists, because a probe that cannot tell you it missed is worse than none.++Every verdict is a DOM fact: did the assistant message count go down, did the menu close, did+the watched click land. Clicks go through `page.mouse` / `page.touchscreen`, real hit tests that+honour pointer-events. `locator.click()` throws on interception and `element.click()` skips hit+testing, and each would lie in a different direction.++Run against the PR head AND the merge base. On the merge base these menus are modal, the body+carries `pointer-events: none`, and no variant reaches the control at all.++Usage: python tests/studio/probe_dismiss_guard.py --label head --engine chromium+Exits non-zero on any failure, so it is a gate rather than a report.+Writes logs/pw/dismiss_guard_<label>_<engine>.json+"""++from __future__ import annotations++import argparse+import asyncio+import json+import os+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))++from playwright_heavy_thread import ( # noqa: E402+ BASE,+ OWNS_SERVER,+ PORT,+ start_vite,+ stop_process,+ wait_for_smoke_page,+)++CHARS = int(os.environ.get("PROBE_CHARS", "25000"))+HOLD_MS = int(os.environ.get("PROBE_HOLD_MS", "600"))+# Deliberately beyond CLICK_GRACE_MS (500).+GRACE_HOLD_MS = int(os.environ.get("PROBE_GRACE_HOLD_MS", "900"))++OPEN_MENU_JS = """+async () => {+ const api = window.__heavyThread;+ const trigger = api.actionButton("More");+ if (!trigger) return { ok: false, why: "no More trigger" };+ 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 deadline = performance.now() + 15000;+ while (performance.now() < deadline) {+ if (document.querySelector(".aui-action-bar-more-content")) break;+ await new Promise((r) => requestAnimationFrame(r));+ }+ return { ok: Boolean(document.querySelector(".aui-action-bar-more-content")) };+}+"""++FACTS_JS = """+() => {+ const api = window.__heavyThread;+ const del = api.actionButton("Delete message");+ const r = del ? del.getBoundingClientRect() : 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,+ };+}+"""++# Simulate main-thread work between pointerdown and the synthesized click.+BLOCK_JS = """+(ms) => { const end = Date.now() + ms; while (Date.now() < end) {} }+"""++# Watch clicks that must still land.+WATCH_ITEM_JS = """+() => {+ // The first item forks into a new chat, so a fast runner can navigate before this probe reads+ // its counter. Export closes the same Radix menu without replacing the page under the probe.+ const item = [...document.querySelectorAll(".aui-action-bar-more-item")].find(+ (candidate) => candidate.textContent?.includes("Export as markdown")+ );+ if (!item) return null;+ window.__dismissProbe = { itemClicks: 0 };+ item.addEventListener("click", () => { window.__dismissProbe.itemClicks += 1; });+ const r = item.getBoundingClientRect();+ return { x: r.x + r.width / 2, y: r.y + r.height / 2 };+}+"""++# Find a real neutral target in the visible thread.+WATCH_NEUTRAL_JS = """+(wantUnfocusable) => {+ const v = window.__heavyThread.viewport();+ if (!v) return null;+ const r = v.getBoundingClientRect();+ const FOCUSABLE = 'button,a[href],input,textarea,select,[tabindex],[contenteditable]';+ // Grid-search rather than pick one point. The obvious choice lands on a BUTTON often enough+ // that a run can silently test the focusable case while claiming to test the other one, and+ // a probe that cannot tell you it missed is worse than no probe. If no qualifying point+ // exists in the viewport, say so instead of falling back to whatever was there.+ for (let fy = 0.9; fy > 0.05; fy -= 0.05) {+ for (let fx = 0.1; fx < 0.95; fx += 0.05) {+ const x = Math.round(r.x + r.width * fx);+ const y = Math.round(r.y + r.height * fy);+ const el = document.elementFromPoint(x, y);+ if (!el) continue;+ if (el.closest('[role="menu"],[data-radix-popper-content-wrapper]')) continue;+ const focusable = Boolean(el.closest(FOCUSABLE));+ if (wantUnfocusable && focusable) continue;+ window.__dismissProbe = { neutralClicks: 0 };+ el.addEventListener("click", () => { window.__dismissProbe.neutralClicks += 1; });+ return { x, y, tag: el.tagName, focusable };+ }+ }+ return null;+}+"""+++# Record concurrent pointers and clicks for multi-pointer cases.+MULTI_POINTER_INIT = """+(() => {+ const st = { live: [], maxLive: 0, concurrentTypes: [], downs: [] };+ window.__multiPointer = st;+ const typeOf = {};+ document.addEventListener("pointerdown", (e) => {+ st.live.push(e.pointerId);+ typeOf[e.pointerId] = e.pointerType;+ if (st.live.length > st.maxLive) {+ st.maxLive = st.live.length;+ st.concurrentTypes = st.live.map((id) => typeOf[id]);+ }+ st.downs.push({ id: e.pointerId, type: e.pointerType, primary: e.isPrimary });+ }, true);+ const drop = (e) => {+ const i = st.live.indexOf(e.pointerId);+ if (i >= 0) st.live.splice(i, 1);+ };+ document.addEventListener("pointerup", drop, true);+ document.addEventListener("pointercancel", drop, true);+ const inMenu = (el) => Boolean(el && el.closest && el.closest(+ '[role="menu"],[role="menuitem"],[data-radix-popper-content-wrapper]'+ ));+ const seen = (e) => ({ tag: e.target && e.target.tagName, detail: e.detail,+ inMenu: inMenu(e.target) });+ st.clicks = [];+ st.delivered = [];+ document.addEventListener("click", (e) => { st.clicks.push(seen(e)); }, true);+ // Bubble phase on `document`: the guard stops propagation in CAPTURE at `document`, so a click+ // it swallowed can never reach this. Node identity is not usable here -- the menu re-renders+ // between the setup read and the press -- so delivery is read off the event's own target.+ document.addEventListener("click", (e) => { st.delivered.push(seen(e)); }, false);+})()+"""++# Find a non-item point inside the menu for the second pointer.+MENU_BLANK_JS = """+() => {+ const menu = document.querySelector('[role="menu"]');+ if (!menu) return null;+ const r = menu.getBoundingClientRect();+ for (let y = Math.round(r.y) + 1; y < r.bottom - 1; y += 1) {+ for (let x = Math.round(r.x) + 1; x < r.right - 1; x += 2) {+ const el = document.elementFromPoint(x, y);+ if (!el) continue;+ const surface = el.closest(+ '[role="menu"],[role="menuitem"],[data-radix-popper-content-wrapper]'+ );+ if (!surface) continue;+ if (el.closest('[role="menuitem"]')) continue;+ return { x, y, tag: el.tagName };+ }+ }+ return null;+}+"""+++async def hover_last_assistant(page) -> None:+ await page.evaluate(+ "() => window.__heavyThread.lastAssistantMessage()?.scrollIntoView({ block: 'center' })"+ )+ box = await page.evaluate(+ "() => { const m = window.__heavyThread.lastAssistantMessage();"+ "if (!m) return null; const r = m.getBoundingClientRect();"+ "return { x: r.x + r.width / 2, y: r.y + r.height / 2 }; }"+ )+ if box:+ await page.mouse.move(box["x"], box["y"])+ await page.wait_for_timeout(600)+++async def one_case(+ page,+ case: str,+ engine: str = "chromium",+ context = None,+) -> dict:+ """Open the menu, attack the Delete button one way, report whether it fired."""+ 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)+ rect = before["deleteRect"]+ if not rect:+ return {"case": case, "error": "no Delete button"}+ x, y = rect["x"], rect["y"]++ if case == "quick":+ await page.mouse.move(x, y)+ await page.mouse.down()+ await page.mouse.up()+ elif case == "held":+ await page.mouse.move(x, y)+ await page.mouse.down()+ await page.wait_for_timeout(HOLD_MS)+ await page.mouse.up()+ elif case == "busy":+ await page.mouse.move(x, y)+ await page.mouse.down()+ # Keep the press normal-length while blocking the page.+ await page.evaluate(BLOCK_JS, HOLD_MS)+ await page.mouse.up()+ elif case == "held_modifier":+ # Modifiers may be pressed during a held gesture.+ await page.mouse.move(x, y)+ await page.mouse.down()+ await page.wait_for_timeout(120)+ await page.keyboard.down("Shift")+ await page.wait_for_timeout(120)+ await page.mouse.up()+ await page.keyboard.up("Shift")+ elif case == "held_enter":+ # Enter activates the focused button while the pointer remains down.+ await page.mouse.move(x, y)+ await page.mouse.down()+ await page.wait_for_timeout(120)+ await page.keyboard.press("Enter")+ await page.wait_for_timeout(120)+ await page.mouse.up()+ elif case == "held_space":+ # Space activates on keyup, after the pointer click.+ await page.mouse.move(x, y)+ await page.mouse.down()+ await page.wait_for_timeout(120)+ await page.keyboard.down("Space")+ await page.wait_for_timeout(120)+ await page.mouse.up()+ await page.wait_for_timeout(120)+ await page.keyboard.up("Space")+ elif case == "held_space_then_space":+ # Ensure the swallowed press does not leave the button focused.+ await page.mouse.move(x, y)+ await page.mouse.down()+ await page.wait_for_timeout(120)+ await page.keyboard.down("Space")+ await page.wait_for_timeout(120)+ await page.mouse.up()+ await page.wait_for_timeout(120)+ await page.keyboard.up("Space")+ await page.wait_for_timeout(300)+ await page.keyboard.press("Space")+ elif case == "dismiss_then_space":+ # A swallowed dismissal must not leave Delete focused for Space activation.+ await page.mouse.click(x, y)+ await page.wait_for_timeout(300)+ await page.keyboard.press("Space")+ elif case in ("drag_then_space", "blur_then_space"):+ # A drag may retarget the click; blur exercises the no-click cleanup path.+ spot = await page.evaluate(WATCH_NEUTRAL_JS, False)+ if not spot:+ return {"case": case, "error": "no qualifying neutral spot in the viewport"}+ await page.mouse.move(x, y)+ await page.mouse.down()+ await page.wait_for_timeout(120)+ if case == "blur_then_space":+ await page.evaluate("() => window.dispatchEvent(new Event('blur'))")+ await page.mouse.move(spot["x"], spot["y"])+ await page.mouse.up()+ await page.wait_for_timeout(700)+ await page.keyboard.press("Space")+ elif case == "dismiss_on_composer":+ # Dismissing into the composer must preserve its caret.+ spot = await page.evaluate(+ "() => { const c = window.__heavyThread.composer(); if (!c) return null;"+ "const r = c.getBoundingClientRect();"+ "return { x: r.x + r.width / 2, y: r.y + r.height / 2 }; }"+ )+ if not spot:+ return {"case": case, "error": "no composer"}+ await page.mouse.click(spot["x"], spot["y"])+ await page.wait_for_timeout(300)+ await page.keyboard.type("zz")+ await page.wait_for_timeout(400)+ after = await page.evaluate(FACTS_JS)+ typed = await page.evaluate(+ "() => { const c = window.__heavyThread.composer(); return c ? c.value : ''; }"+ )+ return {+ "case": case,+ "composerText": typed[-8:],+ "menuClosed": not after["menuOpen"],+ "lostComposerFocus": not typed.endswith("zz"),+ "deleted": after["assistantMessages"] < before["assistantMessages"],+ }+ elif case == "touch":+ await page.touchscreen.tap(x, y)+ elif case in ("touch_hold_second_pointer", "touch_hold_second_pointer_grace"):+ # Hold touch while a mouse interacts with the open menu.+ if engine != "chromium" or context is None:+ return {+ "case": case,+ "skipped": f"{engine} has no API for a held touch alongside a second pointer",+ }+ blank = await page.evaluate(MENU_BLANK_JS)+ if not blank:+ return {"case": case, "error": "no non-item spot inside the menu"}+ cdp = await context.new_cdp_session(page)+ finger = [{"x": x, "y": y, "id": 1, "radiusX": 1, "radiusY": 1, "force": 1}]+ await cdp.send("Input.dispatchTouchEvent", {"type": "touchStart", "touchPoints": finger})+ await page.wait_for_timeout(150)+ held = await page.evaluate(FACTS_JS)+ await page.mouse.move(blank["x"], blank["y"])+ await page.mouse.down()+ await page.wait_for_timeout(80)+ live = await page.evaluate("() => window.__multiPointer.live.length")+ await page.mouse.up()+ await page.wait_for_timeout(GRACE_HOLD_MS if case.endswith("_grace") else 150)+ if case.endswith("_grace"):+ still_down = await page.evaluate("() => window.__multiPointer.live.length")+ if still_down < 1:+ return {+ "case": case,+ "error": "the finger was no longer down when the bound expired, so the "+ "case tested nothing",+ }+ await cdp.send("Input.dispatchTouchEvent", {"type": "touchEnd", "touchPoints": finger})+ await page.wait_for_timeout(1500)+ after = await page.evaluate(FACTS_JS)+ state = await page.evaluate("() => window.__multiPointer")+ if not held["menuOpen"]:+ return {+ "case": case,+ "error": "the held touch dismissed the menu, so there was no "+ "open menu for a second pointer to land in",+ }+ if state["maxLive"] < 2 or live < 2:+ return {+ "case": case,+ "error": f"the two pointers never coexisted: maxLive="+ f"{state['maxLive']}, live at the second press={live}",+ }+ if sorted(state["concurrentTypes"]) != ["mouse", "touch"]:+ return {"case": case, "error": f"wrong pointer types: {state['concurrentTypes']}"}+ return {+ "case": case,+ "concurrentPointers": state["downs"],+ "menuOpenUnderSecondPointer": held["menuOpen"],+ "assistantMessagesBefore": before["assistantMessages"],+ "assistantMessagesAfter": after["assistantMessages"],+ "deleted": after["assistantMessages"] < before["assistantMessages"],+ "menuClosed": not after["menuOpen"],+ "clicksSeen": state["clicks"],+ "clicksDelivered": state["delivered"],+ }+ elif case == "select":+ # Selection inside the menu must reach its item.+ spot = await page.evaluate(WATCH_ITEM_JS)+ if not spot:+ return {"case": case, "error": "no menu item to select"}+ await page.mouse.click(spot["x"], spot["y"])+ await page.wait_for_timeout(800)+ return {+ "case": case,+ "itemClicks": await page.evaluate("() => window.__dismissProbe.itemClicks"),+ "swallowedSelection": (+ await page.evaluate("() => window.__dismissProbe.itemClicks") == 0+ ),+ }+ elif case == "touch_neutral":+ # A non-focusable touch target exercises Radix's deferred dismissal.+ spot = await page.evaluate(WATCH_NEUTRAL_JS, case == "touch_neutral")+ if not spot:+ return {"case": case, "error": "no qualifying neutral spot in the viewport"}+ await page.touchscreen.tap(spot["x"], spot["y"])+ await page.wait_for_timeout(1200)+ after = await page.evaluate(FACTS_JS)+ return {+ "case": case,+ "tappedTag": spot.get("tag"),+ "menuClosed": not after["menuOpen"],+ "deleted": after["assistantMessages"] < before["assistantMessages"],+ }+ elif case == "touch_trigger":+ # Tapping the trigger must still close the menu.+ trigger = await page.evaluate(+ "() => { const t = window.__heavyThread.actionButton('More');"+ "if (!t) return null; const r = t.getBoundingClientRect();"+ "return { x: r.x + r.width / 2, y: r.y + r.height / 2 }; }"+ )+ if not trigger:+ return {"case": case, "error": "no More trigger"}+ await page.touchscreen.tap(trigger["x"], trigger["y"])+ await page.wait_for_timeout(1200)+ after = await page.evaluate(FACTS_JS)+ return {+ "case": case,+ "menuClosed": not after["menuOpen"],+ "deleted": after["assistantMessages"] < before["assistantMessages"],+ }+ elif case in ("rightclick_then_click", "dragoff_then_click"):+ # These dismissing gestures may produce no click.+ spot = await page.evaluate(WATCH_NEUTRAL_JS, False)+ if not spot:+ return {"case": case, "error": "no qualifying neutral spot in the viewport"}+ if case == "rightclick_then_click":+ # Prevent browser chrome from consuming the next automated click.+ await page.evaluate(+ """() => document.addEventListener(+ "contextmenu", (event) => event.preventDefault(),+ { capture: true, once: true }+ )"""+ )+ await page.mouse.click(spot["x"], spot["y"], button = "right")+ else:+ await page.mouse.move(spot["x"], spot["y"])+ await page.mouse.down()+ await page.mouse.move(4, 4)+ await page.mouse.up()+ # INSIDE the release-anchored grace window on purpose. Waiting it out was the first+ # version of this case and it passed on a tree that was still eating the click, because+ # it only ever asked whether the bound existed, not whether the guard should have armed+ # for a gesture that cannot produce a click at all.+ await page.wait_for_timeout(150)+ await page.mouse.click(spot["x"], spot["y"])+ await page.wait_for_timeout(600)+ clicks = await page.evaluate("() => window.__dismissProbe.neutralClicks")+ return {+ "case": case,+ "neutralClicks": clicks,+ "swallowedLaterClick": clicks < 1,+ }+ elif case == "select_then_quick_click":+ # Exercise a click during the menu's exit animation.+ item = await page.evaluate(WATCH_ITEM_JS)+ if not item:+ return {"case": case, "error": "no menu item to select"}+ spot = await page.evaluate(WATCH_NEUTRAL_JS, False)+ if not spot:+ return {"case": case, "error": "no qualifying neutral spot in the viewport"}+ await page.evaluate("() => { window.__dismissProbe.neutralClicks = 0; }")+ await page.mouse.click(item["x"], item["y"])+ await page.wait_for_timeout(int(os.environ.get("PROBE_EXIT_DELAY_MS", "40")))+ await page.mouse.click(spot["x"], spot["y"])+ await page.wait_for_timeout(600)+ clicks = await page.evaluate("() => window.__dismissProbe.neutralClicks")+ return {+ "case": case,+ "neutralClicks": clicks,+ "swallowedLaterClick": clicks == 0,+ }+ elif case == "second_click":+ # Only the dismissing click may be swallowed.+ spot = await page.evaluate(WATCH_NEUTRAL_JS, False)+ if not spot:+ return {"case": case, "error": "no qualifying neutral spot in the viewport"}+ await page.mouse.click(spot["x"], spot["y"])+ await page.wait_for_timeout(200)+ await page.mouse.click(spot["x"], spot["y"])+ await page.wait_for_timeout(600)+ clicks = await page.evaluate("() => window.__dismissProbe.neutralClicks")+ return {+ "case": case,+ "neutralClicks": clicks,+ "swallowedSecondClick": clicks < 1,+ }+ else:+ return {"case": case, "error": f"unknown case {case}"}++ await page.wait_for_timeout(1500)+ after = await page.evaluate(FACTS_JS)+ return {+ "case": case,+ "bodyPointerEvents": before["bodyPointerEvents"],+ "assistantMessagesBefore": before["assistantMessages"],+ "assistantMessagesAfter": after["assistantMessages"],+ "deleted": after["assistantMessages"] < before["assistantMessages"],+ "menuClosed": not after["menuOpen"],+ }+++async def run(engine: str, cases: list[str]) -> dict:+ from playwright.async_api import async_playwright++ out: dict = {"engine": engine, "chars": CHARS, "hold_ms": HOLD_MS, "cases": []}+ async with async_playwright() as pw:+ browser = await getattr(pw, engine).launch(headless = True)+ for case in cases:+ context = await browser.new_context(+ viewport = {"width": 1280, "height": 900},+ has_touch = case.startswith("touch"),+ )+ page = await context.new_page()+ await page.add_init_script(MULTI_POINTER_INIT)+ await page.goto(f"{BASE}/smoke-heavy-thread.html", wait_until = "domcontentloaded")+ await page.wait_for_function("() => Boolean(window.__heavyThread)", timeout = 60_000)+ plan = await page.evaluate("(n) => window.__heavyThread.seed(n)", CHARS)+ await page.wait_for_function(+ "(n) => window.__heavyThread.messageCount() >= n",+ arg = plan["messages"],+ timeout = 300_000,+ )+ try:+ out["cases"].append(await one_case(page, case, engine, context))+ except Exception as exc: # a failed case is a result, not a crash+ out["cases"].append({"case": case, "error": repr(exc)})+ await context.close()+ await browser.close()+ return out+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument("--label", default = "run")+ ap.add_argument("--engine", default = "chromium", choices = ("chromium", "webkit", "firefox"))+ ap.add_argument(+ "--cases",+ default = "quick,held,busy,held_modifier,held_enter,held_space,held_space_then_space,dismiss_then_space,drag_then_space,blur_then_space,dismiss_on_composer,touch,touch_hold_second_pointer,touch_hold_second_pointer_grace,select,select_then_quick_click,second_click,rightclick_then_click,dragoff_then_click,touch_neutral,touch_trigger",+ )+ args = ap.parse_args()+ cases = [c.strip() for c in args.cases.split(",") if c.strip()]++ vite = start_vite(PORT) if OWNS_SERVER else None+ try:+ wait_for_smoke_page(+ f"{BASE}/smoke-heavy-thread.html",+ "smoke-heavy-thread-main.tsx",+ proc = vite,+ info = lambda m: print(f"[probe] {m}", flush = True),+ )+ result = asyncio.run(run(args.engine, cases))+ finally:+ if vite is not None:+ stop_process(vite)++ out = Path("logs/pw") / f"dismiss_guard_{args.label}_{args.engine}.json"+ out.parent.mkdir(parents = True, exist_ok = True)+ out.write_text(json.dumps(result, indent = 2), encoding = "utf-8")+ print(json.dumps(result, indent = 2))+ print(f"[probe] wrote {out}", flush = True)++ 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")]+ stuck = [c["case"] for c in result["cases"] if "menuClosed" in c and not c["menuClosed"]]+ broken = [c["case"] for c in result["cases"] if c.get("error")]+ over = [+ c["case"]+ for c in result["cases"]+ if c.get("swallowedSelection")+ or c.get("swallowedSecondClick")+ or c.get("swallowedLaterClick")+ or c.get("lostComposerFocus")+ ]+ if over:+ print(f"[probe] FAIL: the guard swallowed a click it should not have: {over}", flush = True)+ broken = broken + over+ if deleted:+ print(+ f"[probe] FAIL: dismissing the menu also deleted a message via {deleted}",+ flush = True,+ )+ if broken:+ print(f"[probe] FAIL: cases did not run: {broken}", flush = True)+ if stuck:+ print(f"[probe] FAIL: the menu did not close on {stuck}", flush = True)+ if deleted or broken or stuck:+ return 1+ print("[probe] PASS: no dismissal variant reached the control underneath", flush = True)+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())