TypeScript
fix(desktop): keep preview download settings out of app exports (#25428)
Isaac Mayese7c375d6ed8f
diff --git a/apps/desktop/src/preview/CdpRelay.test.ts b/apps/desktop/src/preview/CdpRelay.test.tsindex a2589edf8f7..d409ad8b42e 100644--- a/apps/desktop/src/preview/CdpRelay.test.ts+++ b/apps/desktop/src/preview/CdpRelay.test.ts@@ -171,7 +171,7 @@ describe("CDP relay extra sessions", () => {});describe("CDP relay downloads", () => {- it("applies the server's download directory and reports downloads on the root session", async () => {+ it("captures preview downloads without changing the default browser context", async () => {const send = vi.fn(async () => ({}));const directories: Array<string | null> = [];const written: Array<Record<string, unknown>> = [];@@ -194,17 +194,110 @@ describe("CDP relay downloads", () => {);await settle();expect(directories).toEqual(["/srv/artifacts"]);- expect(send).toHaveBeenCalledWith(- "Browser.setDownloadBehavior",- { behavior: "allowAndName", downloadPath: "/srv/artifacts", eventsEnabled: true },- undefined,- );+ expect(send.mock.calls).toEqual([+ ["Page.setDownloadBehavior", { behavior: "default" }, undefined],+ ]);written.length = 0;- relay.event("Browser.downloadWillBegin", { guid: "g1", suggestedFilename: "r.csv" }, "");+ relay.event("Page.downloadWillBegin", { guid: "g1", suggestedFilename: "r.csv" }, "");+ relay.event("Page.downloadProgress", { guid: "g1", state: "completed" }, "");expect(written).toEqual([{ method: "Browser.downloadWillBegin", params: { guid: "g1", suggestedFilename: "r.csv" } },+ { method: "Browser.downloadProgress", params: { guid: "g1", state: "completed" } },]);});++ it("keeps denial scoped to the preview and restores Electron's save handling when allowed", async () => {+ const send = vi.fn(async () => ({}));+ const directories: Array<string | null> = [];+ const relay = makeRelay(+ makeTarget(send, (directory) => directories.push(directory)),+ () => {},+ );+ for (const [id, behavior] of ["deny", "allowAndName"].entries()) {+ relay.receive(+ JSON.stringify({+ id,+ method: "Browser.setDownloadBehavior",+ params: { behavior, downloadPath: "/srv/artifacts" },+ }),+ );+ await settle();+ }+ expect(directories).toEqual([null, "/srv/artifacts"]);+ expect(send.mock.calls).toEqual([+ ["Page.setDownloadBehavior", { behavior: "deny" }, undefined],+ ["Page.setDownloadBehavior", { behavior: "default" }, undefined],+ ]);+ });++ it("does not publish download events when the connection has disabled them", async () => {+ const written: Array<Record<string, unknown>> = [];+ const relay = makeRelay(makeTarget(vi.fn(async () => ({}))), (raw) =>+ written.push(JSON.parse(raw)),+ );+ relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));+ relay.receive(+ JSON.stringify({+ id: 2,+ method: "Browser.setDownloadBehavior",+ params: { behavior: "allowAndName", downloadPath: "/srv/artifacts", eventsEnabled: false },+ }),+ );+ await settle();+ written.length = 0;+ relay.event("Page.downloadWillBegin", { guid: "g1" }, "");+ relay.event("Page.downloadProgress", { guid: "g1", state: "completed" }, "");+ expect(written).toEqual([]);+ });++ it.each([false, true])(+ "keeps the previous download configuration (events enabled: %s) when configuration fails",+ async (enabled) => {+ const send = vi+ .fn(async () => ({}))+ .mockResolvedValueOnce({})+ .mockRejectedValueOnce(new Error("Page command rejected"));+ const written: Array<Record<string, unknown>> = [];+ let directory: string | null = null;+ const relay = makeRelay(+ makeTarget(send, (value) => {+ directory = value;+ }),+ (raw) => written.push(JSON.parse(raw)),+ );+ relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));+ for (const [id, eventsEnabled] of [enabled, !enabled].entries()) {+ relay.receive(+ JSON.stringify({+ id: id + 2,+ method: "Browser.setDownloadBehavior",+ params: {+ behavior: id === 1 && enabled ? "deny" : "allowAndName",+ downloadPath: id === 0 ? "/srv/artifacts" : "/srv/new-artifacts",+ eventsEnabled,+ },+ }),+ );+ await settle();+ }+ expect(written).toContainEqual({+ id: 3,+ error: { code: -32000, message: "Page command rejected" },+ });+ expect(directory).toBe("/srv/artifacts");+ written.length = 0;+ relay.event("Page.downloadWillBegin", { guid: "g1" }, "");+ relay.event("Page.downloadProgress", { guid: "g1", state: "completed" }, "");+ expect(written).toEqual(+ enabled+ ? [+ { method: "Browser.downloadWillBegin", params: { guid: "g1" } },+ { method: "Browser.downloadProgress", params: { guid: "g1", state: "completed" } },+ ]+ : [],+ );+ },+ );});describe("CDP relay payload budget", () => {diff --git a/apps/desktop/src/preview/CdpRelay.ts b/apps/desktop/src/preview/CdpRelay.tsindex d52b0a3b2ab..9a8e4e4c683 100644--- a/apps/desktop/src/preview/CdpRelay.ts+++ b/apps/desktop/src/preview/CdpRelay.ts@@ -98,6 +98,7 @@ export function createCdpRelayConnection(close();};let attached = false;+ let downloadEventsEnabled = false;/** Relay-created page sessions share one real debugger; child frame sessions retain their own ids. */const sessions = new Map<string, "browser" | "page">([[PAGE_SESSION_ID, "page"]]);let sessionSequence = 0;@@ -122,9 +123,15 @@ export function createCdpRelayConnection(case "Browser.setDownloadBehavior": {const directory = command.params?.["downloadPath"];const allowed = command.params?.["behavior"] !== "deny" && typeof directory === "string";+ // Browser-scoped behavior targets Electron's app session; preview paths belong to will-download.+ const result = await target.send(+ "Page.setDownloadBehavior",+ { behavior: command.params?.["behavior"] === "deny" ? "deny" : "default" },+ undefined,+ );target.setDownloadDirectory(allowed ? directory : null);- const { browserContextId: _ignored, ...params } = command.params ?? {};- return target.send("Browser.setDownloadBehavior", params, undefined);+ downloadEventsEnabled = command.params?.["eventsEnabled"] === true;+ return result;}case "Browser.getVersion":return {@@ -232,9 +239,10 @@ export function createCdpRelayConnection(},event: (method, params, sessionId) => {if (!attached) return;+ if (method.startsWith("Page.download")) method = method.replace("Page.", "Browser.");// Download events are the browser's; Playwright listens on its root session.if (method.startsWith("Browser.download")) {- send({ method, params });+ if (downloadEventsEnabled) send({ method, params });return;}// Electron reports the page's own events with an empty session id.diff --git a/apps/desktop/src/preview/DesktopBrowserHost.test.ts b/apps/desktop/src/preview/DesktopBrowserHost.test.tsindex 3168788bebe..2e6e54a5293 100644--- a/apps/desktop/src/preview/DesktopBrowserHost.test.ts+++ b/apps/desktop/src/preview/DesktopBrowserHost.test.ts@@ -917,12 +917,14 @@ describe("DesktopBrowserHost", () => {const host = yield* DesktopBrowserHost.make;const debuggee = makeDebuggee();host.attach(key, debuggee.tab);+ const replies = yield* watchReplies(host);const paths: Array<string> = [];const item = {setSavePath: (path: string) => void paths.push(path),} as unknown as Electron.DownloadItem;expect(host.placeDownload(debuggee.tab.webContents, item)).toBe(false);+ const sent = debuggee.nextSend();yield* host.handleCommandLine(encodeJson({type: "cdp",@@ -934,10 +936,15 @@ describe("DesktopBrowserHost", () => {}),}),);- debuggee.emit("Browser.downloadWillBegin", { guid: "guid-1", suggestedFilename: "r.csv" });+ yield* Effect.promise(() => sent);+ debuggee.release();+ expect(yield* Queue.take(replies)).toBe(1);+ debuggee.emit("Page.downloadWillBegin", { guid: "guid-1", suggestedFilename: "r.csv" });+ expect(host.placeDownload(makeDebuggee().tab.webContents, item)).toBe(false);expect(host.placeDownload(debuggee.tab.webContents, item)).toBe(true);expect(paths).toEqual(["/srv/downloads/guid-1"]);- }),+ expect(host.placeDownload(debuggee.tab.webContents, item)).toBe(false);+ }).pipe(Effect.scoped),);it.effect("tells a download the person clicked from one the agent's input started", () =>diff --git a/apps/desktop/src/preview/DesktopBrowserHost.ts b/apps/desktop/src/preview/DesktopBrowserHost.tsindex 7bf1246f9a4..3ac6c6d73ca 100644--- a/apps/desktop/src/preview/DesktopBrowserHost.ts+++ b/apps/desktop/src/preview/DesktopBrowserHost.ts@@ -438,7 +438,7 @@ export const make = Effect.gen(function* () {focusReleasing: false,screencasts: new Set(),onMessage: (_event, method, params, sessionId) => {- if (method === "Browser.downloadWillBegin") {+ if (method === "Page.downloadWillBegin") {const guid = (params as { guid?: unknown } | undefined)?.guid;tab.pendingDownloadGuid = typeof guid === "string" ? guid : null;}