Skip to content

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

fix(work-panel): contain scrolled tab drag exclusions

AR307410fa9df1079
diff --git a/apps/desktop/src/components/workpanel/WorkPanel.tsx b/apps/desktop/src/components/workpanel/WorkPanel.tsx
index 13dc664fd..f553112ae 100644
--- a/apps/desktop/src/components/workpanel/WorkPanel.tsx
+++ b/apps/desktop/src/components/workpanel/WorkPanel.tsx
@@ -818,7 +818,7 @@ function LocalWorkPanel({
<div className="work-panel-tab-strip-wrap">
<div
ref={tabStripRef}
- className="work-panel-tab-strip"
+ className="work-panel-tab-strip no-drag"
role="tablist"
aria-label={t("panel.tabsLabel")}
onWheel={onTabStripWheel}
@@ -838,7 +838,7 @@ function LocalWorkPanel({
return (
<div
className={cx(
- "work-panel-tab no-drag",
+ "work-panel-tab",
selected && "active",
draggingTabId === tab.id && "is-dragging",
dropIndicator?.tabId === tab.id &&
diff --git a/apps/desktop/src/styles/work-panel.css b/apps/desktop/src/styles/work-panel.css
index 6eda9b74f..7e7741a13 100644
--- a/apps/desktop/src/styles/work-panel.css
+++ b/apps/desktop/src/styles/work-panel.css
@@ -191,8 +191,12 @@
display: flex;
min-width: 0;
max-width: 100%;
+ width: max-content;
height: 32px;
- flex: 1 1 auto;
+ /* Only the visible viewport excludes native dragging. Per-tab exclusions
+ escape the overflow clip when scrolled, blocking neighboring titlebars.
+ Keep unused header space outside this content-sized viewport draggable. */
+ flex: 0 1 auto;
align-items: center;
gap: 6px;
overflow-x: auto;
diff --git a/apps/desktop/test/work-panel.test.mjs b/apps/desktop/test/work-panel.test.mjs
index 432a146be..c0f827cd3 100644
--- a/apps/desktop/test/work-panel.test.mjs
+++ b/apps/desktop/test/work-panel.test.mjs
@@ -28,6 +28,14 @@ const panelSource = await readFile(
const transcriptSource = await readTranscriptSource();
const storeSource = await readStoreSource();
const globalStyles = await loadStyles();
+test("only the visible tab viewport excludes native window dragging", () => {
+ assert.match(panelSource, /className="work-panel-tab-strip-wrap"/);
+ assert.match(panelSource, /className="work-panel-tab-strip no-drag"/);
+ assert.doesNotMatch(panelSource, /work-panel-tab no-drag/);
+ assert.doesNotMatch(panelSource, /work-panel-tab-strip-wrap no-drag/);
+ assert.match(globalStyles, /\.work-panel-tab-strip \{[^}]*width:\s*max-content;[^}]*flex:\s*0 1 auto;/s);
+});
+
test("closing a tab restores focus to its neighbor or the new-tab action", () => {
assert.match(panelSource, /const closeTabAndFocus = useCallback/);
assert.match(panelSource, /tabButtonRefs\.current\[nextTab\.id\]\?\.focus/);
@@ -240,7 +248,7 @@ test("work panel uses the fixed-window internal dock", () => {
test("work panel header exposes a scrollable tab strip and direct new-page action", () => {
const headerIndex = panelSource.indexOf('className="work-panel-header"');
- const stripIndex = panelSource.indexOf('className="work-panel-tab-strip"');
+ const stripIndex = panelSource.indexOf('className="work-panel-tab-strip no-drag"');
const actionsIndex = panelSource.indexOf('className="work-panel-actions no-drag"');
const bodyIndex = panelSource.indexOf('<div className="work-panel-body">');
diff --git a/package.json b/package.json
index e38f497ba..99f061716 100644
--- a/package.json
+++ b/package.json
@@ -59,6 +59,7 @@
"test:e2e:window-resize-native": "node scripts/e2e-window-controls.mjs --native-edge-drag",
"test:e2e:window-surface": "node scripts/e2e-window-surface.mjs",
"test:e2e:work-panel-reorder": "node scripts/e2e-work-panel-reorder.mjs",
+ "test:e2e:work-panel-drag": "node scripts/e2e-work-panel-drag.mjs",
"test:e2e:supervision": "node scripts/e2e-supervision.mjs",
"test:e2e:subagents": "node scripts/e2e-subagents.mjs",
"test:e2e:subagent-parent-error": "node scripts/e2e-subagent-parent-error.mjs",
diff --git a/scripts/e2e-work-panel-drag.mjs b/scripts/e2e-work-panel-drag.mjs
new file mode 100644
index 000000000..b0ae5abc2
--- /dev/null
+++ b/scripts/e2e-work-panel-drag.mjs
@@ -0,0 +1,118 @@
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { createRequire } from "node:module";
+import { mkdtemp, readFile, 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";
+
+// Windows' native hit test is required: DOM geometry alone cannot prove that
+// Chromium clipped the excluded drag regions. Python reads only this window.
+assert.equal(process.platform, "win32", "Run the native drag regression on Windows");
+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-drag-"));
+const styles = await Promise.all(["tokens", "base", "chat-shell", "work-panel"].map((name) =>
+ readFile(join(root, "apps/desktop/src/styles/" + name + ".css"), "utf8"),
+));
+await writeFile(join(temp, "style.css"), styles.join("\n"));
+await build({
+ entryPoints: [join(root, "scripts/e2e/work-panel-drag.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>PI Tab Drag Regression</title><link rel="stylesheet" href="style.css"><body><script src="renderer.js"></script>');
+await writeFile(join(temp, "hit-test.py"), [
+ "import ctypes as c, ctypes.wintypes as w, json, sys",
+ "u = c.WinDLL('user32', use_last_error=True)",
+ "u.SetProcessDPIAware()",
+ "u.ClientToScreen.argtypes = [w.HWND, c.POINTER(w.POINT)]",
+ "u.SendMessageTimeoutW.argtypes = [w.HWND, w.UINT, c.c_size_t, c.c_ssize_t, w.UINT, w.UINT, c.POINTER(c.c_size_t)]",
+ "u.SendMessageTimeoutW.restype = c.c_ssize_t",
+ "hwnd, scale = int(sys.argv[1]), float(sys.argv[2])",
+ "origin = w.POINT(0, 0)",
+ "if not u.ClientToScreen(hwnd, c.byref(origin)): raise RuntimeError('ClientToScreen failed')",
+ "points = json.loads(sys.stdin.read())",
+ "for point in points:",
+ " x = origin.x + round(point['x'] * scale)",
+ " y = origin.y + round(point['y'] * scale)",
+ " result = c.c_size_t()",
+ " ok = u.SendMessageTimeoutW(hwnd, 0x84, 0, ((y & 65535) << 16) | (x & 65535), 2, 3000, c.byref(result))",
+ " if not ok: raise RuntimeError('WM_NCHITTEST failed')",
+ " point['actual'] = result.value",
+ "print(json.dumps(points))",
+].join("\n"));
+
+function electronProbe() {
+ const { app, BrowserWindow } = require("electron");
+ const { spawn } = require("node:child_process");
+ const path = require("node:path");
+ app.setPath("userData", path.join(__dirname, "profile"));
+ function nativeHits(hwnd, scale, points) {
+ return new Promise((resolve, reject) => {
+ const child = spawn(process.env.PI_TEST_PYTHON || "python", [path.join(__dirname, "hit-test.py"), hwnd, String(scale)], { windowsHide: true, stdio: ["pipe", "pipe", "pipe"] });
+ let out = "", err = "";
+ child.stdout.on("data", (data) => out += data);
+ child.stderr.on("data", (data) => err += data);
+ child.once("error", reject);
+ child.once("close", (code) => {
+ if (code !== 0) return reject(new Error(err || "Native hit test failed"));
+ try { resolve(JSON.parse(out)); } catch (error) { reject(error); }
+ });
+ child.stdin.end(JSON.stringify(points));
+ });
+ }
+ app.whenReady().then(async () => {
+ const window = new BrowserWindow({ show: false, frame: false, width: 1000, height: 650, webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false } });
+ const results = [];
+ try {
+ await window.loadFile(path.join(__dirname, "index.html"));
+ window.showInactive();
+ const handle = window.getNativeWindowHandle();
+ const hwnd = (handle.length === 8 ? handle.readBigUInt64LE() : BigInt(handle.readUInt32LE())).toString();
+ for (const stage of ["overflow-end", "switch-back", "overflow-start", "keyboard-reorder", "one-tab", "no-tabs"]) {
+ const points = await window.webContents.executeJavaScript("globalThis.workPanelDragProbe(" + JSON.stringify(stage) + ")");
+ await window.webContents.capturePage();
+ const scale = await window.webContents.executeJavaScript("devicePixelRatio");
+ const hits = await nativeHits(hwnd, scale, points);
+ results.push({ stage, hits });
+ const failures = hits.filter((point) => point.actual !== point.expected);
+ if (failures.length) throw new Error(stage + ": " + JSON.stringify(failures));
+ }
+ console.log("WORK_PANEL_DRAG_PROBE " + JSON.stringify({ ok: true, results }));
+ app.exit(0);
+ } catch (error) {
+ console.error("WORK_PANEL_DRAG_PROBE " + JSON.stringify({ ok: false, error: String(error), results }));
+ app.exit(1);
+ }
+ });
+}
+await writeFile(join(temp, "main.cjs"), "(" + electronProbe.toString() + ")();");
+const env = { ...process.env };
+delete env.ELECTRON_RUN_AS_NODE;
+const child = spawn(electronBinary, [join(temp, "main.cjs")], { env, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
+let output = "";
+for (const stream of [child.stdout, child.stderr]) stream.on("data", (data) => output += data);
+const timeout = setTimeout(() => child.kill(), 60_000);
+try {
+ const code = await new Promise((resolve, reject) => { child.once("error", reject); child.once("close", resolve); });
+ const line = output.split(/\r?\n/).find((line) => line.startsWith("WORK_PANEL_DRAG_PROBE "));
+ console.log(line ?? output.slice(-6000));
+ assert.equal(code, 0, output.slice(-6000));
+ assert.ok(line, "Native drag probe did not return results");
+} finally {
+ clearTimeout(timeout);
+ // Retain isolated profiles and evidence for inspection; no user data is used.
+ console.log("Drag regression artifacts: " + temp);
+}
diff --git a/scripts/e2e/work-panel-drag.tsx b/scripts/e2e/work-panel-drag.tsx
new file mode 100644
index 000000000..0a09ca857
--- /dev/null
+++ b/scripts/e2e/work-panel-drag.tsx
@@ -0,0 +1,109 @@
+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 { useAppStore } from "../../apps/desktop/src/stores/app-store";
+import { switchWorkPanelSession } from "../../apps/desktop/src/stores/slices/work-panel-slice";
+
+type HitPoint = { label: string; x: number; y: number; expected: number };
+declare global {
+ var workPanelDragProbe: (stage: string) => Promise<HitPoint[]>;
+}
+const assert = (condition: unknown, message: string) => {
+ if (!condition) throw new Error(message);
+};
+const host = document.createElement("div");
+host.style.cssText = "position:absolute;inset:0 0 0 640px;display:flex";
+const neighbor = document.createElement("div");
+neighbor.className = "drag";
+neighbor.style.cssText = "position:absolute;left:0;top:0;width:640px;height:46px";
+document.body.append(neighbor, host);
+document.documentElement.dataset.platform = "win32";
+const root = createRoot(host);
+const i18n = createInstance();
+const ready = i18n.init({
+ lng: "en",
+ resources: { en: { translation: catalogs.en } },
+ interpolation: { escapeValue: false },
+});
+
+function switchSession(id: string) {
+ flushSync(() => useAppStore.setState((state) => ({
+ ...switchWorkPanelSession(state, id),
+ activeSessionId: id,
+ })));
+}
+function element(selector: string): HTMLElement {
+ const result = host.querySelector<HTMLElement>(selector);
+ if (!result) throw new Error("Missing " + selector);
+ return result;
+}
+function currentTabs() {
+ return useAppStore.getState().workPanelTabs;
+}
+function click(selector: string) {
+ flushSync(() => element(selector).click());
+}
+async function rendered() {
+ await Promise.all(document.getAnimations().map((animation) => animation.finished));
+ await new Promise<void>((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
+}
+
+globalThis.workPanelDragProbe = async (stage) => {
+ if (stage === "overflow-end") {
+ await ready;
+ flushSync(() => {
+ useAppStore.setState({ activeSessionId: "drag-a", workPanelWidth: 360, pluginViews: [] });
+ root.render(<I18nextProvider i18n={i18n}><WorkPanel containerWidth={1000} sidebarCollapsed /></I18nextProvider>);
+ });
+ // Enter through the real header action rather than replacing store methods.
+ for (let i = 0; i < 12; i++) click(".work-panel-new-tab");
+ await rendered();
+ const strip = element(".work-panel-tab-strip");
+ assert(strip.scrollWidth > strip.clientWidth, "tabs did not overflow");
+ assert(strip.scrollLeft > 0, "active tab did not scroll into view");
+ assert(element(".work-panel-tab").getBoundingClientRect().x < 640, "fixture did not reproduce clipped tabs crossing the neighboring titlebar");
+ } else if (stage === "switch-back") {
+ const ids = currentTabs().map((tab) => tab.id).join(",");
+ switchSession("drag-b");
+ click(".work-panel-new-tab");
+ switchSession("drag-a");
+ assert(currentTabs().map((tab) => tab.id).join(",") === ids, "switching back lost the session tab context");
+ } else if (stage === "overflow-start") {
+ click(".work-panel-tab-button");
+ } else if (stage === "keyboard-reorder") {
+ const first = currentTabs()[0].id;
+ flushSync(() => element(".work-panel-tab-button").dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowRight", altKey: true, bubbles: true, cancelable: true })));
+ assert(currentTabs()[1].id === first, "keyboard reorder did not reach the store action");
+ assert(useAppStore.getState().activeWorkPanelTabId === first, "reorder changed the active resource");
+ } else if (stage === "one-tab") {
+ while (currentTabs().length > 1) click(".work-panel-tab-close");
+ } else if (stage === "no-tabs") {
+ click(".work-panel-tab-close");
+ assert(currentTabs().length === 0, "last tab did not close");
+ } else {
+ throw new Error("Unknown drag probe stage: " + stage);
+ }
+ await rendered();
+ const strip = element(".work-panel-tab-strip");
+ const viewport = strip.getBoundingClientRect();
+ const points: HitPoint[] = [
+ { label: "sidebar titlebar", x: 180, y: 23, expected: 2 },
+ { label: "conversation titlebar", x: 450, y: 23, expected: 2 },
+ ];
+ for (const selector of [".work-panel-new-tab", ".work-panel-maximize"]) {
+ const rect = element(selector).getBoundingClientRect();
+ points.push({ label: selector, x: rect.x + rect.width / 2, y: rect.y + rect.height / 2, expected: 1 });
+ }
+ if (currentTabs().length) {
+ points.push({ label: "visible tab", x: viewport.x + Math.min(40, viewport.width / 2), y: 23, expected: 1 });
+ }
+ if (stage === "one-tab" || stage === "no-tabs") {
+ const wrap = element(".work-panel-tab-strip-wrap").getBoundingClientRect();
+ assert(wrap.right - viewport.right > 20, "sparse tabs consume empty draggable header space");
+ points.push({ label: "unused panel header", x: (viewport.right + wrap.right) / 2, y: 23, expected: 2 });
+ }
+ return points;
+};
diff --git a/scripts/e2e/work-panel-reorder.tsx b/scripts/e2e/work-panel-reorder.tsx
index df86018c2..b5fe6d180 100644
--- a/scripts/e2e/work-panel-reorder.tsx
+++ b/scripts/e2e/work-panel-reorder.tsx
@@ -136,8 +136,12 @@ globalThis.workPanelReorderProbe = async () => {
"empty tab-strip space blocks native window dragging",
);
assert(
- [...panelHost.querySelectorAll(".work-panel-tab")].every((tab) => tab.classList.contains("no-drag")),
- "tab interactions must remain outside native window dragging",
+ panelHost.querySelector(".work-panel-tab-strip")?.classList.contains("no-drag"),
+ "the visible tab viewport must keep tabs interactive",
+ );
+ assert(
+ [...panelHost.querySelectorAll(".work-panel-tab")].every((tab) => !tab.classList.contains("no-drag")),
+ "offscreen tabs must not subtract unclipped native drag rectangles",
);
assert(
panelHost.querySelector(".work-panel-actions")?.classList.contains("no-drag"),