@devries-cameron20 / t3code-1 / commits / bb4e4e7eca
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 15, 2026 at 18:40 UTC bb4e4e7eca1d0de27efbc9fb9eab69e5463b9374
3 files changed +266 -1
apps/desktop/src/preview/DesktopBrowserHost.ts
+2 -1
@@ -24,6 +24,7 @@ import * as Schema from "effect/Schema";
24 import * as Stream from "effect/Stream";
25
26 import { createCdpRelayConnection, type CdpRelayConnection } from "./CdpRelay.ts";
27 +import { sendPageCommand } from "./GuestInput.ts";
28
29 const encodeEvent = Schema.encodeSync(Schema.fromJsonString(DesktopBrowserEvent));
30 const decodeCommand = Schema.decodeUnknownOption(Schema.fromJsonString(DesktopBrowserCommand));
@@ -115,7 +116,7 @@ export const make = Effect.gen(function* () {
116 {
117 send: (method, params, sessionId) =>
118 sessionId === undefined
118 - ? debuggee.sendCommand(method, params)
119 + ? sendPageCommand(webContents, debuggee, method, params)
120 : debuggee.sendCommand(method, params, sessionId),
121 targetId: () =>
122 debuggee
apps/desktop/src/preview/GuestInput.test.ts new
+114
@@ -0,0 +1,114 @@
1 +import { describe, expect, it, vi } from "vite-plus/test";
2 +
3 +import { sendPageCommand, toKeyboardInputEvents } from "./GuestInput.ts";
4 +
5 +/** A guest whose page reports `focusedDocument` for the focus probe. */
6 +const makeGuest = ({
7 + focused,
8 + focusedDocument = true,
9 +}: {
10 + readonly focused: boolean;
11 + readonly focusedDocument?: boolean;
12 +}) => {
13 + const sendCommand = vi.fn(async (method: string, params?: { expression?: string }) =>
14 + method === "Runtime.evaluate" && params?.expression?.endsWith("!== null")
15 + ? { result: { value: focusedDocument } }
16 + : { result: {} },
17 + );
18 + const webContents = {
19 + focusedFrame: focused ? {} : null,
20 + insertText: vi.fn(async () => {}),
21 + sendInputEvent: vi.fn(),
22 + };
23 + return {
24 + webContents,
25 + sendCommand,
26 + send: (method: string, params: Record<string, unknown>) =>
27 + sendPageCommand(
28 + webContents as unknown as Electron.WebContents,
29 + { sendCommand } as unknown as Electron.Debugger,
30 + method,
31 + params,
32 + ),
33 + };
34 +};
35 +
36 +describe("preview guest input", () => {
37 + it("types into an unfocused guest's own page, not the app's focused field", async () => {
38 + const guest = makeGuest({ focused: false });
39 + await guest.send("Input.insertText", { text: "pairing-code" });
40 + expect(guest.webContents.insertText).toHaveBeenCalledWith("pairing-code");
41 + expect(guest.sendCommand).not.toHaveBeenCalledWith("Input.insertText", expect.anything());
42 + });
43 +
44 + it("uses CDP input while the guest holds focus, where it already reaches the page", async () => {
45 + const guest = makeGuest({ focused: true });
46 + await guest.send("Input.insertText", { text: "x" });
47 + await guest.send("Input.dispatchKeyEvent", { type: "keyUp", key: "a" });
48 + expect(guest.sendCommand.mock.calls.map(([method]) => method)).toEqual([
49 + "Input.insertText",
50 + "Input.dispatchKeyEvent",
51 + ]);
52 + expect(guest.webContents.insertText).not.toHaveBeenCalled();
53 + });
54 +
55 + it("refuses input when a cross-site frame holds the unfocused page's focus", async () => {
56 + const guest = makeGuest({ focused: false, focusedDocument: false });
57 + await expect(guest.send("Input.insertText", { text: "secret" })).rejects.toThrow(
58 + /cross-site frame/,
59 + );
60 + expect(guest.webContents.insertText).not.toHaveBeenCalled();
61 + });
62 +
63 + it("clears a field with Cmd+A and Delete while unfocused, never touching the clipboard", async () => {
64 + const guest = makeGuest({ focused: false });
65 + await guest.send("Input.dispatchKeyEvent", {
66 + type: "rawKeyDown",
67 + key: "a",
68 + modifiers: 4,
69 + commands: ["selectAll", "paste"],
70 + });
71 + await guest.send("Input.dispatchKeyEvent", { type: "rawKeyDown", key: "Delete" });
72 + expect(guest.webContents.sendInputEvent.mock.calls.map(([event]) => event)).toEqual([
73 + { type: "rawKeyDown", keyCode: "a", modifiers: ["meta"] },
74 + { type: "rawKeyDown", keyCode: "Delete", modifiers: [] },
75 + ]);
76 + const scripts = guest.sendCommand.mock.calls.map(([, params]) => params?.expression ?? "");
77 + expect(scripts.some((script) => script.includes('["selectAll"]'))).toBe(true);
78 + expect(scripts.some((script) => script.includes("paste"))).toBe(false);
79 + });
80 +
81 + it("does not run other page commands through the guest's direct input", async () => {
82 + const guest = makeGuest({ focused: false });
83 + await guest.send("Input.dispatchMouseEvent", { type: "mousePressed", x: 1, y: 1 });
84 + expect(guest.sendCommand).toHaveBeenCalledWith("Input.dispatchMouseEvent", {
85 + type: "mousePressed",
86 + x: 1,
87 + y: 1,
88 + });
89 + expect(guest.webContents.sendInputEvent).not.toHaveBeenCalled();
90 + });
91 +});
92 +
93 +describe("CDP key events as Electron input", () => {
94 + it("sends a key's text as char events after its key down", () => {
95 + expect(toKeyboardInputEvents({ type: "keyDown", key: "Enter", text: "\r" })).toEqual([
96 + { type: "rawKeyDown", keyCode: "Enter", modifiers: [] },
97 + { type: "char", keyCode: "\r", modifiers: [] },
98 + ]);
99 + expect(toKeyboardInputEvents({ type: "keyDown", key: "é", text: "é", modifiers: 8 })).toEqual([
100 + { type: "rawKeyDown", keyCode: "é", modifiers: ["shift"] },
101 + { type: "char", keyCode: "é", modifiers: ["shift"] },
102 + ]);
103 + });
104 +
105 + it("names arrows and function keys as Electron accelerators", () => {
106 + expect(toKeyboardInputEvents({ type: "keyUp", key: "ArrowLeft", modifiers: 3 })).toEqual([
107 + { type: "keyUp", keyCode: "Left", modifiers: ["alt", "control"] },
108 + ]);
109 + expect(toKeyboardInputEvents({ type: "rawKeyDown", key: "F12" })).toEqual([
110 + { type: "rawKeyDown", keyCode: "F12", modifiers: [] },
111 + ]);
112 + expect(toKeyboardInputEvents({ type: "rawKeyDown", key: "AudioVolumeUp" })).toEqual([]);
113 + });
114 +});
apps/desktop/src/preview/GuestInput.ts new
+150
@@ -0,0 +1,150 @@
1 +/**
2 + * Keyboard and text input for a preview tab's page that never lands outside it.
3 + *
4 + * Chromium sends a page's CDP key and text input to whichever frame holds focus
5 + * in the window. A `<webview>` guest shares that focus with the app around it,
6 + * so while a person works in the app, `Input.insertText` on the guest's own
7 + * debugger types into the app's focused field. Such input goes through CDP only
8 + * while the guest holds focus. Otherwise it goes straight to the guest's own
9 + * widget, which nothing redirects.
10 + */
11 +
12 +/** CDP input Chromium delivers to the window's focused frame rather than the page's. */
13 +const FOCUS_ROUTED_INPUT = new Set([
14 + "Input.insertText",
15 + "Input.dispatchKeyEvent",
16 + "Input.imeSetComposition",
17 +]);
18 +
19 +/**
20 + * Page script: the document holding the page's focus, or null when a cross-site
21 + * frame holds it. Electron's direct input reaches only the main frame's process,
22 + * and `insertText` crashes the page when focus is in another one.
23 + */
24 +const FOCUSED_DOCUMENT = `(() => {
25 + let doc = document;
26 + for (;;) {
27 + const active = doc.activeElement;
28 + if (active?.tagName !== "IFRAME" && active?.tagName !== "FRAME") return doc;
29 + if (!active.contentDocument) return null;
30 + doc = active.contentDocument;
31 + }
32 +})()`;
33 +
34 +/**
35 + * macOS editing commands a key press asks for (Cmd+A is `selectAll`), which
36 + * Chromium runs only for CDP keys. Clipboard commands stay out: they would read
37 + * or replace the person's clipboard.
38 + */
39 +const EDITING_COMMANDS = new Set(["selectAll", "undo", "redo"]);
40 +
41 +const CROSS_SITE_FOCUS_MESSAGE =
42 + "The page's focus is inside a cross-site frame, which takes typed input only while the preview has focus. Click the field first.";
43 +
44 +const ARROW_KEYS: Record<string, string> = {
45 + ArrowUp: "Up",
46 + ArrowDown: "Down",
47 + ArrowLeft: "Left",
48 + ArrowRight: "Right",
49 +};
50 +const NAMED_KEYS = new Set([
51 + "Backspace",
52 + "Tab",
53 + "Enter",
54 + "Escape",
55 + "Delete",
56 + "Insert",
57 + "Home",
58 + "End",
59 + "PageUp",
60 + "PageDown",
61 + "Shift",
62 + "Control",
63 + "Alt",
64 + "Meta",
65 + "CapsLock",
66 + "NumLock",
67 + "ScrollLock",
68 + "PrintScreen",
69 +]);
70 +const MODIFIER_BITS = [
71 + [1, "alt"],
72 + [2, "control"],
73 + [4, "meta"],
74 + [8, "shift"],
75 +] as const;
76 +
77 +/** Electron's accelerator name for a DOM key value, or null when it has none. */
78 +const keyCodeFor = (key: string) => {
79 + if ([...key].length === 1) return key;
80 + if (ARROW_KEYS[key]) return ARROW_KEYS[key];
81 + return NAMED_KEYS.has(key) || /^F(?:[1-9]|1\d|2[0-4])$/u.test(key) ? key : null;
82 +};
83 +
84 +/**
85 + * The Electron key events for one CDP `Input.dispatchKeyEvent`. Electron
86 + * derives key, code, and a char's text from `keyCode`, so typed text travels
87 + * as `char` events of its own.
88 + */
89 +export const toKeyboardInputEvents = (
90 + params: Record<string, unknown>,
91 +): Array<Electron.KeyboardInputEvent> => {
92 + const bits = typeof params["modifiers"] === "number" ? params["modifiers"] : 0;
93 + const modifiers = MODIFIER_BITS.flatMap(([bit, name]) => (bits & bit ? [name] : []));
94 + const text = typeof params["text"] === "string" ? params["text"] : "";
95 + const chars = [...text].map((char) => ({ type: "char" as const, keyCode: char, modifiers }));
96 + const keyCode = keyCodeFor(typeof params["key"] === "string" ? params["key"] : "");
97 + switch (params["type"]) {
98 + case "keyDown":
99 + return [...(keyCode ? [{ type: "rawKeyDown" as const, keyCode, modifiers }] : []), ...chars];
100 + case "rawKeyDown":
101 + case "keyUp":
102 + return keyCode ? [{ type: params["type"], keyCode, modifiers }] : [];
103 + case "char":
104 + return chars;
105 + default:
106 + return [];
107 + }
108 +};
109 +
110 +const evaluate = async (debuggee: Electron.Debugger, expression: string) => {
111 + const reply = (await debuggee.sendCommand("Runtime.evaluate", {
112 + expression,
113 + returnByValue: true,
114 + })) as { readonly result?: { readonly value?: unknown } };
115 + return reply.result?.value;
116 +};
117 +
118 +/** Sends one command to the guest's page, keeping key and text input inside it. */
119 +export const sendPageCommand = async (
120 + webContents: Electron.WebContents,
121 + debuggee: Electron.Debugger,
122 + method: string,
123 + params: Record<string, unknown>,
124 +): Promise<unknown> => {
125 + if (!FOCUS_ROUTED_INPUT.has(method) || webContents.focusedFrame) {
126 + return debuggee.sendCommand(method, params);
127 + }
128 + if ((await evaluate(debuggee, `${FOCUSED_DOCUMENT} !== null`)) !== true) {
129 + throw new Error(CROSS_SITE_FOCUS_MESSAGE);
130 + }
131 + switch (method) {
132 + case "Input.insertText":
133 + await webContents.insertText(typeof params["text"] === "string" ? params["text"] : "");
134 + return {};
135 + case "Input.dispatchKeyEvent": {
136 + for (const event of toKeyboardInputEvents(params)) webContents.sendInputEvent(event);
137 + const commands = Array.isArray(params["commands"])
138 + ? params["commands"].filter((command) => EDITING_COMMANDS.has(command))
139 + : [];
140 + // Runs after the page handles the keys, so the reply also waits for them.
141 + await evaluate(
142 + debuggee,
143 + `(() => { const doc = ${FOCUSED_DOCUMENT}; for (const name of ${JSON.stringify(commands)}) doc?.execCommand(name); return 0; })()`,
144 + );
145 + return {};
146 + }
147 + default:
148 + throw new Error(`${method} needs the preview to have focus.`);
149 + }
150 +};