Порівняти коміти

...
Автор SHA1 Повідомлення Дата
Deng Liu 14884e4214 fix(workbench): skip hidden tool-window focus targets and track plugin iframe focus
Skip hidden, inert, and display:none/visibility:hidden descendants when
ToolWindowView activates a tool window (falling back to the body if a
target refuses focus), so tool windows with hidden inputs such as docked
Agents reliably receive focus.

Detect focus moving into sandboxed plugin webview iframes via window blur
and verified frame-bridge focus notifications, keeping toolWindowFocus,
activeToolWindow, unpinned/undocked auto-hide, and data-focus-active
focus-scope highlighting in sync.
2026-11-26 09:31:23 -08:00
9 змінених файлів з 388 додано та 11 видалено

No files matched your search

+146
Переглянути файл
@@ -0,0 +1,146 @@
/** Focus activation for tool windows with hidden inputs (docked Agents) and sandboxed plugin webview iframes. */
import { expect, test } from "./fixtures";
const TASK = {
id: "task-1",
title: "Inspect rollout logs",
status: "ready" as const,
isolation: "local" as const,
provider: "codex",
model: null,
cwd: "/dev/acme-api",
branch: null,
base: null,
baseCommit: null,
error: null,
createdMs: 1,
updatedMs: 2,
config: [],
commands: [],
usage: null,
queue: [],
};
test("focuses docked Agents tool window instead of getting stuck on its hidden file input", async ({
workbench: page,
}) => {
await page.getByRole("treeitem", { name: "App.tsx", exact: true }).dblclick();
await expect(page.getByRole("textbox", { name: "Editor for /dev/acme-api/App.tsx" })).toBeFocused();
await page.evaluate(async (task) => {
const agentsStorePath = "/src/features/agents/store.ts";
const { useAgents, dockTask } = await import(/* @vite-ignore */ agentsStorePath);
useAgents.setState({
loaded: true,
error: null,
providers: [],
tasks: new Map([[task.id, task]]),
entries: new Map([[task.id, [{ type: "user", text: "Check pods", attachments: [] }]]]),
unread: new Set(),
docked: null,
homeOpen: false,
sessionLocation: "toolWindow",
});
dockTask(task.id);
}, TASK);
const agents = page.locator('[data-toolwindow="agents"]');
await expect(agents).toBeVisible();
await expect(agents).toHaveAttribute("data-focus-active", "");
await expect
.poll(() =>
page.evaluate(async () => {
const storePath = "/src/workbench/toolwindows/store.ts";
const { useToolWindowLayout } = await import(/* @vite-ignore */ storePath);
return useToolWindowLayout.getState().focused;
}),
)
.toBe("agents");
});
test("tracks focus and focus-scope highlighting when clicking into a sandboxed plugin webview iframe", async ({
workbench: page,
}) => {
await page.getByRole("treeitem", { name: "App.tsx", exact: true }).dblclick();
await expect(page.getByRole("textbox", { name: "Editor for /dev/acme-api/App.tsx" })).toBeFocused();
await page.evaluate(async () => {
const pluginsBackendPath = "/src/features/plugins/backend.ts";
const pluginsStorePath = "/src/features/plugins/store.ts";
const bridgeRawPath = "/src/features/plugins/views/frame-bridge.js?raw";
const { createMemoryPluginsBackend, setPluginsBackend } = await import(/* @vite-ignore */ pluginsBackendPath);
const { usePlugins } = await import(/* @vite-ignore */ pluginsStorePath);
const { default: bridgeSource } = await import(/* @vite-ignore */ bridgeRawPath);
const bridgeFn = bridgeSource.trim().replace(/;\s*$/, "");
const html = `<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<script>(${bridgeFn})(null);</script>
</head>
<body>
<button id="pod-api" type="button">acme-api-7f9b4</button>
</body>
</html>`;
const url = URL.createObjectURL(new Blob([html], { type: "text/html" }));
const base = createMemoryPluginsBackend();
const template = (await base.list()).plugins[0]!;
const plugin = { ...template, id: "demo.k8s", name: "Kubernetes", status: "active" as const };
setPluginsBackend({
...base,
webPageUrl: async (pluginId: string) => (pluginId === "demo.k8s" ? url : base.webPageUrl(pluginId, "v")),
});
usePlugins.setState({
plugins: [plugin],
ui: [
{
pluginId: "demo.k8s",
point: "views",
key: "kubernetes",
decl: { id: "kubernetes", title: "Kubernetes", location: "right", web: "web/index.html", header: "default" },
},
],
});
});
// Put Project in Undock mode so clicking into the plugin iframe also verifies unpinned/undocked auto-hide.
await page.evaluate(async () => {
const storePath = "/src/workbench/toolwindows/store.ts";
const { setToolWindowViewMode, focusToolWindow } = await import(/* @vite-ignore */ storePath);
setToolWindowViewMode("project", "undock");
focusToolWindow("project");
});
const project = page.getByRole("region", { name: "Project", exact: true });
await expect(project).toBeVisible();
const k8sStripe = page.locator('[data-stripe-button="plugin.demo.k8s.kubernetes"]');
await expect(k8sStripe).toBeVisible();
await k8sStripe.click();
const k8sRegion = page.locator('[data-toolwindow="plugin.demo.k8s.kubernetes"]');
await expect(k8sRegion).toBeVisible();
await page.frameLocator('iframe[data-plugin-webview="demo.k8s"]').locator("#pod-api").click();
await expect(k8sRegion).toHaveAttribute("data-focus-active", "");
await expect(project).toBeHidden();
await expect
.poll(() =>
page.evaluate(async () => {
const storePath = "/src/workbench/toolwindows/store.ts";
const ctxPath = "/src/platform/context.ts";
const { useToolWindowLayout } = await import(/* @vite-ignore */ storePath);
const { getContext } = await import(/* @vite-ignore */ ctxPath);
return {
focused: useToolWindowLayout.getState().focused,
toolWindowFocus: getContext().toolWindowFocus,
activeToolWindow: getContext().activeToolWindow,
};
}),
)
.toEqual({
focused: "plugin.demo.k8s.kubernetes",
toolWindowFocus: true,
activeToolWindow: "plugin.demo.k8s.kubernetes",
});
});
+53
Переглянути файл
@@ -3,6 +3,8 @@ import { render, waitFor } from "@testing-library/react";
import type { PluginInfo } from "@/bindings";
import { registerAction } from "@/platform/actions";
import { installKeyboardDispatcher, useKeymap } from "@/platform/keymap";
import { installFocusScopeTracking } from "@/ui/focusScope";
import { installFocusTracking } from "@/workbench/focus";
import { createMemoryPluginsBackend, setPluginsBackend } from "../backend";
import { usePlugins } from "../store";
import { FRAME_TAG } from "../views/frame";
@@ -141,4 +143,55 @@ describe("keys a plugin web view passes on", () => {
await flush();
expect(run).not.toHaveBeenCalled();
});
it("reports iframe focus to the host only while the frame actually holds window focus", async () => {
const hasFocus = vi.spyOn(document, "hasFocus").mockReturnValue(true);
setPluginsBackend({ ...createMemoryPluginsBackend([]), webPageUrl: async () => "about:blank" });
usePlugins.setState({
plugins: [{ id: "k8s.view", hasCode: false, enabled: true, capabilities: [] } as unknown as PluginInfo],
});
const calls: Array<[string | null, boolean]> = [];
const disposeScope = installFocusScopeTracking();
const disposeFocus = installFocusTracking((id, editor) => calls.push([id, editor]));
try {
const view = render(
<section data-toolwindow="plugin.k8s.view" data-focus-scope="">
<WebView pluginId="k8s.view" view="v" label="Kubernetes" />
</section>,
);
const frame = await waitFor(() => {
const found = view.container.querySelector("iframe");
expect(found).not.toBeNull();
return found!;
});
const scope = view.container.querySelector('[data-toolwindow="plugin.k8s.view"]')!;
// Spoofed focus message while another element has focus is ignored.
window.dispatchEvent(
new MessageEvent("message", { data: { tag: FRAME_TAG, focus: true }, source: frame.contentWindow }),
);
expect(calls).toEqual([]);
expect(scope).not.toHaveAttribute("data-focus-active");
// Ignored when the window itself does not have focus.
frame.focus();
calls.length = 0;
hasFocus.mockReturnValue(false);
window.dispatchEvent(
new MessageEvent("message", { data: { tag: FRAME_TAG, focus: true }, source: frame.contentWindow }),
);
expect(calls).toEqual([]);
// Accepted once the frame is activeElement and the window has focus.
hasFocus.mockReturnValue(true);
window.dispatchEvent(
new MessageEvent("message", { data: { tag: FRAME_TAG, focus: true }, source: frame.contentWindow }),
);
expect(calls).toEqual([["plugin.k8s.view", false]]);
expect(scope).toHaveAttribute("data-focus-active", "");
} finally {
disposeFocus();
disposeScope();
}
});
});
+6 -1
Переглянути файл
@@ -23,6 +23,7 @@ import { useProject } from "@/platform/project";
import { subscribeTheme, themeKey } from "@/platform/themeWatch";
import { EmptyState, Spinner } from "@/ui";
import { editorService, registerFontZoomSurface } from "@/workbench/contributions";
import { notifyFocusElement } from "@/workbench/focus";
import { ToolWindowCornerActions, useOwnToolWindowHeader } from "@/workbench/toolwindows/ToolWindows";
import { pluginsBackend, type FileFilter } from "../backend";
import { errorText, usePlugins } from "../store";
@@ -548,9 +549,13 @@ export function WebView({
op?: unknown;
args?: unknown;
key?: unknown;
focus?: unknown;
} | null;
if (m?.tag !== FRAME_TAG) return;
if (m.key && typeof m.key === "object") {
if (m.focus === true) {
const host = frame.current.ownerDocument;
if (host.activeElement === frame.current && host.hasFocus()) notifyFocusElement(frame.current);
} else if (m.key && typeof m.key === "object") {
// A shortcut the page didn't handle: as if pressed on the frame, for the IDE's keymap. The
// page can post one at any time and can take the focus, but it cannot fake the user's own
// input, so it counts only right after the user pressed a key or clicked in the frame.
+6
Переглянути файл
@@ -88,6 +88,12 @@
root.style.zoom = next === 100 ? "" : (next / 100).toFixed(2);
};
// Report frame activation to the host so focus tracking and focus-scope highlighting
// stay in sync even when switching directly into or between sandboxed plugin frames.
const notifyFocus = () => window.parent.postMessage({ tag: TAG, focus: true }, "*");
window.addEventListener("focus", notifyFocus);
window.addEventListener("pointerdown", notifyFocus, true);
// IDE shortcuts (Save, Close, Find Action…) pressed while the page has focus:
// the ones the page left alone go to the workbench. Editing keys stay here.
const EDITING_KEYS = new Set(["a", "c", "v", "x", "z", "y"]);
+19
Переглянути файл
@@ -10,6 +10,13 @@
const FOCUS_SCOPE_ATTR = "data-focus-scope";
export const FOCUS_ACTIVE_ATTR = "data-focus-active";
let markCurrent: ((target: Element | null) => void) | null = null;
/** Updates the active focus scope marks for `target` (e.g. a focused plugin iframe). */
export function syncFocusScope(target: Element | null) {
markCurrent?.(target);
}
/** Marks the scopes holding focus. Returns an uninstaller that clears the marks. */
export function installFocusScopeTracking(): () => void {
let active: Element[] = [];
@@ -22,11 +29,23 @@ export function installFocusScopeTracking(): () => void {
for (const el of chain) el.setAttribute(FOCUS_ACTIVE_ATTR, "");
active = chain;
};
markCurrent = mark;
const onFocusIn = (e: FocusEvent) => mark(e.target instanceof Element ? e.target : null);
const checkIframe = () => {
const el = document.activeElement;
if (el instanceof HTMLIFrameElement && document.hasFocus()) mark(el);
};
const onWindowBlur = () => {
checkIframe();
queueMicrotask(checkIframe);
};
document.addEventListener("focusin", onFocusIn);
window.addEventListener("blur", onWindowBlur);
mark(document.activeElement);
return () => {
if (markCurrent === mark) markCurrent = null;
document.removeEventListener("focusin", onFocusIn);
window.removeEventListener("blur", onWindowBlur);
for (const el of active) el.removeAttribute(FOCUS_ACTIVE_ATTR);
active = [];
};
+43 -1
Переглянути файл
@@ -1,6 +1,7 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { setContext } from "@/platform/context";
import { EDITOR_AREA_SELECTOR, focusEditor, installFocusTracking } from "./focus";
import { installFocusScopeTracking } from "@/ui/focusScope";
import { EDITOR_AREA_SELECTOR, focusEditor, installFocusTracking, notifyFocusElement } from "./focus";
describe("focus after popups", () => {
afterEach(() => {
@@ -122,4 +123,45 @@ describe("focus tracking", () => {
]);
dispose();
});
it("tracks focus entering sandboxed plugin iframes and updates focus-scope highlighting", () => {
vi.spyOn(document, "hasFocus").mockReturnValue(true);
document.body.innerHTML = `
<div data-editor-area>
<section data-pane-id="p1" data-focus-scope=""><iframe id="ed-frame" tabindex="0"></iframe></section>
</div>
<section data-toolwindow="plugin.k8s.view" data-focus-scope="">
<iframe id="tw-frame" tabindex="0"></iframe>
</section>`;
const calls: Array<[string | null, boolean]> = [];
const disposeScope = installFocusScopeTracking();
const dispose = installFocusTracking((id, editor) => calls.push([id, editor]));
const twFrame = document.getElementById("tw-frame") as HTMLIFrameElement;
const edFrame = document.getElementById("ed-frame") as HTMLIFrameElement;
let active: Element | null = twFrame;
Object.defineProperty(document, "activeElement", { configurable: true, get: () => active });
// Window blur when activeElement is an iframe inside a tool window tracks it and marks its focus scope.
window.dispatchEvent(new Event("blur"));
// Repeated bridge notification for the same iframe is deduplicated.
notifyFocusElement(twFrame);
expect(calls).toEqual([["plugin.k8s.view", false]]);
expect(document.querySelector('[data-toolwindow="plugin.k8s.view"]')).toHaveAttribute("data-focus-active", "");
// Switching to an iframe inside an editor pane updates both tracking and focus-scope highlight.
active = edFrame;
notifyFocusElement(edFrame);
expect(calls).toEqual([
["plugin.k8s.view", false],
[null, true],
]);
expect(document.querySelector('[data-pane-id="p1"]')).toHaveAttribute("data-focus-active", "");
expect(document.querySelector('[data-toolwindow="plugin.k8s.view"]')).not.toHaveAttribute("data-focus-active");
Reflect.deleteProperty(document, "activeElement");
dispose();
disposeScope();
vi.restoreAllMocks();
});
});
+34 -4
Переглянути файл
@@ -1,9 +1,18 @@
/** Focus routing between tool windows and the editor area. */
import { setContext, useContextKeys } from "@/platform/context";
import { syncFocusScope } from "@/ui/focusScope";
import { maybeEditorService } from "./contributions";
export const EDITOR_AREA_SELECTOR = "[data-editor-area]";
let activeTracker: ((el: Element | null) => void) | null = null;
/** Reports that focus entered `el` (e.g. a sandboxed plugin iframe that does not bubble `focusin`). */
export function notifyFocusElement(el: Element | null) {
syncFocusScope(el);
activeTracker?.(el);
}
/** Moves focus to the active editor (or the editor area when none is open). */
export function focusEditor() {
if (typeof document !== "undefined" && document.querySelector(EDITOR_AREA_SELECTOR)?.closest("[hidden]")) {
@@ -51,25 +60,44 @@ function dropEditorCaret(e: FocusEvent) {
* `activeToolWindow` and `editorAreaFocus`. Returns an uninstaller.
*/
export function installFocusTracking(onToolWindowFocus: (id: string | null, editor: boolean) => void): () => void {
const onFocusIn = (e: FocusEvent) => {
const el = e.target as Element | null;
let lastEl: Element | null = null;
const handleFocus = (el: Element | null) => {
if (el && el === lastEl && el instanceof HTMLIFrameElement) return;
lastEl = el;
const tw = el?.closest?.("[data-toolwindow]");
const editor = !!el?.closest?.(EDITOR_AREA_SELECTOR);
onToolWindowFocus(tw?.getAttribute("data-toolwindow") ?? null, editor);
setContext("editorAreaFocus", editor);
};
activeTracker = handleFocus;
const onFocusIn = (e: FocusEvent) => handleFocus(e.target as Element | null);
const checkIframeFocus = () => {
const active = document.activeElement;
if (active instanceof HTMLIFrameElement && document.hasFocus()) handleFocus(active);
};
const onWindowBlur = () => {
checkIframeFocus();
queueMicrotask(checkIframeFocus);
};
const onFocusOut = (e: FocusEvent) => {
dropEditorCaret(e);
if (e.relatedTarget) return;
// Focus left to nowhere (window blur keeps document.activeElement).
// Focus left to nowhere (window blur keeps document.activeElement) or into an iframe.
queueMicrotask(() => {
if (document.activeElement && document.activeElement !== document.body) return;
const active = document.activeElement;
if (active instanceof HTMLIFrameElement && document.hasFocus()) {
handleFocus(active);
return;
}
if (active && active !== document.body) return;
lastEl = null;
onToolWindowFocus(null, false);
setContext("editorAreaFocus", false);
});
};
document.addEventListener("focusin", onFocusIn);
document.addEventListener("focusout", onFocusOut);
window.addEventListener("blur", onWindowBlur);
// IDEA: closing the last popup / menu / dialog never leaves focus nowhere.
let popupOpen = !!useContextKeys.getState().popupOpen;
let refocus: ReturnType<typeof setTimeout> | undefined;
@@ -84,9 +112,11 @@ export function installFocusTracking(onToolWindowFocus: (id: string | null, edit
});
});
return () => {
if (activeTracker === handleFocus) activeTracker = null;
clearTimeout(refocus);
unsubPopups();
document.removeEventListener("focusin", onFocusIn);
document.removeEventListener("focusout", onFocusOut);
window.removeEventListener("blur", onWindowBlur);
};
}
+16 -5
Переглянути файл
@@ -831,18 +831,29 @@ function ToolWindowView({ tw, hidden }: { tw: ToolWindowContribution; hidden: bo
const root = ref.current;
if (!root) return;
const body = root.querySelector<HTMLElement>("[data-toolwindow-body]");
// Like IDEA, activation focuses the content (a field, list or tree), never a button or
// link: a scripted focus on one draws its focus ring (an empty view's "New…" link).
// Like IDEA, activation focuses visible content (a field, list or tree), never a button,
// link, or hidden / inert target: a scripted focus on a button draws its focus ring, and
// focusing a hidden element (e.g. a file input or inactive tab panel) is a silent no-op
// that leaves focus stranded in the previous window.
const isVisibleTarget = (el: HTMLElement) => {
if (el.matches('input[type="hidden"]') || el.closest("[hidden], [inert]")) return false;
for (let cur: HTMLElement | null = el; cur && cur !== body; cur = cur.parentElement) {
const style = getComputedStyle(cur);
if (style.display === "none" || style.visibility === "hidden") return false;
}
return true;
};
const contentTarget = () =>
body?.querySelector<HTMLElement>("[data-autofocus]") ??
[...(body?.querySelectorAll<HTMLElement>("[data-autofocus]") ?? [])].find(isVisibleTarget) ??
[...(body?.querySelectorAll<HTMLElement>(FOCUSABLE) ?? [])].find(
(el) => !el.matches('button, a[href], [role="button"], [role="link"]'),
(el) => !el.matches('button, a[href], [role="button"], [role="link"]') && isVisibleTarget(el),
);
const target = contentTarget();
if (target || !body) {
(target ?? root).focus({ preventScroll: true });
return;
if (root.contains(document.activeElement)) return;
}
if (!body) return;
if (!body.hasAttribute("tabindex")) body.tabIndex = -1;
body.focus({ preventScroll: true });
// Lazily loaded views (the Terminal) render their field after this: focus it when it
+65
Переглянути файл
@@ -134,3 +134,68 @@ it("shows the header title in a language chosen while the window is open", () =>
act(() => useI18n.setState({ texts: before }));
}
});
it("skips hidden and inert focus targets when activating a tool window", () => {
vi.useFakeTimers();
const dispose = registerToolWindow({
id: "hidden-inputs",
title: "Hidden Inputs",
icon: "file",
anchor: "right",
requiresProject: false,
component: () => (
<div>
<input type="file" aria-label="Hidden file" style={{ display: "none" }} />
<input type="hidden" value="secret" />
<div hidden>
<input aria-label="In hidden panel" data-autofocus="" />
</div>
<div inert>
<input aria-label="In inert container" />
</div>
<div style={{ display: "none" }}>
<input aria-label="In display-none wrapper" />
</div>
<textarea aria-label="Visible composer" />
</div>
),
});
try {
render(<ToolWindowLayout editor={<input aria-label="Editor" />} />);
screen.getByRole("textbox", { name: "Editor" }).focus();
act(() => showToolWindow("hidden-inputs", true));
act(() => vi.runAllTimers());
expect(document.activeElement).toBe(screen.getByRole("textbox", { name: "Visible composer" }));
} finally {
dispose();
vi.useRealTimers();
}
});
it("falls back to the tool window body when only hidden focus targets exist", () => {
vi.useFakeTimers();
const dispose = registerToolWindow({
id: "only-hidden",
title: "Only Hidden",
icon: "file",
anchor: "right",
requiresProject: false,
component: () => (
<div>
<input type="file" aria-label="Hidden file" style={{ display: "none" }} />
<button type="button">Action</button>
</div>
),
});
try {
render(<ToolWindowLayout editor={<input aria-label="Editor" />} />);
screen.getByRole("textbox", { name: "Editor" }).focus();
act(() => showToolWindow("only-hidden", true));
act(() => vi.runAllTimers());
const body = document.querySelector<HTMLElement>('[data-toolwindow="only-hidden"] [data-toolwindow-body]')!;
expect(document.activeElement).toBe(body);
} finally {
dispose();
vi.useRealTimers();
}
});