Skip to content
TypeScript

fix(desktop): agent typing in a preview tab no longer lands in the app (#18556)

Julius Marmingebb4e4e7eca1d
diff --git a/apps/desktop/src/preview/DesktopBrowserHost.ts b/apps/desktop/src/preview/DesktopBrowserHost.ts
index cfb1ff753c4..1e5d28e1c54 100644
--- a/apps/desktop/src/preview/DesktopBrowserHost.ts
+++ b/apps/desktop/src/preview/DesktopBrowserHost.ts
@@ -24,6 +24,7 @@ import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { createCdpRelayConnection, type CdpRelayConnection } from "./CdpRelay.ts";
+import { sendPageCommand } from "./GuestInput.ts";
const encodeEvent = Schema.encodeSync(Schema.fromJsonString(DesktopBrowserEvent));
const decodeCommand = Schema.decodeUnknownOption(Schema.fromJsonString(DesktopBrowserCommand));
@@ -115,7 +116,7 @@ export const make = Effect.gen(function* () {
{
send: (method, params, sessionId) =>
sessionId === undefined
- ? debuggee.sendCommand(method, params)
+ ? sendPageCommand(webContents, debuggee, method, params)
: debuggee.sendCommand(method, params, sessionId),
targetId: () =>
debuggee
diff --git a/apps/desktop/src/preview/GuestInput.test.ts b/apps/desktop/src/preview/GuestInput.test.ts
new file mode 100644
index 00000000000..d607b217262
--- /dev/null
+++ b/apps/desktop/src/preview/GuestInput.test.ts
@@ -0,0 +1,114 @@
+import { describe, expect, it, vi } from "vite-plus/test";
+
+import { sendPageCommand, toKeyboardInputEvents } from "./GuestInput.ts";
+
+/** A guest whose page reports `focusedDocument` for the focus probe. */
+const makeGuest = ({
+ focused,
+ focusedDocument = true,
+}: {
+ readonly focused: boolean;
+ readonly focusedDocument?: boolean;
+}) => {
+ const sendCommand = vi.fn(async (method: string, params?: { expression?: string }) =>
+ method === "Runtime.evaluate" && params?.expression?.endsWith("!== null")
+ ? { result: { value: focusedDocument } }
+ : { result: {} },
+ );
+ const webContents = {
+ focusedFrame: focused ? {} : null,
+ insertText: vi.fn(async () => {}),
+ sendInputEvent: vi.fn(),
+ };
+ return {
+ webContents,
+ sendCommand,
+ send: (method: string, params: Record<string, unknown>) =>
+ sendPageCommand(
+ webContents as unknown as Electron.WebContents,
+ { sendCommand } as unknown as Electron.Debugger,
+ method,
+ params,
+ ),
+ };
+};
+
+describe("preview guest input", () => {
+ it("types into an unfocused guest's own page, not the app's focused field", async () => {
+ const guest = makeGuest({ focused: false });
+ await guest.send("Input.insertText", { text: "pairing-code" });
+ expect(guest.webContents.insertText).toHaveBeenCalledWith("pairing-code");
+ expect(guest.sendCommand).not.toHaveBeenCalledWith("Input.insertText", expect.anything());
+ });
+
+ it("uses CDP input while the guest holds focus, where it already reaches the page", async () => {
+ const guest = makeGuest({ focused: true });
+ await guest.send("Input.insertText", { text: "x" });
+ await guest.send("Input.dispatchKeyEvent", { type: "keyUp", key: "a" });
+ expect(guest.sendCommand.mock.calls.map(([method]) => method)).toEqual([
+ "Input.insertText",
+ "Input.dispatchKeyEvent",
+ ]);
+ expect(guest.webContents.insertText).not.toHaveBeenCalled();
+ });
+
+ it("refuses input when a cross-site frame holds the unfocused page's focus", async () => {
+ const guest = makeGuest({ focused: false, focusedDocument: false });
+ await expect(guest.send("Input.insertText", { text: "secret" })).rejects.toThrow(
+ /cross-site frame/,
+ );
+ expect(guest.webContents.insertText).not.toHaveBeenCalled();
+ });
+
+ it("clears a field with Cmd+A and Delete while unfocused, never touching the clipboard", async () => {
+ const guest = makeGuest({ focused: false });
+ await guest.send("Input.dispatchKeyEvent", {
+ type: "rawKeyDown",
+ key: "a",
+ modifiers: 4,
+ commands: ["selectAll", "paste"],
+ });
+ await guest.send("Input.dispatchKeyEvent", { type: "rawKeyDown", key: "Delete" });
+ expect(guest.webContents.sendInputEvent.mock.calls.map(([event]) => event)).toEqual([
+ { type: "rawKeyDown", keyCode: "a", modifiers: ["meta"] },
+ { type: "rawKeyDown", keyCode: "Delete", modifiers: [] },
+ ]);
+ const scripts = guest.sendCommand.mock.calls.map(([, params]) => params?.expression ?? "");
+ expect(scripts.some((script) => script.includes('["selectAll"]'))).toBe(true);
+ expect(scripts.some((script) => script.includes("paste"))).toBe(false);
+ });
+
+ it("does not run other page commands through the guest's direct input", async () => {
+ const guest = makeGuest({ focused: false });
+ await guest.send("Input.dispatchMouseEvent", { type: "mousePressed", x: 1, y: 1 });
+ expect(guest.sendCommand).toHaveBeenCalledWith("Input.dispatchMouseEvent", {
+ type: "mousePressed",
+ x: 1,
+ y: 1,
+ });
+ expect(guest.webContents.sendInputEvent).not.toHaveBeenCalled();
+ });
+});
+
+describe("CDP key events as Electron input", () => {
+ it("sends a key's text as char events after its key down", () => {
+ expect(toKeyboardInputEvents({ type: "keyDown", key: "Enter", text: "\r" })).toEqual([
+ { type: "rawKeyDown", keyCode: "Enter", modifiers: [] },
+ { type: "char", keyCode: "\r", modifiers: [] },
+ ]);
+ expect(toKeyboardInputEvents({ type: "keyDown", key: "é", text: "é", modifiers: 8 })).toEqual([
+ { type: "rawKeyDown", keyCode: "é", modifiers: ["shift"] },
+ { type: "char", keyCode: "é", modifiers: ["shift"] },
+ ]);
+ });
+
+ it("names arrows and function keys as Electron accelerators", () => {
+ expect(toKeyboardInputEvents({ type: "keyUp", key: "ArrowLeft", modifiers: 3 })).toEqual([
+ { type: "keyUp", keyCode: "Left", modifiers: ["alt", "control"] },
+ ]);
+ expect(toKeyboardInputEvents({ type: "rawKeyDown", key: "F12" })).toEqual([
+ { type: "rawKeyDown", keyCode: "F12", modifiers: [] },
+ ]);
+ expect(toKeyboardInputEvents({ type: "rawKeyDown", key: "AudioVolumeUp" })).toEqual([]);
+ });
+});
diff --git a/apps/desktop/src/preview/GuestInput.ts b/apps/desktop/src/preview/GuestInput.ts
new file mode 100644
index 00000000000..773d6b79873
--- /dev/null
+++ b/apps/desktop/src/preview/GuestInput.ts
@@ -0,0 +1,150 @@
+/**
+ * Keyboard and text input for a preview tab's page that never lands outside it.
+ *
+ * Chromium sends a page's CDP key and text input to whichever frame holds focus
+ * in the window. A `<webview>` guest shares that focus with the app around it,
+ * so while a person works in the app, `Input.insertText` on the guest's own
+ * debugger types into the app's focused field. Such input goes through CDP only
+ * while the guest holds focus. Otherwise it goes straight to the guest's own
+ * widget, which nothing redirects.
+ */
+
+/** CDP input Chromium delivers to the window's focused frame rather than the page's. */
+const FOCUS_ROUTED_INPUT = new Set([
+ "Input.insertText",
+ "Input.dispatchKeyEvent",
+ "Input.imeSetComposition",
+]);
+
+/**
+ * Page script: the document holding the page's focus, or null when a cross-site
+ * frame holds it. Electron's direct input reaches only the main frame's process,
+ * and `insertText` crashes the page when focus is in another one.
+ */
+const FOCUSED_DOCUMENT = `(() => {
+ let doc = document;
+ for (;;) {
+ const active = doc.activeElement;
+ if (active?.tagName !== "IFRAME" && active?.tagName !== "FRAME") return doc;
+ if (!active.contentDocument) return null;
+ doc = active.contentDocument;
+ }
+})()`;
+
+/**
+ * macOS editing commands a key press asks for (Cmd+A is `selectAll`), which
+ * Chromium runs only for CDP keys. Clipboard commands stay out: they would read
+ * or replace the person's clipboard.
+ */
+const EDITING_COMMANDS = new Set(["selectAll", "undo", "redo"]);
+
+const CROSS_SITE_FOCUS_MESSAGE =
+ "The page's focus is inside a cross-site frame, which takes typed input only while the preview has focus. Click the field first.";
+
+const ARROW_KEYS: Record<string, string> = {
+ ArrowUp: "Up",
+ ArrowDown: "Down",
+ ArrowLeft: "Left",
+ ArrowRight: "Right",
+};
+const NAMED_KEYS = new Set([
+ "Backspace",
+ "Tab",
+ "Enter",
+ "Escape",
+ "Delete",
+ "Insert",
+ "Home",
+ "End",
+ "PageUp",
+ "PageDown",
+ "Shift",
+ "Control",
+ "Alt",
+ "Meta",
+ "CapsLock",
+ "NumLock",
+ "ScrollLock",
+ "PrintScreen",
+]);
+const MODIFIER_BITS = [
+ [1, "alt"],
+ [2, "control"],
+ [4, "meta"],
+ [8, "shift"],
+] as const;
+
+/** Electron's accelerator name for a DOM key value, or null when it has none. */
+const keyCodeFor = (key: string) => {
+ if ([...key].length === 1) return key;
+ if (ARROW_KEYS[key]) return ARROW_KEYS[key];
+ return NAMED_KEYS.has(key) || /^F(?:[1-9]|1\d|2[0-4])$/u.test(key) ? key : null;
+};
+
+/**
+ * The Electron key events for one CDP `Input.dispatchKeyEvent`. Electron
+ * derives key, code, and a char's text from `keyCode`, so typed text travels
+ * as `char` events of its own.
+ */
+export const toKeyboardInputEvents = (
+ params: Record<string, unknown>,
+): Array<Electron.KeyboardInputEvent> => {
+ const bits = typeof params["modifiers"] === "number" ? params["modifiers"] : 0;
+ const modifiers = MODIFIER_BITS.flatMap(([bit, name]) => (bits & bit ? [name] : []));
+ const text = typeof params["text"] === "string" ? params["text"] : "";
+ const chars = [...text].map((char) => ({ type: "char" as const, keyCode: char, modifiers }));
+ const keyCode = keyCodeFor(typeof params["key"] === "string" ? params["key"] : "");
+ switch (params["type"]) {
+ case "keyDown":
+ return [...(keyCode ? [{ type: "rawKeyDown" as const, keyCode, modifiers }] : []), ...chars];
+ case "rawKeyDown":
+ case "keyUp":
+ return keyCode ? [{ type: params["type"], keyCode, modifiers }] : [];
+ case "char":
+ return chars;
+ default:
+ return [];
+ }
+};
+
+const evaluate = async (debuggee: Electron.Debugger, expression: string) => {
+ const reply = (await debuggee.sendCommand("Runtime.evaluate", {
+ expression,
+ returnByValue: true,
+ })) as { readonly result?: { readonly value?: unknown } };
+ return reply.result?.value;
+};
+
+/** Sends one command to the guest's page, keeping key and text input inside it. */
+export const sendPageCommand = async (
+ webContents: Electron.WebContents,
+ debuggee: Electron.Debugger,
+ method: string,
+ params: Record<string, unknown>,
+): Promise<unknown> => {
+ if (!FOCUS_ROUTED_INPUT.has(method) || webContents.focusedFrame) {
+ return debuggee.sendCommand(method, params);
+ }
+ if ((await evaluate(debuggee, `${FOCUSED_DOCUMENT} !== null`)) !== true) {
+ throw new Error(CROSS_SITE_FOCUS_MESSAGE);
+ }
+ switch (method) {
+ case "Input.insertText":
+ await webContents.insertText(typeof params["text"] === "string" ? params["text"] : "");
+ return {};
+ case "Input.dispatchKeyEvent": {
+ for (const event of toKeyboardInputEvents(params)) webContents.sendInputEvent(event);
+ const commands = Array.isArray(params["commands"])
+ ? params["commands"].filter((command) => EDITING_COMMANDS.has(command))
+ : [];
+ // Runs after the page handles the keys, so the reply also waits for them.
+ await evaluate(
+ debuggee,
+ `(() => { const doc = ${FOCUSED_DOCUMENT}; for (const name of ${JSON.stringify(commands)}) doc?.execCommand(name); return 0; })()`,
+ );
+ return {};
+ }
+ default:
+ throw new Error(`${method} needs the preview to have focus.`);
+ }
+};