Open History to see the last commit
1import * as NodeVM from "node:vm";
2
3import { describe, expect, it, vi } from "vite-plus/test";
4
5import { sendPageCommand, toKeyboardInputEvents } from "./GuestInput.ts";
6
7const makeGuest = ({
8 focused,
9 focusedDocument = true,
10}: {
11 readonly focused: boolean;
12 readonly focusedDocument?: boolean;
13}) => {
14 const sendCommand = vi.fn(async (method: string, params?: { expression?: string }) =>
15 method === "Runtime.evaluate" && params?.expression?.endsWith("!== null")
16 ? { result: { value: focusedDocument } }
17 : { result: {} },
18 );
19 const webContents = {
20 focusedFrame: focused ? {} : null,
21 insertText: vi.fn(async () => {}),
22 sendInputEvent: vi.fn(),
23 reload: vi.fn(),
24 reloadIgnoringCache: vi.fn(),
25 };
26 return {
27 webContents,
28 sendCommand,
29 send: (method: string, params: Record<string, unknown>) =>
30 sendPageCommand(
31 webContents as unknown as Electron.WebContents,
32 { sendCommand } as unknown as Electron.Debugger,
33 method,
34 params,
35 ),
36 };
37};
38
39describe("preview guest input", () => {
40 it("types into an unfocused guest's own page, not the app's focused field", async () => {
41 const guest = makeGuest({ focused: false });
42 await guest.send("Input.insertText", { text: "pairing-code" });
43 expect(guest.webContents.insertText).toHaveBeenCalledWith("pairing-code");
44 expect(guest.sendCommand).not.toHaveBeenCalledWith("Input.insertText", expect.anything());
45 });
46
47 it.each([
48 {
49 sessionId: undefined,
50 method: "Input.dispatchMouseEvent",
51 type: "mousePressed",
52 outcome: "restore",
53 },
54 {
55 sessionId: "child-frame",
56 method: "Input.dispatchMouseEvent",
57 type: "mousePressed",
58 outcome: "restore",
59 },
60 {
61 sessionId: undefined,
62 method: "Input.dispatchTouchEvent",
63 type: "touchStart",
64 outcome: "restore",
65 },
66 {
67 sessionId: undefined,
68 method: "Input.dispatchMouseEvent",
69 type: "mousePressed",
70 outcome: "other-field",
71 },
72 {
73 sessionId: undefined,
74 method: "Input.dispatchMouseEvent",
75 type: "mousePressed",
76 outcome: "removed",
77 },
78 {
79 sessionId: undefined,
80 method: "Input.dispatchMouseEvent",
81 type: "mousePressed",
82 outcome: "failure",
83 },
84 ])(
85 "preserves host focus for $method in $sessionId with $outcome",
86 async ({ sessionId, method, type, outcome }) => {
87 const document = { activeElement: {} as object };
88 const composer = {
89 isConnected: true,
90 focus: () => {
91 document.activeElement = composer;
92 },
93 };
94 const preview = { tagName: "WEBVIEW", getWebContentsId: () => 7 };
95 const otherField = { tagName: "INPUT" };
96 document.activeElement = composer;
97 const context = NodeVM.createContext({ document });
98 const host = {
99 isDestroyed: () => false,
100 executeJavaScript: async (script: string) => NodeVM.runInContext(script, context),
101 };
102 const guest = { id: 7, focusedFrame: null, hostWebContents: host };
103 const debuggee = {
104 sendCommand: async () => {
105 document.activeElement = outcome === "other-field" ? otherField : preview;
106 if (outcome === "removed") composer.isConnected = false;
107 if (outcome === "failure") throw new Error("Pointer failed");
108 return {};
109 },
110 };
111 const result = sendPageCommand(
112 guest as unknown as Electron.WebContents,
113 debuggee as unknown as Electron.Debugger,
114 method,
115 { type, x: 10, y: 10, button: "left" },
116 sessionId,
117 );
118 if (outcome === "failure") await expect(result).rejects.toThrow("Pointer failed");
119 else await result;
120 expect(document.activeElement).toBe(
121 outcome === "other-field" ? otherField : outcome === "removed" ? preview : composer,
122 );
123 expect(Object.keys(context)).toEqual(["document"]);
124 },
125 );
126
127 it.each([{ userClicksStuckTab: false }, { userClicksStuckTab: true }])(
128 "keeps the right focus when a sibling press finishes beside a stuck one, user clicks: $userClicksStuckTab",
129 async ({ userClicksStuckTab }) => {
130 const document = { activeElement: {} as object };
131 const composer = {
132 isConnected: true,
133 focus: () => {
134 document.activeElement = composer;
135 },
136 };
137 document.activeElement = composer;
138 const context = NodeVM.createContext({ document });
139 const host = {
140 isDestroyed: () => false,
141 executeJavaScript: async (script: string) => NodeVM.runInContext(script, context),
142 };
143 const previews = new Map(
144 [7, 8].map((id) => [id, { tagName: "WEBVIEW", getWebContentsId: () => id }]),
145 );
146 const stuckPressFocused = Promise.withResolvers<void>();
147 const stuckPressEnds = Promise.withResolvers<void>();
148 const press = (id: number) => {
149 const debuggee = {
150 sendCommand: async () => {
151 document.activeElement = previews.get(id)!;
152 if (id === 7) {
153 stuckPressFocused.resolve();
154 await stuckPressEnds.promise;
155 } else if (userClicksStuckTab) {
156 document.activeElement = previews.get(7)!;
157 }
158 return {};
159 },
160 };
161 return sendPageCommand(
162 { id, focusedFrame: null, hostWebContents: host } as unknown as Electron.WebContents,
163 debuggee as unknown as Electron.Debugger,
164 "Input.dispatchMouseEvent",
165 { type: "mousePressed", x: 10, y: 10, button: "left" },
166 );
167 };
168 // A press held open, as by a page's confirm() on mousedown, must not block or win focus.
169 const stuck = press(7);
170 await stuckPressFocused.promise;
171 await press(8);
172 const expected = userClicksStuckTab ? previews.get(7) : composer;
173 expect(document.activeElement).toBe(expected);
174 stuckPressEnds.resolve();
175 await stuck;
176 expect(Object.keys(context)).toEqual(["document"]);
177 },
178 );
179
180 it.each([
181 {
182 method: "Input.dispatchMouseEvent",
183 press: "mousePressed",
184 release: "mouseReleased",
185 failPress: false,
186 },
187 {
188 method: "Input.dispatchTouchEvent",
189 press: "touchStart",
190 release: "touchEnd",
191 failPress: false,
192 },
193 {
194 method: "Input.dispatchMouseEvent",
195 press: "mousePressed",
196 release: "mouseReleased",
197 failPress: true,
198 },
199 ])(
200 "keeps $method releases behind presses waiting for host focus, failed press: $failPress",
201 async ({ method, press, release, failPress }) => {
202 const captureStarted = Promise.withResolvers<void>();
203 const finishCapture = Promise.withResolvers<void>();
204 const events: Array<unknown> = [];
205 const guest = {
206 id: 7,
207 focusedFrame: null,
208 hostWebContents: {
209 isDestroyed: () => false,
210 executeJavaScript: async () => {
211 captureStarted.resolve();
212 await finishCapture.promise;
213 },
214 },
215 };
216 const debuggee = {
217 sendCommand: async (_method: string, params: Record<string, unknown>) => {
218 events.push(params["type"]);
219 if (failPress && params["type"] === press) throw new Error("Press failed");
220 return {};
221 },
222 };
223 const send = (type: string) =>
224 sendPageCommand(
225 guest as unknown as Electron.WebContents,
226 debuggee as unknown as Electron.Debugger,
227 method,
228 { type },
229 );
230 const pressed = send(press);
231 await captureStarted.promise;
232 const released = send(release);
233 finishCapture.resolve();
234 const results = await Promise.allSettled([pressed, released]);
235 expect(results.map((result) => result.status)).toEqual([
236 failPress ? "rejected" : "fulfilled",
237 "fulfilled",
238 ]);
239 expect(events).toEqual([press, release]);
240 },
241 );
242
243 it("refuses input when a cross-site frame holds the unfocused page's focus", async () => {
244 const guest = makeGuest({ focused: false, focusedDocument: false });
245 await expect(guest.send("Input.insertText", { text: "secret" })).rejects.toThrow(
246 /cross-site frame/,
247 );
248 expect(guest.webContents.insertText).not.toHaveBeenCalled();
249 });
250});
251
252describe("CDP key events as Electron input", () => {
253 it("sends a key's text as char events after its key down", () => {
254 expect(toKeyboardInputEvents({ type: "keyDown", key: "Enter", text: "\r" })).toEqual([
255 { type: "rawKeyDown", keyCode: "Enter", modifiers: [] },
256 { type: "char", keyCode: "\r", modifiers: [] },
257 ]);
258 expect(toKeyboardInputEvents({ type: "keyDown", key: "é", text: "é", modifiers: 8 })).toEqual([
259 { type: "rawKeyDown", keyCode: "é", modifiers: ["shift"] },
260 { type: "char", keyCode: "é", modifiers: ["shift"] },
261 ]);
262 });
263
264 // regression: #18556 agent typing in a preview tab landed in the app instead of the guest
265 it("names arrows and function keys as Electron accelerators", () => {
266 expect(toKeyboardInputEvents({ type: "keyUp", key: "ArrowLeft", modifiers: 3 })).toEqual([
267 { type: "keyUp", keyCode: "Left", modifiers: ["alt", "control"] },
268 ]);
269 expect(toKeyboardInputEvents({ type: "rawKeyDown", key: "F12" })).toEqual([
270 { type: "rawKeyDown", keyCode: "F12", modifiers: [] },
271 ]);
272 expect(toKeyboardInputEvents({ type: "rawKeyDown", key: "AudioVolumeUp" })).toEqual([]);
273 });
274});