Open History to see the last commit
1interface PreviewClick {
2 readonly runtimeTabId: string;
3 readonly order: number;
4 previous: Element | null;
5}
6
7// Agent clicks can overlap across tabs and threads.
8const inFlightClicks = new Set<PreviewClick>();
9let nextClickOrder = 0;
10
11const focusedPreviewTab = (element: Element | null): string | null =>
12 element?.localName === "webview" ? element.getAttribute("data-preview-tab") : null;
13
14const restoreHostFocus = ({ runtimeTabId, previous }: PreviewClick): void => {
15 const current = document.activeElement;
16 if (
17 !(current instanceof HTMLElement) ||
18 current === previous ||
19 focusedPreviewTab(current) !== runtimeTabId
20 ) {
21 return;
22 }
23 if (previous instanceof HTMLElement && previous.isConnected && previous !== document.body) {
24 previous.focus({ preventScroll: true });
25 }
26 // The previous element may no longer take focus, like a composer that was
27 // disabled during the click. Never leave focus in the page.
28 if (document.activeElement === current) current.blur();
29};
30
31/**
32 * Runs an agent click in a preview tab and hands keyboard focus back to the
33 * host page afterwards.
34 *
35 * The desktop dispatches the click as a CDP mouse press, which focuses the
36 * guest page, and nothing gives that focus back. The user's next keystrokes
37 * then go into the page, even when its tab is hidden or belongs to another
38 * thread. Only the host document knows what had focus before the click, so
39 * the restore happens here and not in the desktop main process.
40 */
41export async function runPreviewClickKeepingHostFocus<A>(
42 runtimeTabId: string,
43 click: () => Promise<A>,
44): Promise<A> {
45 const entry: PreviewClick = {
46 runtimeTabId,
47 order: nextClickOrder++,
48 previous: document.activeElement,
49 };
50 inFlightClicks.add(entry);
51 try {
52 return await click();
53 } finally {
54 // Also runs when the click fails: a keystroke that reaches the page after
55 // the press counts as human input and fails the click as interrupted.
56 inFlightClicks.delete(entry);
57 // A click that started while this one held focus in its page saw that page
58 // as what had focus. Hand it this click's target instead. A click that never
59 // finishes never gets here, so it cannot override where the user goes later.
60 for (const other of inFlightClicks) {
61 if (other.order > entry.order && focusedPreviewTab(other.previous) === runtimeTabId) {
62 other.previous = entry.previous;
63 }
64 }
65 restoreHostFocus(entry);
66 }
67}