Skip to content
Merged
128 changes: 128 additions & 0 deletions apps/desktop/src/preview/DesktopBrowserHost.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
const decodeCdpReply = Schema.decodeUnknownSync(
Schema.fromJsonString(Schema.Struct({ id: Schema.Number })),
);
const decodeCdpError = Schema.decodeUnknownSync(
Schema.fromJsonString(
Schema.Struct({ error: Schema.optional(Schema.Struct({ message: Schema.String })) }),
),
);
const decodeCdpMessage = Schema.decodeUnknownSync(
Schema.fromJsonString(
Schema.Struct({
Expand Down Expand Up @@ -55,13 +60,16 @@ const makeDebuggee = (
/** Electron's capture of this guest never settles. */
readonly capturesStall?: () => boolean;
readonly refuse?: (method: string, sessionId: string | undefined) => boolean;
/** Answers a command at once with this value, unless it returns undefined. */
readonly answer?: (method: string, sessionId: string | undefined) => unknown;
} = {},
) => {
const emitter = new NodeEvents.EventEmitter();
const pending: Array<() => void> = [];
const focusChanges: Array<() => void> = [];
const sent: Array<unknown> = [];
const methods: Array<string> = [];
const sessionIds: Array<string | undefined> = [];
const rejects: Array<() => void> = [];
const sendWaiters: Array<() => void> = [];
const focusEmulation: Array<boolean> = [];
Expand All @@ -86,8 +94,14 @@ const makeDebuggee = (
else resolve({});
return;
}
const answer = options.answer?.(method, sessionId);
if (answer !== undefined) {
resolve(answer);
return;
}
sent.push(params?.id);
methods.push(method);
sessionIds.push(sessionId);
rejects.push(() => reject(new Error("Refused")));
pending.push(() => resolve({ method }));
sendWaiters.shift()?.();
Expand Down Expand Up @@ -125,6 +139,8 @@ const makeDebuggee = (
sent,
/** Methods of the same commands, in order. */
methods,
/** Sessions of the same commands, in order; undefined for the page. */
sessionIds,
/** Refuses the pending command the debugger received with this id. */
refuse: (id: number) => rejects[sent.indexOf(id)]?.(),
focusEmulation,
Expand Down Expand Up @@ -1094,6 +1110,118 @@ describe("DesktopBrowserHost", () => {
}),
);

it.effect("finds the frame under the mouse only on a guest the window does not show", () =>
Effect.gen(function* () {
const host = yield* makeDrawnHost;
const debuggee = makeDebuggee();
host.attach(key, debuggee.tab);
const move = (id: number) =>
host.handleCommandLine(
encodeJson({
type: "cdp",
...key,
message: encodeJson({
id,
method: "Input.dispatchMouseEvent",
params: { id, type: "mouseMoved", x: 5, y: 5 },
sessionId: "t3-preview-page",
}),
}),
);

// No cross-site frame is attached yet.
yield* move(1);
yield* settle;
expect(debuggee.methods).toEqual(["Input.dispatchMouseEvent"]);
debuggee.release();

debuggee.emit("Target.attachedToTarget", {
sessionId: "FRAME-SESSION",
targetInfo: { targetId: "FRAME", type: "iframe" },
});
yield* move(2);
yield* settle;
expect(debuggee.methods.at(-1)).toBe("Page.getLayoutMetrics");
// A lookup that fails leaves the event on the page.
debuggee.releaseFirst();
yield* settle;
expect(debuggee.methods.at(-1)).toBe("Input.dispatchMouseEvent");
debuggee.release();

host.setShown(key, true);
yield* move(3);
yield* settle;
debuggee.release();
host.setShown(key, false);
debuggee.emit("Target.detachedFromTarget", { sessionId: "FRAME-SESSION" });
yield* move(4);
yield* settle;
expect(debuggee.methods.slice(-2)).toEqual([
"Input.dispatchMouseEvent",
"Input.dispatchMouseEvent",
]);
expect(debuggee.methods.filter((method) => method === "Page.getLayoutMetrics")).toHaveLength(
1,
);
}),
);

it.effect("fails mouse input whose frame detaches before taking it, then moves on", () =>
Effect.gen(function* () {
const host = yield* makeDrawnHost;
const lookup: Record<string, unknown> = {
"Page.getLayoutMetrics": { cssLayoutViewport: { pageX: 0, pageY: 0 } },
"DOM.getNodeForLocation": { backendNodeId: 1 },
"DOM.describeNode": { node: { frameId: "FRAME" } },
"DOM.getBoxModel": { model: { content: [0, 0, 100, 0, 100, 100, 0, 100] } },
};
const debuggee = makeDebuggee({ answer: (method) => lookup[method] });
host.attach(key, debuggee.tab);
const errors: Array<string> = [];
yield* host.events.pipe(
Stream.map((line) => decodeEvent(new TextDecoder().decode(line))),
Stream.runForEach((event) =>
Effect.sync(() => {
if (event.type !== "cdp") return;
const { error } = decodeCdpError(event.message);
if (error) errors.push(error.message);
}),
),
Effect.forkScoped,
);
yield* Effect.yieldNow;
const mouse = (id: number, type: string) =>
host.handleCommandLine(
encodeJson({
type: "cdp",
...key,
message: encodeJson({
id,
method: "Input.dispatchMouseEvent",
params: { id, type, x: 5, y: 5 },
sessionId: "t3-preview-page",
}),
}),
);

debuggee.emit("Target.attachedToTarget", {
sessionId: "FRAME-SESSION",
targetInfo: { targetId: "FRAME", type: "iframe" },
});
yield* mouse(1, "mousePressed");
yield* settle;
expect(debuggee.sessionIds).toEqual(["FRAME-SESSION"]);

// Chromium never acknowledges input on a frame that detaches first.
debuggee.emit("Target.detachedFromTarget", { sessionId: "FRAME-SESSION" });
yield* settle;
expect(errors).toEqual([expect.stringContaining("went away before it took this input")]);
yield* mouse(2, "mouseReleased");
yield* settle;
expect(debuggee.sessionIds).toEqual(["FRAME-SESSION", undefined]);
}),
);

it.effect("paints a hidden guest only while the screenshot it is taking is pending", () =>
Effect.gen(function* () {
const host = yield* makeDrawnHost;
Expand Down
82 changes: 80 additions & 2 deletions apps/desktop/src/preview/DesktopBrowserHost.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,12 @@ import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";

import { createCdpRelayConnection, type CdpRelayConnection } from "./CdpRelay.ts";
import { sendPageCommand } from "./GuestInput.ts";
import {
type FrameDetachWatch,
type PointerRoute,
routeMouseToFrame,
sendPageCommand,
} from "./GuestInput.ts";

const encodeEvent = Schema.encodeSync(Schema.fromJsonString(DesktopBrowserEvent));
const decodeCommand = Schema.decodeUnknownOption(Schema.fromJsonString(DesktopBrowserCommand));
Expand Down Expand Up @@ -56,6 +61,55 @@ export interface DesktopBrowserTabDebugger {

const keyOf = ({ threadId, tabId }: DesktopBrowserTabKey) => `${threadId}\u0000${tabId}`;

const trackFrameSession = (
tab: {
readonly frameSessions: Map<string, string>;
readonly frameDetachListeners: Map<string, Set<() => void>>;
},
method: string,
params: unknown,
) => {
if (method === "Target.attachedToTarget") {
const { sessionId, targetInfo } = params as {
readonly sessionId?: string;
readonly targetInfo?: { readonly targetId?: string; readonly type?: string };
};
if (targetInfo?.type === "iframe" && targetInfo.targetId && sessionId) {
tab.frameSessions.set(targetInfo.targetId, sessionId);
}
} else if (method === "Target.detachedFromTarget") {
const { sessionId } = params as { readonly sessionId?: string };
for (const [frameId, frameSession] of tab.frameSessions) {
if (frameSession === sessionId) tab.frameSessions.delete(frameId);
}
if (sessionId === undefined) return;
const listeners = tab.frameDetachListeners.get(sessionId);
tab.frameDetachListeners.delete(sessionId);
for (const listener of listeners ?? []) listener();
}
};

const watchFrameDetach =
(tab: {
readonly frameSessions: Map<string, string>;
readonly frameDetachListeners: Map<string, Set<() => void>>;
}): FrameDetachWatch =>
(sessionId, listener) => {
if (![...tab.frameSessions.values()].includes(sessionId)) {
listener();
return () => {};
}
const listeners = tab.frameDetachListeners.get(sessionId) ?? new Set();
tab.frameDetachListeners.set(sessionId, listeners);
listeners.add(listener);
return () => {
listeners.delete(listener);
if (listeners.size === 0 && tab.frameDetachListeners.get(sessionId) === listeners) {
tab.frameDetachListeners.delete(sessionId);
}
};
};

interface AttachedTab {
readonly key: DesktopBrowserTabKey;
readonly debuggee: DesktopBrowserTabDebugger;
Expand All @@ -81,6 +135,10 @@ interface AttachedTab {
readonly capturing: Set<object>;
/** Each wait on the guest's next frame, as whether it still waits; the guest is prodded until none do. */
readonly frameWaits: Set<() => boolean>;
/** Sessions of the guest's cross-site frames that Chromium attached, by frame id. */
readonly frameSessions: Map<string, string>;
/** Input sent to a frame session, waiting to learn if the frame detaches first. */
readonly frameDetachListeners: Map<string, Set<() => void>>;
nudging: Fiber.Fiber<void> | null;
/** A wait outlasted its first nudge, so the guest is painted and unthrottled like a capture. */
frameStalled: boolean;
Expand Down Expand Up @@ -437,8 +495,19 @@ export const make = Effect.gen(function* () {
const relayFor = (tab: AttachedTab) => {
if (tab.relay) return tab.relay;
const { webContents, debugger: debuggee, cookiesCleared } = tab.debuggee;
const routeHidden = routeMouseToFrame(debuggee, tab.frameSessions, watchFrameDetach(tab));
// Read when the pointer queue reaches the event: a guest the window shows routes its own input.
const routeMouse: PointerRoute = (params) =>
shownTabs.get(keyOf(tab.key)) === true ? Promise.resolve(null) : routeHidden(params);
const send = async (method: string, params: Record<string, unknown>, sessionId?: string) => {
const result = await sendPageCommand(webContents, debuggee, method, params, sessionId);
const result = await sendPageCommand(
webContents,
debuggee,
method,
params,
sessionId,
routeMouse,
);
if (method === "Network.clearBrowserCookies") await cookiesCleared?.();
return result;
};
Expand Down Expand Up @@ -595,6 +664,12 @@ export const make = Effect.gen(function* () {
tab.relay = null;
tab.debuggee.debugger.off("message", tab.onMessage);
tab.debuggee.webContents.off("did-navigate", tab.onNewDocument);
// Input routed to a frame would wait for a detach event the tab no longer hears.
const listeners = [...tab.frameDetachListeners.values()].flatMap((set) => [...set]);
tab.frameDetachListeners.clear();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// A route resolved after this would find no session and go to the page.
tab.frameSessions.clear();
for (const listener of listeners) listener();
syncPainting(tab);
if (announced) emit({ type: "detached", ...key });
};
Expand All @@ -619,6 +694,8 @@ export const make = Effect.gen(function* () {
focusPending: new Map(),
capturing: new Set(),
frameWaits: new Set(),
frameSessions: new Map(),
frameDetachListeners: new Map(),
nudging: null,
frameStalled: false,
painting: false,
Expand All @@ -630,6 +707,7 @@ export const make = Effect.gen(function* () {
const guid = (params as { guid?: unknown } | undefined)?.guid;
tab.pendingDownloadGuid = typeof guid === "string" ? guid : null;
}
trackFrameSession(tab, method, params);
tab.relay?.event(method, params, sessionId);
},
// A screenshot pending when the page loads a new document, a reload included, can
Expand Down
Loading
Loading