Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix: cancel stale work panel tab drags safely

vastsa0556f4ccb40e
diff --git a/apps/desktop/src/components/workpanel/WorkPanel.tsx b/apps/desktop/src/components/workpanel/WorkPanel.tsx
index a8fbe3212..f3ee8c647 100644
--- a/apps/desktop/src/components/workpanel/WorkPanel.tsx
+++ b/apps/desktop/src/components/workpanel/WorkPanel.tsx
@@ -73,6 +73,9 @@ type WorkPanelResizeState = {
type WorkPanelTabReorderState = {
pointerId: number;
sourceTabId: string;
+ activeSessionId: string | undefined;
+ activeTabId: string | null;
+ tabSignature: string;
startClientX: number;
startClientY: number;
lastClientX: number;
@@ -206,12 +209,15 @@ export function WorkPanel({
const setWidth = useAppStore((s) => s.setWorkPanelWidth);
const activeTab = tabs.find((tab) => tab.id === activeTabId) ?? null;
const tools = workPanelTools(t, pluginViews);
+ const tabSignature = JSON.stringify(
+ tabs.map(({ id, kind, resource, location }) => [id, kind, resource, location]),
+ );
const [panelDragWidth, setPanelDragWidth] = useState<number | null>(null);
const panelResizeState = useRef<WorkPanelResizeState | null>(null);
const tabReorderState = useRef<WorkPanelTabReorderState | null>(null);
const tabStripRef = useRef<HTMLDivElement | null>(null);
- const suppressTabClickRef = useRef(false);
+ const suppressedTabClickPointerIdsRef = useRef<Set<number>>(new Set());
const tabButtonRefs = useRef<Record<string, HTMLButtonElement | null>>({});
const newTabButtonRef = useRef<HTMLButtonElement | null>(null);
const [draggingTabId, setDraggingTabId] = useState<string | null>(null);
@@ -280,36 +286,83 @@ export function WorkPanel({
});
}, [activeTabId, tabs.length]);
- const finishTabReorder = useCallback(
- (keepClickSuppressed = false) => {
- const state = tabReorderState.current;
- if (state) {
- window.removeEventListener("pointermove", state.onMove, true);
- window.removeEventListener("pointerup", state.onUp, true);
- window.removeEventListener("pointercancel", state.onCancel, true);
- if (state.autoScrollFrame !== null) {
- cancelAnimationFrame(state.autoScrollFrame);
- state.autoScrollFrame = null;
- }
- tabReorderState.current = null;
+ const finishTabReorder = useCallback(() => {
+ const state = tabReorderState.current;
+ if (state) {
+ window.removeEventListener("pointermove", state.onMove, true);
+ window.removeEventListener("pointerup", state.onUp, true);
+ window.removeEventListener("pointercancel", state.onCancel, true);
+ if (state.autoScrollFrame !== null) {
+ cancelAnimationFrame(state.autoScrollFrame);
+ state.autoScrollFrame = null;
}
- if (!keepClickSuppressed) suppressTabClickRef.current = false;
- setDraggingTabId(null);
- setDropIndicator(null);
- document.documentElement.removeAttribute("data-work-panel-tab-reordering");
- },
- [],
- );
+ tabReorderState.current = null;
+ }
+ setDraggingTabId(null);
+ setDropIndicator(null);
+ document.documentElement.removeAttribute("data-work-panel-tab-reordering");
+ }, []);
+
+ useLayoutEffect(() => {
+ const state = tabReorderState.current;
+ if (
+ state &&
+ (state.activeSessionId !== activeSessionId ||
+ state.activeTabId !== activeTabId ||
+ state.tabSignature !== tabSignature)
+ ) {
+ suppressedTabClickPointerIdsRef.current.add(state.pointerId);
+ finishTabReorder();
+ }
+ }, [activeSessionId, activeTabId, finishTabReorder, tabSignature]);
useEffect(() => {
const onKeyDown = (event: KeyboardEvent) => {
- if (event.key !== "Escape" || !tabReorderState.current) return;
+ const state = tabReorderState.current;
+ if (event.key !== "Escape" || !state) return;
event.preventDefault();
+ suppressedTabClickPointerIdsRef.current.add(state.pointerId);
+ finishTabReorder();
+ };
+ const onWindowBlur = () => {
+ const state = tabReorderState.current;
+ if (state) suppressedTabClickPointerIdsRef.current.add(state.pointerId);
finishTabReorder();
};
+ const onPointerDown = (event: PointerEvent) => {
+ // A reused pointer id starts a new gesture; unrelated pointers do not
+ // clear a canceled gesture's pending click suppression.
+ suppressedTabClickPointerIdsRef.current.delete(event.pointerId);
+ };
+ const onClick = (event: MouseEvent) => {
+ if (
+ event.detail === 0 ||
+ !("pointerId" in event) ||
+ typeof event.pointerId !== "number" ||
+ !suppressedTabClickPointerIdsRef.current.has(event.pointerId)
+ ) {
+ return;
+ }
+ suppressedTabClickPointerIdsRef.current.delete(event.pointerId);
+ if (
+ !(event.target instanceof Element) ||
+ !event.target.closest('[role="tab"]')
+ ) {
+ return;
+ }
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ };
window.addEventListener("keydown", onKeyDown);
+ window.addEventListener("blur", onWindowBlur);
+ window.addEventListener("pointerdown", onPointerDown, true);
+ window.addEventListener("click", onClick, true);
return () => {
window.removeEventListener("keydown", onKeyDown);
+ window.removeEventListener("blur", onWindowBlur);
+ window.removeEventListener("pointerdown", onPointerDown, true);
+ window.removeEventListener("click", onClick, true);
+ suppressedTabClickPointerIdsRef.current.clear();
finishTabReorder();
};
}, [finishTabReorder]);
@@ -334,10 +387,7 @@ export function WorkPanel({
) {
return;
}
- // A completed drag may not produce a click when released outside the
- // strip. Clear the one-shot suppression before the next gesture so that
- // later ordinary clicks are never swallowed.
- suppressTabClickRef.current = false;
+ // Pointer click suppression is armed only when this drag completes.
const updateDropTarget = (state: WorkPanelTabReorderState) => {
const strip = tabStripRef.current;
@@ -433,7 +483,6 @@ export function WorkPanel({
return;
}
state.armed = true;
- suppressTabClickRef.current = true;
document.documentElement.setAttribute(
"data-work-panel-tab-reordering",
"true",
@@ -454,7 +503,8 @@ export function WorkPanel({
if (state.targetTabId) {
reorderTab(state.sourceTabId, state.targetTabId, state.insertAfter);
}
- finishTabReorder(true);
+ finishTabReorder();
+ suppressedTabClickPointerIdsRef.current.add(state.pointerId);
return;
}
finishTabReorder();
@@ -462,12 +512,16 @@ export function WorkPanel({
const onCancel = (cancelEvent: PointerEvent) => {
if (tabReorderState.current?.pointerId !== cancelEvent.pointerId) return;
+ suppressedTabClickPointerIdsRef.current.delete(cancelEvent.pointerId);
finishTabReorder();
};
const state: WorkPanelTabReorderState = {
pointerId: event.pointerId,
sourceTabId,
+ activeSessionId,
+ activeTabId,
+ tabSignature,
startClientX: event.clientX,
startClientY: event.clientY,
lastClientX: event.clientX,
@@ -485,7 +539,7 @@ export function WorkPanel({
window.addEventListener("pointerup", onUp, true);
window.addEventListener("pointercancel", onCancel, true);
},
- [finishTabReorder, reorderTab],
+ [activeSessionId, activeTabId, finishTabReorder, reorderTab, tabSignature],
);
const selectTool = useCallback(
@@ -801,13 +855,7 @@ export function WorkPanel({
title={tab.resource ?? label}
onPointerDown={(event) => beginTabReorder(event, tab.id)}
onDragStart={(event) => event.preventDefault()}
- onClick={() => {
- if (suppressTabClickRef.current) {
- suppressTabClickRef.current = false;
- return;
- }
- activateTab(tab.id);
- }}
+ onClick={() => activateTab(tab.id)}
onAuxClick={(event) => {
if (event.button !== 1) return;
event.preventDefault();
diff --git a/apps/desktop/src/hooks/use-card-reorder.ts b/apps/desktop/src/hooks/use-card-reorder.ts
index e52fd6c6b..c2f8092f1 100644
--- a/apps/desktop/src/hooks/use-card-reorder.ts
+++ b/apps/desktop/src/hooks/use-card-reorder.ts
@@ -22,15 +22,20 @@ export function useCardReorder(
const latest = useRef({ busy, move });
latest.current = { busy, move };
const [draggingId, setDraggingId] = useState<string | null>(null);
- const suppressClick = useRef(false);
+ const suppressedClickPointerIds = useRef(new Set<number>());
const disabled = busy || items.length < 2;
const cancel = () => {
- drag.current?.cleanup();
+ const current = drag.current;
+ if (current) suppressedClickPointerIds.current.delete(current.pointerId);
+ current?.cleanup();
drag.current = null;
setDraggingId(null);
};
- useEffect(() => () => { drag.current?.cleanup(); }, []);
+ useEffect(() => () => {
+ drag.current?.cleanup();
+ suppressedClickPointerIds.current.clear();
+ }, []);
useEffect(() => {
const current = drag.current;
if (current && (busy || current.rows.length !== items.length || current.rows.some((row, index) => row.id !== items[index]?.id))) cancel();
@@ -48,14 +53,21 @@ export function useCardReorder(
},
onDragStart(event) { event.preventDefault(); },
onClickCapture(event) {
- if (suppressClick.current) {
- suppressClick.current = false;
- event.preventDefault();
- event.stopPropagation();
+ if (event.detail === 0) return;
+ const nativeEvent = event.nativeEvent;
+ if (
+ !("pointerId" in nativeEvent) ||
+ typeof nativeEvent.pointerId !== "number" ||
+ !suppressedClickPointerIds.current.has(nativeEvent.pointerId)
+ ) {
+ return;
}
+ suppressedClickPointerIds.current.delete(nativeEvent.pointerId);
+ event.preventDefault();
+ event.stopPropagation();
},
onPointerDown(event) {
- suppressClick.current = false;
+ suppressedClickPointerIds.current.delete(event.pointerId);
if (disabled || event.button !== 0 || drag.current) return;
const target = event.target as Element;
if (target.closest("button, input, select, textarea, a, [contenteditable=true]")) return;
@@ -146,7 +158,6 @@ export function useCardReorder(
source.node.style.willChange = "transform";
setDraggingId(id);
}
- suppressClick.current = true;
next.preventDefault();
schedule();
};
@@ -157,8 +168,12 @@ export function useCardReorder(
update();
const destination = current.rows[current.index];
const shouldMove = current.armed && current.index !== sourceIndex;
- cancel();
- if (shouldMove && !latest.current.busy) {
+ const shouldSuppressClick = current.armed;
+ current.cleanup();
+ drag.current = null;
+ setDraggingId(null);
+ if (shouldSuppressClick) suppressedClickPointerIds.current.add(current.pointerId);
+ if (shouldMove && destination && !latest.current.busy) {
latest.current.move(id, destination.id, current.index > sourceIndex ? "after" : "before");
}
};
diff --git a/package.json b/package.json
index 8f984e363..4b4e8092a 100644
--- a/package.json
+++ b/package.json
@@ -42,6 +42,7 @@
"test:e2e:settings-scroll": "node scripts/e2e-settings-scroll.mjs",
"test:e2e:layout": "node scripts/e2e-three-column-layout.mjs",
"test:e2e:window-controls": "node scripts/e2e-window-controls.mjs",
+ "test:e2e:work-panel-reorder": "node scripts/e2e-work-panel-reorder.mjs",
"test:e2e:supervision": "node scripts/e2e-supervision.mjs",
"test:e2e:subagents": "node scripts/e2e-subagents.mjs",
"test:e2e:subagent-models": "node scripts/e2e-subagent-models.mjs",
diff --git a/scripts/e2e-work-panel-reorder.mjs b/scripts/e2e-work-panel-reorder.mjs
new file mode 100644
index 000000000..795055ab4
--- /dev/null
+++ b/scripts/e2e-work-panel-reorder.mjs
@@ -0,0 +1,88 @@
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { createRequire } from "node:module";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { resolveElectronBinary } from "./e2e/boot.mjs";
+
+const root = join(dirname(fileURLToPath(import.meta.url)), "..");
+const require = createRequire(join(root, "packages/agent-runtime/package.json"));
+const { build } = require("esbuild");
+const { electronBinary } = resolveElectronBinary(root);
+const temp = await mkdtemp(join(tmpdir(), "pi-work-panel-reorder-"));
+try {
+ await build({
+ entryPoints: [join(root, "scripts/e2e/work-panel-reorder.tsx")],
+ outfile: join(temp, "renderer.js"),
+ bundle: true,
+ platform: "browser",
+ format: "iife",
+ jsx: "automatic",
+ define: { "process.env.NODE_ENV": '"production"' },
+ loader: { ".css": "empty" },
+ alias: {
+ "@pi-desktop/i18n": join(root, "packages/i18n/src/index.ts"),
+ react: join(root, "apps/desktop/node_modules/react"),
+ "react-dom": join(root, "apps/desktop/node_modules/react-dom"),
+ },
+ nodePaths: [join(root, "apps/desktop/node_modules")],
+ });
+ await writeFile(
+ join(temp, "index.html"),
+ '<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src \'self\'; style-src \'self\' \'unsafe-inline\'"><title>Work panel reorder regression</title><body><script src="renderer.js"></script>',
+ );
+ await writeFile(
+ join(temp, "main.cjs"),
+ `
+const { app, BrowserWindow } = require("electron");
+const path = require("node:path");
+app.setPath("userData", path.join(__dirname, "profile"));
+app.whenReady().then(async () => {
+ const window = new BrowserWindow({ show: false, width: 1000, height: 800, webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false } });
+ window.webContents.on("console-message", (event) => console.error(event.message));
+ try {
+ await window.loadFile(path.join(__dirname, "index.html"));
+ const result = await window.webContents.executeJavaScript("globalThis.workPanelReorderProbe()");
+ console.log("WORK_PANEL_REORDER_PROBE " + JSON.stringify(result));
+ app.exit(result?.ok === true ? 0 : 1);
+ } catch (error) {
+ console.error("WORK_PANEL_REORDER_PROBE " + JSON.stringify({ ok: false, error: String(error) }));
+ app.exit(1);
+ }
+});
+`,
+ );
+ const env = { ...process.env };
+ delete env.ELECTRON_RUN_AS_NODE;
+ const child = spawn(electronBinary, [join(temp, "main.cjs")], {
+ env,
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+ let output = "";
+ for (const stream of [child.stdout, child.stderr])
+ stream.on("data", (data) => {
+ output += data;
+ });
+ const timeout = setTimeout(() => child.kill("SIGKILL"), 45_000);
+ let code;
+ try {
+ code = await new Promise((resolve, reject) => {
+ child.once("error", reject);
+ child.once("close", resolve);
+ });
+ } finally {
+ clearTimeout(timeout);
+ }
+ const line = output
+ .split(/\r?\n/)
+ .find((line) => line.startsWith("WORK_PANEL_REORDER_PROBE "));
+ assert(line, `renderer returned no result (exit=${code}): ${output.slice(-4000)}`);
+ const result = JSON.parse(line.slice("WORK_PANEL_REORDER_PROBE ".length));
+ console.log(line);
+ assert.equal(code, 0, output.slice(-6000));
+ assert.equal(result.ok, true);
+} finally {
+ await rm(temp, { recursive: true, force: true });
+}
diff --git a/scripts/e2e/work-panel-reorder.tsx b/scripts/e2e/work-panel-reorder.tsx
new file mode 100644
index 000000000..a6ff9ee2c
--- /dev/null
+++ b/scripts/e2e/work-panel-reorder.tsx
@@ -0,0 +1,348 @@
+import { createRoot } from "react-dom/client";
+import { flushSync } from "react-dom";
+import { createInstance } from "i18next";
+import { I18nextProvider } from "react-i18next";
+import { catalogs } from "@pi-desktop/i18n";
+import { WorkPanel } from "../../apps/desktop/src/components/workpanel/WorkPanel";
+import { useCardReorder } from "../../apps/desktop/src/hooks/use-card-reorder";
+import { useAppStore } from "../../apps/desktop/src/stores/app-store";
+import type { WorkPanelTab } from "../../apps/desktop/src/lib/work-panel-tabs";
+
+declare global {
+ var workPanelReorderProbe: () => Promise<{ ok: true }>;
+}
+
+const assert = (condition: unknown, message: string) => {
+ if (!condition) throw new Error(message);
+};
+const launcher: WorkPanelTab = { id: "new:shared", kind: "new" };
+const review: WorkPanelTab = { id: "review", kind: "review" };
+const file: WorkPanelTab = {
+ id: "file:src/a.txt",
+ kind: "file",
+ resource: "src/a.txt",
+};
+const tabs = [launcher, review, file];
+const cardItems = [{ id: "one" }, { id: "two" }, { id: "three" }];
+
+function CardFixture({ moved }: { moved: (id: string) => void }) {
+ const reorder = useCardReorder(cardItems, false, (id) => moved(id));
+ return (
+ <ul>
+ {cardItems.map(({ id }) => (
+ <li key={id} ref={reorder.rowRef(id)} {...reorder.rowEvents(id)}>
+ {id}
+ </li>
+ ))}
+ </ul>
+ );
+}
+
+function pointer(type: string, pointerId: number, x: number, y: number) {
+ return new PointerEvent(type, {
+ pointerId,
+ pointerType: "mouse",
+ button: 0,
+ buttons: type === "pointerup" ? 0 : 1,
+ clientX: x,
+ clientY: y,
+ bubbles: true,
+ cancelable: true,
+ });
+}
+
+function clickPointer(pointerId: number) {
+ return new PointerEvent("click", {
+ pointerId,
+ detail: 1,
+ bubbles: true,
+ cancelable: true,
+ });
+}
+
+function setPanelState(
+ sessionId: string,
+ currentTabs: WorkPanelTab[],
+ reorderCalls: Array<{ source: string; target: string; after: boolean }>,
+ activations: string[],
+) {
+ useAppStore.setState({
+ activeSessionId: sessionId,
+ workPanelTabs: currentTabs,
+ activeWorkPanelTabId: launcher.id,
+ pluginViews: [],
+ workPanelWidth: 360,
+ activateWorkPanelTab: (tabId) => {
+ activations.push(tabId);
+ useAppStore.setState({ activeWorkPanelTabId: tabId });
+ },
+ reorderWorkPanelTabs: (source, target, after) => {
+ reorderCalls.push({ source, target, after });
+ },
+ });
+}
+
+function CardRows({ host }: { host: HTMLElement }) {
+ return [...host.querySelectorAll<HTMLLIElement>("li")];
+}
+
+globalThis.workPanelReorderProbe = async () => {
+ const previousStore = useAppStore.getState();
+ const panelHost = document.createElement("div");
+ const cardHost = document.createElement("div");
+ panelHost.style.cssText = "width: 900px; height: 400px;";
+ cardHost.style.cssText = "width: 400px; height: 200px;";
+ document.body.append(panelHost, cardHost);
+
+ const frameCallbacks = new Map<number, FrameRequestCallback>();
+ let nextFrameId = 0;
+ const nativeRequestFrame = window.requestAnimationFrame;
+ const nativeCancelFrame = window.cancelAnimationFrame;
+ const originalElementFromPoint = document.elementFromPoint.bind(document);
+ const i18n = createInstance();
+ await i18n.init({
+ lng: "en",
+ fallbackLng: "en",
+ resources: { en: { translation: catalogs.en } },
+ interpolation: { escapeValue: false },
+ });
+
+ const uncaught: unknown[] = [];
+ const workPanelRoot = createRoot(panelHost, {
+ onUncaughtError: (error) => uncaught.push(error),
+ });
+ const cardRoot = createRoot(cardHost, {
+ onUncaughtError: (error) => uncaught.push(error),
+ });
+ const reorderCalls: Array<{ source: string; target: string; after: boolean }> = [];
+ const activations: string[] = [];
+ const cardMoves: string[] = [];
+ let targetTabId = review.id;
+
+ try {
+ setPanelState("session-a", tabs, reorderCalls, activations);
+ flushSync(() =>
+ workPanelRoot.render(
+ <I18nextProvider i18n={i18n}>
+ <WorkPanel containerWidth={900} sidebarCollapsed />
+ </I18nextProvider>,
+ ),
+ );
+ flushSync(() => cardRoot.render(<CardFixture moved={(id) => cardMoves.push(id)} />));
+ assert(panelHost.querySelector('[role="tab"][aria-selected="true"]'), "active launcher tab did not render");
+
+ window.requestAnimationFrame = (callback) => {
+ const id = ++nextFrameId;
+ frameCallbacks.set(id, callback);
+ return id;
+ };
+ window.cancelAnimationFrame = (id) => {
+ frameCallbacks.delete(id);
+ };
+
+ const configureGeometry = () => {
+ const strip = panelHost.querySelector<HTMLDivElement>(".work-panel-tab-strip");
+ assert(strip, "work panel tab strip missing");
+ strip.getBoundingClientRect = () => new DOMRect(0, 0, 100, 40);
+ Object.defineProperty(strip, "scrollWidth", { configurable: true, value: 300 });
+ Object.defineProperty(strip, "clientWidth", { configurable: true, value: 100 });
+ for (const tab of panelHost.querySelectorAll<HTMLElement>("[data-work-panel-tab-id]")) {
+ tab.getBoundingClientRect = () => new DOMRect(0, 0, 100, 40);
+ }
+ document.elementFromPoint = () =>
+ [...panelHost.querySelectorAll<HTMLElement>("[data-work-panel-tab-id]")].find(
+ (tab) => tab.dataset.workPanelTabId === targetTabId,
+ ) ?? null;
+ };
+ const buttonFor = (tabId: string) => {
+ const tab = [...panelHost.querySelectorAll<HTMLElement>("[data-work-panel-tab-id]")].find(
+ (candidate) => candidate.dataset.workPanelTabId === tabId,
+ );
+ const button = tab?.querySelector<HTMLButtonElement>('[role="tab"]');
+ assert(button, `tab button missing: ${tabId}`);
+ return button;
+ };
+ const beginPanelDrag = (pointerId: number, target: string) => {
+ targetTabId = target;
+ configureGeometry();
+ flushSync(() =>
+ buttonFor(launcher.id).dispatchEvent(pointer("pointerdown", pointerId, 20, 20)),
+ );
+ flushSync(() => window.dispatchEvent(pointer("pointermove", pointerId, 99, 20)));
+ assert(
+ document.documentElement.getAttribute("data-work-panel-tab-reordering") === "true",
+ "pointer movement did not arm tab reorder",
+ );
+ assert(panelHost.querySelector(".work-panel-tab.is-dragging"), "dragging tab state did not render");
+ assert(frameCallbacks.size === 1, "edge drag did not schedule exactly one auto-scroll frame");
+ };
+ const releasePanelDrag = (pointerId: number) => {
+ flushSync(() => window.dispatchEvent(pointer("pointerup", pointerId, 99, 20)));
+ };
+
+ // Session changes cancel an armed drag even with the same tab ids and order.
+ beginPanelDrag(11, review.id);
+ flushSync(() => setPanelState("session-b", tabs, reorderCalls, activations));
+ assert(!document.documentElement.hasAttribute("data-work-panel-tab-reordering"), "session change left the reorder marker set");
+ assert(!panelHost.querySelector(".work-panel-tab.is-dragging"), "session change left the source tab dragging");
+ assert(frameCallbacks.size === 0, "session change retained the auto-scroll frame");
+ // Neither an unrelated pointerdown nor a keyboard click may clear pointer 11's latch.
+ flushSync(() => window.dispatchEvent(pointer("pointerdown", 99, 20, 20)));
+ flushSync(() => buttonFor(launcher.id).click());
+ releasePanelDrag(11);
+ const staleSessionClick = clickPointer(11);
+ flushSync(() => buttonFor(review.id).dispatchEvent(staleSessionClick));
+ assert(staleSessionClick.defaultPrevented, "session-canceled drag click was not suppressed after unrelated input");
+ assert(useAppStore.getState().activeWorkPanelTabId === launcher.id, "stale session click activated the matching tab");
+ assert(reorderCalls.length === 0, "stale session drag reordered tabs with matching ids");
+
+ // Even a press that never crosses the drag threshold belongs to the old context.
+ flushSync(() => setPanelState("session-a", tabs, reorderCalls, activations));
+ flushSync(() => buttonFor(launcher.id).dispatchEvent(pointer("pointerdown", 15, 20, 20)));
+ flushSync(() => setPanelState("session-b", tabs, reorderCalls, activations));
+ flushSync(() => useAppStore.setState({ activeWorkPanelTabId: file.id }));
+ releasePanelDrag(15);
+ const staleUnarmedClick = clickPointer(15);
+ flushSync(() => buttonFor(launcher.id).dispatchEvent(staleUnarmedClick));
+ assert(staleUnarmedClick.defaultPrevented, "unarmed stale pointer click activated a new context tab");
+ assert(useAppStore.getState().activeWorkPanelTabId === file.id, "unarmed stale click changed the active tab");
+
+ // A tab-order change cancels the drag but preserves the node under the release target.
+ flushSync(() => setPanelState("session-a", tabs, reorderCalls, activations));
+ beginPanelDrag(12, review.id);
+ flushSync(() => setPanelState("session-a", [launcher, file, review], reorderCalls, activations));
+ assert(!document.documentElement.hasAttribute("data-work-panel-tab-reordering"), "tab-order change left the reorder marker set");
+ assert(frameCallbacks.size === 0, "tab-order change retained the auto-scroll frame");
+ releasePanelDrag(12);
+ const staleOrderClick = clickPointer(12);
+ flushSync(() => buttonFor(review.id).dispatchEvent(staleOrderClick));
+ assert(staleOrderClick.defaultPrevented, "tab-order-canceled drag click was not suppressed");
+ assert(useAppStore.getState().activeWorkPanelTabId === launcher.id, "stale tab-order click activated the target");
+ assert(reorderCalls.length === 0, "tab-order change allowed a stale reorder");
+
+ // A separate active-tab change also invalidates the gesture and its later click.
+ flushSync(() => setPanelState("session-a", tabs, reorderCalls, activations));
+ beginPanelDrag(14, review.id);
+ flushSync(() => useAppStore.setState({ activeWorkPanelTabId: file.id }));
+ assert(!document.documentElement.hasAttribute("data-work-panel-tab-reordering"), "active-tab change left the reorder marker set");
+ assert(frameCallbacks.size === 0, "active-tab change retained the auto-scroll frame");
+ releasePanelDrag(14);
+ const staleActiveTabClick = clickPointer(14);
+ flushSync(() => buttonFor(review.id).dispatchEvent(staleActiveTabClick));
+ assert(staleActiveTabClick.defaultPrevented, "active-tab-canceled drag click was not suppressed");
+ assert(useAppStore.getState().activeWorkPanelTabId === file.id, "stale click reverted the active tab");
+
+ // Window blur cancels the complete interaction lifecycle and only suppresses its pointer click.
+ flushSync(() => setPanelState("session-a", tabs, reorderCalls, activations));
+ beginPanelDrag(13, review.id);
+ flushSync(() => window.dispatchEvent(new Event("blur")));
+ assert(!document.documentElement.hasAttribute("data-work-panel-tab-reordering"), "blur left the reorder marker set");
+ assert(!panelHost.querySelector(".work-panel-tab.is-dragging"), "blur left the tab visually dragging");
+ assert(frameCallbacks.size === 0, "blur retained the auto-scroll frame");
+ releasePanelDrag(13);
+ assert(reorderCalls.length === 0, "blurred gesture reordered tabs");
+ const afterBlurClick = clickPointer(13);
+ flushSync(() => buttonFor(review.id).dispatchEvent(afterBlurClick));
+ assert(afterBlurClick.defaultPrevented, "blur did not suppress its canceled pointer click");
+ assert(useAppStore.getState().activeWorkPanelTabId === launcher.id, "blurred pointer click activated a tab");
+ flushSync(() => buttonFor(review.id).click());
+ assert(useAppStore.getState().activeWorkPanelTabId === review.id, "keyboard click was swallowed after blur");
+
+ // Only the click generated by the completed drag's own pointer is ignored.
+ flushSync(() => setPanelState("session-a", tabs, reorderCalls, activations));
+ activations.length = 0;
+ beginPanelDrag(21, review.id);
+ releasePanelDrag(21);
+ assert(reorderCalls.length === 1, "completed drag did not call the tab reorder action");
+ assert(frameCallbacks.size === 1, "successful reorder should retain only its source-focus frame");
+ for (const [id, callback] of frameCallbacks) callback(performance.now());
+ frameCallbacks.clear();
+ const dragClick = clickPointer(21);
+ flushSync(() => buttonFor(review.id).dispatchEvent(dragClick));
+ assert(dragClick.defaultPrevented, "completed drag click was not suppressed");
+ assert(activations.length === 0, "completed drag click activated a different tab");
+ assert(useAppStore.getState().activeWorkPanelTabId === launcher.id, "completed drag changed the active tab");
+
+ flushSync(() => setPanelState("session-a", tabs, reorderCalls, activations));
+ activations.length = 0;
+ beginPanelDrag(22, review.id);
+ releasePanelDrag(22);
+ for (const [id, callback] of frameCallbacks) callback(performance.now());
+ frameCallbacks.clear();
+ flushSync(() => buttonFor(review.id).click());
+ assert(useAppStore.getState().activeWorkPanelTabId === review.id, "keyboard-style activation was swallowed after a drag");
+
+ flushSync(() => setPanelState("session-a", tabs, reorderCalls, activations));
+ activations.length = 0;
+ beginPanelDrag(23, review.id);
+ releasePanelDrag(23);
+ for (const [id, callback] of frameCallbacks) callback(performance.now());
+ frameCallbacks.clear();
+ const unrelatedClick = clickPointer(99);
+ flushSync(() => buttonFor(review.id).dispatchEvent(unrelatedClick));
+ assert(!unrelatedClick.defaultPrevented, "an unrelated pointer click was suppressed");
+ assert(useAppStore.getState().activeWorkPanelTabId === review.id, "unrelated click failed to activate its tab");
+
+ // Exercise useCardReorder with its real React bindings: cancellation by all
+ // three supported paths must not leave a pointer-click latch behind.
+ const cardRows = () => CardRows({ host: cardHost });
+ const cancelCardDrag = (kind: "pointercancel" | "escape" | "blur", pointerId: number) => {
+ const source = cardRows()[0];
+ flushSync(() => source.dispatchEvent(pointer("pointerdown", pointerId, 10, 10)));
+ flushSync(() => window.dispatchEvent(pointer("pointermove", pointerId, 20, 20)));
+ assert(frameCallbacks.size === 1, `${kind} test did not arm the card drag`);
+ if (kind === "pointercancel") {
+ flushSync(() => window.dispatchEvent(pointer("pointercancel", pointerId, 20, 20)));
+ } else if (kind === "escape") {
+ flushSync(() => window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true })));
+ } else {
+ flushSync(() => window.dispatchEvent(new Event("blur")));
+ }
+ assert(frameCallbacks.size === 0, `${kind} retained the card animation frame`);
+ assert(!source.style.transform, `${kind} left a card transform behind`);
+ const click = clickPointer(pointerId);
+ flushSync(() => source.dispatchEvent(click));
+ assert(!click.defaultPrevented, `${kind} cancellation left suppressClick latched`);
+ };
+ cancelCardDrag("pointercancel", 31);
+ cancelCardDrag("escape", 32);
+ cancelCardDrag("blur", 33);
+
+ const cardSource = cardRows()[0];
+ const secondCard = cardRows()[1];
+ flushSync(() => cardSource.dispatchEvent(pointer("pointerdown", 34, 10, 10)));
+ flushSync(() => window.dispatchEvent(pointer("pointermove", 34, 20, 20)));
+ flushSync(() => window.dispatchEvent(pointer("pointerup", 34, 20, 20)));
+ const keyboardCardClick = new PointerEvent("click", { pointerId: 0, detail: 0, bubbles: true, cancelable: true });
+ flushSync(() => secondCard.dispatchEvent(keyboardCardClick));
+ assert(!keyboardCardClick.defaultPrevented, "keyboard activation was swallowed by card drag suppression");
+ const completedCardClick = clickPointer(34);
+ flushSync(() => cardSource.dispatchEvent(completedCardClick));
+ assert(completedCardClick.defaultPrevented, "keyboard click cleared the completed card drag latch");
+
+ const secondCardSource = cardRows()[1];
+ flushSync(() => secondCardSource.dispatchEvent(pointer("pointerdown", 35, 10, 30)));
+ flushSync(() => window.dispatchEvent(pointer("pointermove", 35, 20, 40)));
+ flushSync(() => window.dispatchEvent(pointer("pointerup", 35, 20, 40)));
+ flushSync(() => secondCard.dispatchEvent(pointer("pointerdown", 99, 10, 30)));
+ flushSync(() => window.dispatchEvent(pointer("pointercancel", 99, 10, 30)));
+ const completedCardClickAfterOtherPointer = clickPointer(35);
+ flushSync(() => secondCardSource.dispatchEvent(completedCardClickAfterOtherPointer));
+ assert(completedCardClickAfterOtherPointer.defaultPrevented, "another row pointerdown cleared the completed card drag latch");
+
+ assert(uncaught.length === 0, `React render failed: ${uncaught.map(String).join(", ")}`);
+ return { ok: true };
+ } finally {
+ flushSync(() => {
+ workPanelRoot.unmount();
+ cardRoot.unmount();
+ });
+ window.requestAnimationFrame = nativeRequestFrame;
+ window.cancelAnimationFrame = nativeCancelFrame;
+ document.elementFromPoint = originalElementFromPoint;
+ frameCallbacks.clear();
+ panelHost.remove();
+ cardHost.remove();
+ useAppStore.setState(previousStore, true);
+ }
+};