@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

main
ts 217 lines 7.58 KB
Raw
1 // CDP input follows shared window focus; send directly to unfocused guests to avoid typing into the app.
2
3 const FOCUS_ROUTED_INPUT = new Set([
4 "Input.insertText",
5 "Input.dispatchKeyEvent",
6 "Input.imeSetComposition",
7 ]);
8
9 /** Direct input reaches only the main-frame process; insertText crashes when a cross-site frame has focus. */
10 const FOCUSED_DOCUMENT = `(() => {
11 let doc = document;
12 for (;;) {
13 const active = doc.activeElement;
14 if (active?.tagName !== "IFRAME" && active?.tagName !== "FRAME") return doc;
15 if (!active.contentDocument) return null;
16 doc = active.contentDocument;
17 }
18 })()`;
19
20 /** Electron runs editing commands only for CDP keys; exclude clipboard commands to preserve the user's clipboard. */
21 const EDITING_COMMANDS = new Set(["selectAll", "undo", "redo"]);
22
23 const CROSS_SITE_FOCUS_MESSAGE =
24 "The page's focus is inside a cross-site frame, which takes typed input only while the preview has focus. Click the field first.";
25
26 const ARROW_KEYS: Record<string, string> = {
27 ArrowUp: "Up",
28 ArrowDown: "Down",
29 ArrowLeft: "Left",
30 ArrowRight: "Right",
31 };
32 const NAMED_KEYS = new Set([
33 "Backspace",
34 "Tab",
35 "Enter",
36 "Escape",
37 "Delete",
38 "Insert",
39 "Home",
40 "End",
41 "PageUp",
42 "PageDown",
43 "Shift",
44 "Control",
45 "Alt",
46 "Meta",
47 "CapsLock",
48 "NumLock",
49 "ScrollLock",
50 "PrintScreen",
51 ]);
52 const MODIFIER_BITS = [
53 [1, "alt"],
54 [2, "control"],
55 [4, "meta"],
56 [8, "shift"],
57 ] as const;
58
59 const keyCodeFor = (key: string) => {
60 if ([...key].length === 1) return key;
61 if (ARROW_KEYS[key]) return ARROW_KEYS[key];
62 return NAMED_KEYS.has(key) || /^F(?:[1-9]|1\d|2[0-4])$/u.test(key) ? key : null;
63 };
64
65 /** Electron derives text from keyCode, so typed text needs separate char events. */
66 export const toKeyboardInputEvents = (
67 params: Record<string, unknown>,
68 ): Array<Electron.KeyboardInputEvent> => {
69 const bits = typeof params["modifiers"] === "number" ? params["modifiers"] : 0;
70 const modifiers = MODIFIER_BITS.flatMap(([bit, name]) => (bits & bit ? [name] : []));
71 const text = typeof params["text"] === "string" ? params["text"] : "";
72 const chars = [...text].map((char) => ({ type: "char" as const, keyCode: char, modifiers }));
73 const keyCode = keyCodeFor(typeof params["key"] === "string" ? params["key"] : "");
74 switch (params["type"]) {
75 case "keyDown":
76 return [...(keyCode ? [{ type: "rawKeyDown" as const, keyCode, modifiers }] : []), ...chars];
77 case "rawKeyDown":
78 case "keyUp":
79 return keyCode ? [{ type: params["type"], keyCode, modifiers }] : [];
80 case "char":
81 return chars;
82 default:
83 return [];
84 }
85 };
86
87 const evaluate = async (debuggee: Electron.Debugger, expression: string) => {
88 const reply = (await debuggee.sendCommand("Runtime.evaluate", {
89 expression,
90 returnByValue: true,
91 })) as { readonly result?: { readonly value?: unknown } };
92 return reply.result?.value;
93 };
94
95 /** Host focus shared by the presses in flight in one window, so a later press keeps the field an earlier one saved. */
96 const HOST_FOCUS = "globalThis.__t3PreviewFocus";
97
98 /** A CDP pointer press focuses the guest's native view even with focus emulation enabled. */
99 const sendPointerPress = async (
100 webContents: Electron.WebContents,
101 debuggee: Electron.Debugger,
102 method: string,
103 params: Record<string, unknown>,
104 sessionId: string | undefined,
105 ) => {
106 const host = webContents.hostWebContents;
107 if (!host || host.isDestroyed() || webContents.focusedFrame) {
108 return debuggee.sendCommand(method, params, sessionId);
109 }
110 // Focus in a webview with a press in flight came from that press, so keep the earlier save.
111 await host.executeJavaScript(`(() => {
112 const state = (${HOST_FOCUS} ??= { saved: null, presses: [] });
113 const active = document.activeElement;
114 let pressed = false;
115 try {
116 pressed = active?.tagName === "WEBVIEW" && state.presses.includes(active.getWebContentsId());
117 } catch {}
118 if (!pressed) {
119 state.saved = active && active !== document.body && active.tagName !== "WEBVIEW" ? active : null;
120 }
121 state.presses.push(${webContents.id});
122 })()`);
123 try {
124 return await debuggee.sendCommand(method, params, sessionId);
125 } finally {
126 if (!host.isDestroyed()) {
127 // Membership check: a host reload starts a new state without this press.
128 await host.executeJavaScript(`(() => {
129 const state = ${HOST_FOCUS};
130 const index = state ? state.presses.indexOf(${webContents.id}) : -1;
131 if (index < 0) return;
132 state.presses.splice(index, 1);
133 if (state.presses.length === 0) delete ${HOST_FOCUS};
134 const current = document.activeElement;
135 try {
136 if (state.saved?.isConnected && current?.tagName === "WEBVIEW" &&
137 current.getWebContentsId() === ${webContents.id}) state.saved.focus({ preventScroll: true });
138 } catch {}
139 })()`);
140 }
141 }
142 };
143
144 const pointerCommands = new WeakMap<Electron.WebContents, Promise<unknown>>();
145
146 /** Focus capture crosses processes; later pointer events must not overtake the press. */
147 const sendPointerCommand = async (
148 webContents: Electron.WebContents,
149 debuggee: Electron.Debugger,
150 method: string,
151 params: Record<string, unknown>,
152 sessionId: string | undefined,
153 ) => {
154 const previous = pointerCommands.get(webContents) ?? Promise.resolve();
155 const current = previous
156 .catch(() => {})
157 .then(() =>
158 params["type"] === "mousePressed" || params["type"] === "touchStart"
159 ? sendPointerPress(webContents, debuggee, method, params, sessionId)
160 : debuggee.sendCommand(method, params, sessionId),
161 );
162 pointerCommands.set(webContents, current);
163 try {
164 return await current;
165 } finally {
166 if (pointerCommands.get(webContents) === current) pointerCommands.delete(webContents);
167 }
168 };
169
170 /** Sends one command to the guest's page, keeping reloads and input inside it. */
171 export const sendPageCommand = async (
172 webContents: Electron.WebContents,
173 debuggee: Electron.Debugger,
174 method: string,
175 params: Record<string, unknown>,
176 sessionId?: string,
177 ): Promise<unknown> => {
178 if (method === "Input.dispatchMouseEvent" || method === "Input.dispatchTouchEvent") {
179 return sendPointerCommand(webContents, debuggee, method, params, sessionId);
180 }
181 if (sessionId !== undefined) return debuggee.sendCommand(method, params, sessionId);
182 // Electron's debugger routes Page.reload on a webview to its embedder window.
183 if (method === "Page.reload") {
184 if (params["ignoreCache"] === true) webContents.reloadIgnoringCache();
185 else webContents.reload();
186 return {};
187 }
188 if (method === "Page.stopLoading") {
189 webContents.stop();
190 return {};
191 }
192 if (!FOCUS_ROUTED_INPUT.has(method) || webContents.focusedFrame) {
193 return debuggee.sendCommand(method, params);
194 }
195 if ((await evaluate(debuggee, `${FOCUSED_DOCUMENT} !== null`)) !== true) {
196 throw new Error(CROSS_SITE_FOCUS_MESSAGE);
197 }
198 switch (method) {
199 case "Input.insertText":
200 await webContents.insertText(typeof params["text"] === "string" ? params["text"] : "");
201 return {};
202 case "Input.dispatchKeyEvent": {
203 for (const event of toKeyboardInputEvents(params)) webContents.sendInputEvent(event);
204 const commands = Array.isArray(params["commands"])
205 ? params["commands"].filter((command) => EDITING_COMMANDS.has(command))
206 : [];
207 // Runs after the page handles the keys, so the reply also waits for them.
208 await evaluate(
209 debuggee,
210 `(() => { const doc = ${FOCUSED_DOCUMENT}; for (const name of ${JSON.stringify(commands)}) doc?.execCommand(name); return 0; })()`,
211 );
212 return {};
213 }
214 default:
215 throw new Error(`${method} needs the preview to have focus.`);
216 }
217 };