Skip to content

Commit 08186e3

Browse files
committed
fix(web): keep typing focus in the app after agent preview clicks
A dispatched click moves keyboard focus into the guest page, even a hidden one in another thread. Electron reports the guest as focused before the click too, so the host document restores its previously focused element instead.
1 parent ab09917 commit 08186e3

3 files changed

Lines changed: 171 additions & 3 deletions

File tree

‎apps/web/src/components/preview/PreviewAutomationHosts.tsx‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@ import {
9090
resolvePreviewAutomationTarget,
9191
} from "./previewAutomationTarget";
9292
import { resolveHostWaitBudgetMs, waitForHostReadiness } from "./previewAutomationHostBudget";
93+
import { keepHostFocusDuringGuestInput } from "./previewHostFocus";
9394
import { isPreviewViewportReady } from "./previewViewportReadiness";
9495
import { shouldRollbackPreviewViewport } from "./previewViewportRollback";
9596

@@ -141,6 +142,9 @@ const findPreviewWebview = (tabId: string): ExecutablePreviewWebview | null =>
141142
(candidate) => candidate.getAttribute("data-preview-tab") === tabId,
142143
) ?? null;
143144

145+
const activeHtmlElement = (): HTMLElement | null =>
146+
document.activeElement instanceof HTMLElement ? document.activeElement : null;
147+
144148
const isPreviewWebviewRendering = (runtimeTabId: string): boolean => {
145149
const wrapper = findPreviewWebview(runtimeTabId)?.closest<HTMLElement>("[data-preview-viewport]");
146150
return wrapper?.getAttribute("data-preview-rendering") === "active";
@@ -686,9 +690,11 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
686690
}
687691
case "click": {
688692
const ready = await requireReadyTab();
689-
return await ready.bridge.automation.click(
690-
ready.runtimeTabId,
691-
request.input as Parameters<typeof ready.bridge.automation.click>[1],
693+
return await keepHostFocusDuringGuestInput(ready.runtimeTabId, activeHtmlElement, () =>
694+
ready.bridge.automation.click(
695+
ready.runtimeTabId,
696+
request.input as Parameters<typeof ready.bridge.automation.click>[1],
697+
),
692698
);
693699
}
694700
case "type": {
Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
import { describe, expect, it, vi } from "vite-plus/test";
2+
3+
import { type HostFocusElement, keepHostFocusDuringGuestInput } from "./previewHostFocus";
4+
5+
const TAB = "runtime-tab";
6+
7+
const element = (tagName: string, previewTab: string | null = null) => {
8+
const focus = vi.fn<(options?: FocusOptions) => void>();
9+
const blur = vi.fn<() => void>();
10+
let connected = true;
11+
const node = {
12+
tagName,
13+
get isConnected() {
14+
return connected;
15+
},
16+
getAttribute: (name: string) => (name === "data-preview-tab" ? previewTab : null),
17+
focus,
18+
blur,
19+
} satisfies HostFocusElement;
20+
const detach = () => {
21+
connected = false;
22+
};
23+
return { node, focus, blur, detach };
24+
};
25+
26+
const focusTracker = (initial: HostFocusElement | null) => {
27+
let active = initial;
28+
return {
29+
read: () => active,
30+
move: (next: HostFocusElement | null) => {
31+
active = next;
32+
},
33+
};
34+
};
35+
36+
describe("keepHostFocusDuringGuestInput", () => {
37+
it("returns focus to the composer when the click moved it into the clicked webview", async () => {
38+
const composer = element("TEXTAREA");
39+
const webview = element("WEBVIEW", TAB);
40+
const focus = focusTracker(composer.node);
41+
42+
const result = await keepHostFocusDuringGuestInput(TAB, focus.read, async () => {
43+
focus.move(webview.node);
44+
return "clicked";
45+
});
46+
47+
expect(result).toBe("clicked");
48+
expect(composer.focus).toHaveBeenCalledWith({ preventScroll: true });
49+
expect(webview.blur).not.toHaveBeenCalled();
50+
});
51+
52+
it("blurs the webview when nothing in the app had focus before the click", async () => {
53+
const body = element("BODY");
54+
const webview = element("WEBVIEW", TAB);
55+
const focus = focusTracker(body.node);
56+
57+
await keepHostFocusDuringGuestInput(TAB, focus.read, async () => {
58+
focus.move(webview.node);
59+
});
60+
61+
expect(webview.blur).toHaveBeenCalledOnce();
62+
expect(body.focus).not.toHaveBeenCalled();
63+
});
64+
65+
it("blurs the webview when the previously focused element left the page", async () => {
66+
const composer = element("TEXTAREA");
67+
const webview = element("WEBVIEW", TAB);
68+
const focus = focusTracker(composer.node);
69+
70+
await keepHostFocusDuringGuestInput(TAB, focus.read, async () => {
71+
composer.detach();
72+
focus.move(webview.node);
73+
});
74+
75+
expect(composer.focus).not.toHaveBeenCalled();
76+
expect(webview.blur).toHaveBeenCalledOnce();
77+
});
78+
79+
it("leaves focus in the page when the user was already typing there", async () => {
80+
const webview = element("WEBVIEW", TAB);
81+
const focus = focusTracker(webview.node);
82+
83+
await keepHostFocusDuringGuestInput(TAB, focus.read, async () => undefined);
84+
85+
expect(webview.focus).not.toHaveBeenCalled();
86+
expect(webview.blur).not.toHaveBeenCalled();
87+
});
88+
89+
it("keeps a selection the user made somewhere else during the click", async () => {
90+
const composer = element("TEXTAREA");
91+
const search = element("INPUT");
92+
const focus = focusTracker(composer.node);
93+
94+
await keepHostFocusDuringGuestInput(TAB, focus.read, async () => {
95+
focus.move(search.node);
96+
});
97+
98+
expect(composer.focus).not.toHaveBeenCalled();
99+
expect(search.blur).not.toHaveBeenCalled();
100+
});
101+
102+
it("ignores focus in a different preview tab", async () => {
103+
const composer = element("TEXTAREA");
104+
const otherWebview = element("WEBVIEW", "other-tab");
105+
const focus = focusTracker(composer.node);
106+
107+
await keepHostFocusDuringGuestInput(TAB, focus.read, async () => {
108+
focus.move(otherWebview.node);
109+
});
110+
111+
expect(composer.focus).not.toHaveBeenCalled();
112+
expect(otherWebview.blur).not.toHaveBeenCalled();
113+
});
114+
115+
it("restores focus when the click fails and rethrows the failure", async () => {
116+
const composer = element("TEXTAREA");
117+
const webview = element("WEBVIEW", TAB);
118+
const focus = focusTracker(composer.node);
119+
120+
await expect(
121+
keepHostFocusDuringGuestInput(TAB, focus.read, async () => {
122+
focus.move(webview.node);
123+
throw new Error("click failed");
124+
}),
125+
).rejects.toThrow("click failed");
126+
127+
expect(composer.focus).toHaveBeenCalledWith({ preventScroll: true });
128+
});
129+
});
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
export interface HostFocusElement {
2+
readonly tagName: string;
3+
readonly isConnected: boolean;
4+
getAttribute(name: string): string | null;
5+
focus(options?: FocusOptions): void;
6+
blur(): void;
7+
}
8+
9+
// Electron reports the guest as focused even before a click, so only the host document knows what to restore.
10+
export async function keepHostFocusDuringGuestInput<A>(
11+
runtimeTabId: string,
12+
readActiveElement: () => HostFocusElement | null,
13+
action: () => Promise<A>,
14+
): Promise<A> {
15+
const previous = readActiveElement();
16+
try {
17+
return await action();
18+
} finally {
19+
const current = readActiveElement();
20+
if (
21+
current !== null &&
22+
current !== previous &&
23+
current.tagName === "WEBVIEW" &&
24+
current.getAttribute("data-preview-tab") === runtimeTabId
25+
) {
26+
if (previous !== null && previous.isConnected && previous.tagName !== "BODY") {
27+
previous.focus({ preventScroll: true });
28+
} else {
29+
current.blur();
30+
}
31+
}
32+
}
33+
}

0 commit comments

Comments
 (0)