Skip to content

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

fix(work-panel): keep the active tab's close button inside the strip

blackEvil217399dd26e5d5d
diff --git a/apps/desktop/src/components/workpanel/WorkPanel.tsx b/apps/desktop/src/components/workpanel/WorkPanel.tsx
index 1802a1ec9..8d4280773 100644
--- a/apps/desktop/src/components/workpanel/WorkPanel.tsx
+++ b/apps/desktop/src/components/workpanel/WorkPanel.tsx
@@ -312,8 +312,31 @@ function LocalWorkPanel({
setNativeSurfaceReadyForExit(true);
}, [exiting]);
+ /**
+ * Reveal one tab's full box — the wrapper, not the button alone. The close
+ * control is a 24px sibling inside that wrapper, so scrolling only the button
+ * leaves the close control clipped by the strip's overflow edge (issue
+ * #1762). The button is the fallback for a tab rendered without a wrapper.
+ */
+ const revealTab = useCallback((tabId: string) => {
+ tabWrapperRefs.current[tabId]?.scrollIntoView({
+ block: "nearest",
+ inline: "nearest",
+ });
+ tabButtonRefs.current[tabId]?.scrollIntoView({
+ block: "nearest",
+ inline: "nearest",
+ });
+ tabCloseButtonRefs.current[tabId]?.scrollIntoView({
+ block: "nearest",
+ inline: "nearest",
+ });
+ }, []);
+
useLayoutEffect(() => {
if (!activeTabId) return;
+ // Inline rather than a helper call: `work-panel.test.mjs` pins this effect
+ // body as the contract for "wrapper, then button, then close control".
tabWrapperRefs.current[activeTabId]?.scrollIntoView({
block: "nearest",
inline: "nearest",
@@ -328,6 +351,18 @@ function LocalWorkPanel({
});
}, [activeTabId, tabs.length]);
+ // A narrowed panel clips a tab that was fully visible a moment ago, and
+ // neither `activeTabId` nor `tabs.length` changes when only the width does —
+ // so the reveal above would not re-run and the close control would stay
+ // clipped after a resize (issue #1762). Observe the strip itself.
+ useLayoutEffect(() => {
+ const strip = tabStripRef.current;
+ if (!strip || !activeTabId || typeof ResizeObserver === "undefined") return;
+ const observer = new ResizeObserver(() => revealTab(activeTabId));
+ observer.observe(strip);
+ return () => observer.disconnect();
+ }, [activeTabId, revealTab]);
+
const finishTabReorder = useCallback(() => {
const state = tabReorderState.current;
if (state) {
@@ -871,6 +906,12 @@ function LocalWorkPanel({
(dropIndicator.insertAfter ? "is-drop-after" : "is-drop-before"),
)}
data-work-panel-tab-id={tab.id}
+ // A partly visible inactive tab reveals its close
+ // control on hover (`.work-panel-tab:hover
+ // .work-panel-tab-close`, styles/work-panel.css:314) —
+ // revealing opacity is not enough when the control sits
+ // outside the strip, so bring the whole box in first.
+ onPointerEnter={() => revealTab(tab.id)}
key={tab.id}
>
<button
diff --git a/apps/desktop/src/styles/work-panel.css b/apps/desktop/src/styles/work-panel.css
index 7e7741a13..5e2a61a94 100644
--- a/apps/desktop/src/styles/work-panel.css
+++ b/apps/desktop/src/styles/work-panel.css
@@ -202,7 +202,10 @@
overflow-x: auto;
overflow-y: hidden;
overscroll-behavior-inline: contain;
- scroll-padding-inline: 2px;
+ /* Reserve the close button's width at the inline end so a scrolled-to tab
+ never lands with its sibling close button clipped by the overflow edge
+ (issue #1762). */
+ scroll-padding-inline: 2px 24px;
}
.work-panel-tab-strip::-webkit-scrollbar {
diff --git a/apps/desktop/test/work-panel.test.mjs b/apps/desktop/test/work-panel.test.mjs
index b5e2de9ed..9f8719ae9 100644
--- a/apps/desktop/test/work-panel.test.mjs
+++ b/apps/desktop/test/work-panel.test.mjs
@@ -717,3 +717,22 @@ test("preview mode keeps shell actions and restores routes before navigation", (
assert.match(globalStyles, /\.work-panel-header \{[^}]*app-region:\s*drag;/);
assert.match(globalStyles, /\.app-shell\.work-panel-maximized \.work-panel-main \{[^}]*var\(--ds-bg-dock-raised\) 0 var\(--ds-toolbar-height\)/);
});
+
+test("the active tab scrolls its wrapper so the sibling close button stays visible", () => {
+ // Issue #1762: the close button is a sibling of the tab button inside the
+ // tab wrapper. Scrolling the button with `inline: "nearest"` moves nothing
+ // once the button is visible, leaving the close button clipped outside the
+ // strip's overflow edge.
+ // Upstream #1775 introduced the wrapper refs; this branch keeps them and
+ // adds the shared reveal helper plus the resize/hover paths.
+ assert.match(panelSource, /const tabWrapperRefs = useRef<Record<string, HTMLDivElement \| null>>\(\{\}\)/);
+ assert.match(
+ panelSource,
+ /tabWrapperRefs\.current\[tabId\]\?\.scrollIntoView\(/,
+ );
+ assert.match(panelSource, /tabWrapperRefs\.current\[tab\.id\] = node/);
+ // The strip reserves the close button's width at the inline end as a
+ // structural guarantee against sub-pixel clipping.
+ const strip = globalStyles.match(/\.work-panel-tab-strip \{[^}]*\}/)?.[0] ?? "";
+ assert.match(strip, /scroll-padding-inline:\s*2px 24px;/);
+});
diff --git a/package.json b/package.json
index 2efe64d37..f3e8686a5 100644
--- a/package.json
+++ b/package.json
@@ -66,6 +66,7 @@
"test:e2e:work-panel-reorder": "node scripts/e2e-work-panel-reorder.mjs",
"test:e2e:browser-local-files": "node scripts/e2e-browser-local-file-access.mjs",
"test:e2e:work-panel-drag": "node scripts/e2e-work-panel-drag.mjs",
+ "test:e2e:work-panel-tab-close": "node scripts/e2e-work-panel-tab-close.mjs",
"test:e2e:supervision": "node scripts/e2e-supervision.mjs",
"test:e2e:subagents": "node scripts/e2e-subagents.mjs",
"test:e2e:send-now-subagents": "node scripts/e2e-send-now-subagents.mjs",
diff --git a/scripts/e2e-work-panel-tab-close.mjs b/scripts/e2e-work-panel-tab-close.mjs
new file mode 100644
index 000000000..14905423a
--- /dev/null
+++ b/scripts/e2e-work-panel-tab-close.mjs
@@ -0,0 +1,122 @@
+#!/usr/bin/env node
+/**
+ * Renderer-level geometry regression for #1762.
+ *
+ * The maintainer's review on #1769 asked for proof that the active tab's close
+ * control sits inside the strip viewport and receives pointer hits — after a
+ * narrow panel, after a resize that keeps the same active tab, and on hover of
+ * a partially visible inactive tab. Source-contract tests cannot show any of
+ * that, so this runs the real WorkPanel in Electron and measures.
+ *
+ * Cross-platform: DOM geometry + elementFromPoint. Native Win32 hit testing
+ * for drag regions remains in scripts/e2e-work-panel-drag.mjs.
+ */
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { createRequire } from "node:module";
+import { mkdtemp, readFile, writeFile, rm } 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-tab-close-"));
+
+try {
+ 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-tab-close.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/shared": join(root, "packages/shared/src/index.ts"),
+ "@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"),
+ i18next: join(root, "apps/desktop/node_modules/i18next"),
+ "react-i18next": join(root, "apps/desktop/node_modules/react-i18next"),
+ },
+ 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 Close Regression</title><link rel="stylesheet" href="style.css"><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 win = new BrowserWindow({ show: false, width: 1600, height: 700,
+ webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false } });
+ win.webContents.on("console-message", (event) => console.error(event.message));
+ try {
+ await win.loadFile(path.join(__dirname, "index.html"));
+ for (const stage of ["narrow-active", "resize-same-tab", "hover-inactive"]) {
+ const result = await win.webContents.executeJavaScript(
+ "window.tabCloseProbe(" + JSON.stringify(stage) + ")");
+ console.log("TAB_CLOSE " + JSON.stringify(result));
+ }
+ app.exit(0);
+ } catch (error) { console.error(error); app.exit(1); }
+});
+`,
+ );
+
+ const child = spawn(electronBinary, [join(temp, "main.cjs")], {
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+ let stdout = "";
+ let stderr = "";
+ child.stdout.on("data", (chunk) => (stdout += chunk));
+ child.stderr.on("data", (chunk) => (stderr += chunk));
+ const code = await new Promise((resolve) => child.on("exit", resolve));
+ if (code !== 0) {
+ console.error(stderr);
+ assert.fail("electron probe failed with exit code " + code);
+ }
+
+ const results = stdout
+ .split("\n")
+ .filter((line) => line.startsWith("TAB_CLOSE "))
+ .map((line) => JSON.parse(line.slice("TAB_CLOSE ".length)));
+ assert.equal(results.length, 3, "expected three probe stages");
+
+ for (const result of results) {
+ console.log(
+ `${result.stage}: strip [${result.stripLeft.toFixed(1)}, ${result.stripRight.toFixed(1)}] ` +
+ `close [${result.closeLeft.toFixed(1)}, ${result.closeRight.toFixed(1)}] ` +
+ `inside=${result.insideStrip} hit=${result.hitIsClose || result.hitIsDescendant}`,
+ );
+ assert.ok(
+ result.insideStrip,
+ `${result.stage}: close control escapes the strip viewport`,
+ );
+ assert.ok(
+ result.hitIsClose || result.hitIsDescendant,
+ `${result.stage}: close control is not the pointer hit target`,
+ );
+ }
+ console.log("tab close geometry: PASS");
+} finally {
+ await rm(temp, { recursive: true, force: true });
+}
diff --git a/scripts/e2e/work-panel-tab-close.tsx b/scripts/e2e/work-panel-tab-close.tsx
new file mode 100644
index 000000000..5abf5b384
--- /dev/null
+++ b/scripts/e2e/work-panel-tab-close.tsx
@@ -0,0 +1,217 @@
+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";
+
+/*
+ Renderer-level regression for #1762: the active tab's close control must sit
+ inside the tab strip's viewport and be the element the pointer would hit,
+ after a narrow panel and after a resize that keeps the same active tab.
+
+ Source assertions cannot prove this — the maintainer asked for actual
+ geometry and hit target, and DOM geometry plus `elementFromPoint` is what
+ this environment can honestly measure. Native Win32 hit testing stays in
+ scripts/e2e-work-panel-drag.mjs for the drag regions.
+*/
+
+type CloseGeometry = {
+ stage: string;
+ tabId: string;
+ stripLeft: number;
+ stripRight: number;
+ closeLeft: number;
+ closeRight: number;
+ insideStrip: boolean;
+ hitIsClose: boolean;
+ hitIsDescendant: boolean;
+};
+declare global {
+ var tabCloseProbe: (stage: string) => Promise<CloseGeometry>;
+}
+
+const assert = (condition: unknown, message: string) => {
+ if (!condition) throw new Error(message);
+};
+
+const host = document.createElement("div");
+host.style.cssText = "position:absolute;left:0;top:0;height:600px;display:flex";
+document.body.append(host);
+const root = createRoot(host);
+const i18n = createInstance();
+const ready = i18n.init({
+ lng: "en",
+ resources: { en: { translation: catalogs.en } },
+ interpolation: { escapeValue: false },
+});
+
+function element(selector: string): HTMLElement {
+ const found = host.querySelector<HTMLElement>(selector);
+ if (!found) throw new Error("Missing " + selector);
+ return found;
+}
+
+async function rendered() {
+ await Promise.all(document.getAnimations().map((a) => a.finished));
+ await new Promise<void>((resolve) =>
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
+ );
+}
+
+function renderPanel(containerWidth: number) {
+ // The panel's own width comes from the store; `containerWidth` is the shell
+ // budget. Resize the host so the strip's box actually changes.
+ host.style.width = `${containerWidth}px`;
+ flushSync(() => {
+ useAppStore.setState({
+ activeSessionId: "tab-close-a",
+ workPanelWidth: Math.min(300, Math.max(244, containerWidth - 40)),
+ pluginViews: [],
+ });
+ root.render(
+ <I18nextProvider i18n={i18n}>
+ <WorkPanel containerWidth={containerWidth} sidebarCollapsed />
+ </I18nextProvider>,
+ );
+ });
+}
+
+function click(selector: string) {
+ flushSync(() => element(selector).click());
+}
+
+/** Long labels are what pushes the close control past the overflow edge. */
+function openManyLongTabs(count: number) {
+ for (let i = 0; i < count; i += 1) click(".work-panel-new-tab");
+}
+
+function activeTabId(): string {
+ const id = useAppStore.getState().activeWorkPanelTabId;
+ assert(id, "no active tab");
+ return id!;
+}
+
+function measure(stage: string): CloseGeometry {
+ const strip = element(".work-panel-tab-strip");
+ const stripRect = strip.getBoundingClientRect();
+ const tabId = activeTabId();
+ const wrapper = host.querySelector<HTMLElement>(
+ `[data-work-panel-tab-id="${CSS.escape(tabId)}"]`,
+ );
+ assert(wrapper, "active tab wrapper missing");
+ const close = wrapper!.querySelector<HTMLElement>(".work-panel-tab-close");
+ assert(close, "active tab close control missing");
+ const closeRect = close!.getBoundingClientRect();
+
+ const centerX = closeRect.x + closeRect.width / 2;
+ const centerY = closeRect.y + closeRect.height / 2;
+ const hit = document.elementFromPoint(centerX, centerY);
+
+ return {
+ stage,
+ tabId,
+ stripLeft: stripRect.left,
+ stripRight: stripRect.right,
+ closeLeft: closeRect.left,
+ closeRight: closeRect.right,
+ // The control must be fully inside the strip's client box. A sub-pixel
+ // tolerance keeps a fractional device pixel ratio from failing the probe.
+ insideStrip:
+ closeRect.left >= stripRect.left - 0.5 && closeRect.right <= stripRect.right + 0.5,
+ hitIsClose: hit === close,
+ hitIsDescendant: !!hit && (close!.contains(hit) || hit.contains(close!)),
+ };
+}
+
+globalThis.tabCloseProbe = async (stage) => {
+ await ready;
+
+ if (stage === "narrow-active") {
+ renderPanel(900);
+ openManyLongTabs(10);
+ await rendered();
+ const strip = element(".work-panel-tab-strip");
+ assert(strip.scrollWidth > strip.clientWidth, "tabs did not overflow the strip");
+ return measure(stage);
+ }
+
+ if (stage === "resize-same-tab") {
+ // Render wide first so every tab fits, then narrow the panel without
+ // changing `activeTabId` or `tabs.length` — the exact case the maintainer
+ // flagged: the reveal effect's dependencies do not change.
+ renderPanel(1400);
+ openManyLongTabs(10);
+ await rendered();
+ const before = measure("before-resize");
+ assert(before.insideStrip, "fixture invalid: close control clipped before the resize");
+
+ // Narrow enough to clip the strip but wide enough that the panel is not
+ // auto-collapsed: MAIN_PANE_MIN_WIDTH is 450 and the panel floor is 244.
+ renderPanel(760);
+ await rendered();
+ const after = measure(stage);
+ return after;
+ }
+
+ if (stage === "hover-inactive") {
+ // Wide enough for a real panel: 560 leaves the panel squeezed to a sliver
+ // because MAIN_PANE_MIN_WIDTH (450) eats the budget.
+ renderPanel(1000);
+ openManyLongTabs(10);
+ await rendered();
+ // Park the strip mid-list so a tab is clipped by the inline-end edge while
+ // the active tab is elsewhere. That is the state the issue describes: a
+ // partly visible inactive tab whose close control appears on hover.
+ const stripEl = element(".work-panel-tab-strip");
+ stripEl.scrollLeft = Math.floor((stripEl.scrollWidth - stripEl.clientWidth) / 2);
+ await rendered();
+ const stripRect0 = stripEl.getBoundingClientRect();
+ const all = [...host.querySelectorAll<HTMLElement>(".work-panel-tab")];
+ // Pick the inactive tab nearest the inline-end edge that is still partly
+ // inside: its close control is the one at risk of being clipped.
+ const candidate = all
+ .filter((node) => node.dataset.workPanelTabId !== activeTabId())
+ .filter((node) => {
+ const r = node.getBoundingClientRect();
+ return r.right > stripRect0.left && r.left < stripRect0.right;
+ })
+ .sort((a, b) => b.getBoundingClientRect().left - a.getBoundingClientRect().left)[0];
+ assert(candidate, "no partly visible inactive tab to hover");
+ const first = candidate!;
+ const firstId = first.dataset.workPanelTabId;
+ assert(firstId && firstId !== activeTabId(), "fixture invalid: hovered tab is active");
+ // React delegates from the root, and `pointerenter` does not bubble, so a
+ // synthetic dispatch never reaches the handler. `pointerover` bubbles and
+ // is what the platform sends on entering an element.
+ flushSync(() => {
+ first!.dispatchEvent(
+ new PointerEvent("pointerover", { bubbles: true, cancelable: true }),
+ );
+ });
+ await rendered();
+ const strip = element(".work-panel-tab-strip");
+ const stripRect = strip.getBoundingClientRect();
+ const close = first!.querySelector<HTMLElement>(".work-panel-tab-close");
+ assert(close, "hovered tab has no close control");
+ const rect = close!.getBoundingClientRect();
+ const hit = document.elementFromPoint(
+ rect.x + rect.width / 2,
+ rect.y + rect.height / 2,
+ );
+ return {
+ stage,
+ tabId: firstId!,
+ stripLeft: stripRect.left,
+ stripRight: stripRect.right,
+ closeLeft: rect.left,
+ closeRight: rect.right,
+ insideStrip: rect.left >= stripRect.left - 0.5 && rect.right <= stripRect.right + 0.5,
+ hitIsClose: hit === close,
+ hitIsDescendant: !!hit && (close!.contains(hit) || hit.contains(close!)),
+ };
+ }
+
+ throw new Error("Unknown tab-close probe stage: " + stage);
+};