Skip to content

Commit 6ae4382

Browse files
committed
fix(web): preserve composer focus during browser automation
1 parent 5ca3266 commit 6ae4382

4 files changed

Lines changed: 82 additions & 16 deletions

File tree

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

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ import {
3737
import { resolveBrowserRecordingStopTarget } from "~/browser/browserRecordingScope";
3838
import { useBrowserSurfaceStore } from "~/browser/browserSurfaceStore";
3939
import { isElectron } from "~/env";
40+
import { runPreservingDocumentFocus } from "~/lib/documentFocus";
4041
import { useEnvironments } from "~/state/environments";
4142
import { previewEnvironment } from "~/state/preview";
4243
import { useAtomQueryRunner } from "~/state/use-atom-query-runner";
@@ -471,9 +472,11 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
471472
}
472473
case "press": {
473474
const ready = await requireReadyTab();
474-
return await ready.bridge.automation.press(
475-
ready.tabId,
476-
request.input as Parameters<typeof ready.bridge.automation.press>[1],
475+
return await runPreservingDocumentFocus(() =>
476+
ready.bridge.automation.press(
477+
ready.tabId,
478+
request.input as Parameters<typeof ready.bridge.automation.press>[1],
479+
),
477480
);
478481
}
479482
case "scroll": {

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

Lines changed: 3 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
import { useCallback, useEffect, useRef, useState } from "react";
1111

1212
import { useComposerDraftStore } from "~/composerDraftStore";
13+
import { captureDocumentFocus, restoreDocumentFocus } from "~/lib/documentFocus";
1314
import { previewAnnotationScreenshotFile } from "~/lib/previewAnnotation";
1415
import { ensureLocalApi } from "~/localApi";
1516
import {
@@ -468,8 +469,7 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
468469
// focus into the guest webContents. We restore it when the pick
469470
// resolves so the user's typing context isn't lost — otherwise after
470471
// every pick they'd have to click back into the textarea.
471-
const previouslyFocused =
472-
typeof document !== "undefined" ? (document.activeElement as HTMLElement | null) : null;
472+
const previouslyFocused = captureDocumentFocus();
473473
pickActiveRef.current = true;
474474
setPickActive(true);
475475
void (async () => {
@@ -499,17 +499,7 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
499499
// Best-effort: restore focus to whatever the user had before the
500500
// pick stole it into the guest webContents. Skip if the previously-
501501
// focused element was unmounted or is no longer focusable.
502-
if (
503-
previouslyFocused &&
504-
previouslyFocused.isConnected &&
505-
typeof previouslyFocused.focus === "function"
506-
) {
507-
try {
508-
previouslyFocused.focus({ preventScroll: true });
509-
} catch {
510-
// Some elements throw on .focus() (detached iframes, etc.).
511-
}
512-
}
502+
restoreDocumentFocus(previouslyFocused);
513503
}
514504
})();
515505
}, [addImage, addPreviewAnnotation, tabId, threadRef]);
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
2+
3+
import { runPreservingDocumentFocus } from "./documentFocus";
4+
5+
class MockHTMLElement {
6+
isConnected = true;
7+
readonly focus = vi.fn();
8+
}
9+
10+
afterEach(() => {
11+
vi.unstubAllGlobals();
12+
});
13+
14+
const setActiveElement = (activeElement: unknown): void => {
15+
vi.stubGlobal("HTMLElement", MockHTMLElement);
16+
vi.stubGlobal("document", { activeElement });
17+
};
18+
19+
describe("document focus", () => {
20+
it("restores the active element without scrolling after success", async () => {
21+
const element = new MockHTMLElement();
22+
setActiveElement(element);
23+
24+
await expect(runPreservingDocumentFocus(async () => "result")).resolves.toBe("result");
25+
expect(element.focus).toHaveBeenCalledWith({ preventScroll: true });
26+
});
27+
28+
it("restores the active element after failure", async () => {
29+
const element = new MockHTMLElement();
30+
const cause = new Error("automation failed");
31+
setActiveElement(element);
32+
33+
await expect(
34+
runPreservingDocumentFocus(async () => {
35+
throw cause;
36+
}),
37+
).rejects.toBe(cause);
38+
expect(element.focus).toHaveBeenCalledOnce();
39+
});
40+
41+
it("does not restore a focused element that was detached during the operation", async () => {
42+
const element = new MockHTMLElement();
43+
setActiveElement(element);
44+
45+
await runPreservingDocumentFocus(async () => {
46+
element.isConnected = false;
47+
});
48+
49+
expect(element.focus).not.toHaveBeenCalled();
50+
});
51+
});

‎apps/web/src/lib/documentFocus.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
export function captureDocumentFocus(): HTMLElement | null {
2+
const activeElement = document.activeElement;
3+
return activeElement instanceof HTMLElement && activeElement.isConnected ? activeElement : null;
4+
}
5+
6+
export function restoreDocumentFocus(element: HTMLElement | null): void {
7+
if (!element?.isConnected) return;
8+
try {
9+
element.focus({ preventScroll: true });
10+
} catch {
11+
// Focus restoration is best-effort when the element becomes unavailable.
12+
}
13+
}
14+
15+
export async function runPreservingDocumentFocus<T>(operation: () => Promise<T>): Promise<T> {
16+
const previouslyFocused = captureDocumentFocus();
17+
try {
18+
return await operation();
19+
} finally {
20+
restoreDocumentFocus(previouslyFocused);
21+
}
22+
}

0 commit comments

Comments
 (0)