TypeScript
fix(desktop): agent clicks in the browser no longer pop Save dialogs (#14573)
Theo Browne5cc99e1c2398
diff --git a/apps/desktop/src/preview/Manager.test.ts b/apps/desktop/src/preview/Manager.test.tsindex 304efeafefe..d3f6971b820 100644--- a/apps/desktop/src/preview/Manager.test.ts+++ b/apps/desktop/src/preview/Manager.test.ts@@ -186,6 +186,7 @@ const {fromId,getFocusedWebContents,mkdir,+ previewSession,showItemInFolder,webviewSend,writeFile,@@ -200,6 +201,7 @@ const {fromId: vi.fn<(_id?: number) => Electron.WebContents | null>((_id?: number) => null),getFocusedWebContents: vi.fn(() => null),mkdir: vi.fn((_path: string) => undefined),+ previewSession: { on: vi.fn() },showItemInFolder: vi.fn(),webviewSend: vi.fn(),writeFile: vi.fn((_path: string, _data: Uint8Array) => undefined),@@ -236,7 +238,7 @@ const browserSessionLayer = Layer.succeed(BrowserSession.BrowserSession.of({getPartition: () => Effect.succeed("persist:t3code-preview-test"),isPartition: (partition) => partition.startsWith("persist:t3code-preview-"),- getSession: () => Effect.die("unexpected getSession"),+ getSession: () => Effect.succeed(previewSession as unknown as Electron.Session),clearCookies: () => Effect.void,clearCache: () => Effect.void,}),@@ -547,6 +549,7 @@ describe("PreviewManager", () => {getFocusedWebContents.mockReset();getFocusedWebContents.mockReturnValue(null);mkdir.mockClear();+ previewSession.on.mockClear();writeFile.mockClear();showItemInFolder.mockClear();clipboardItemConstructor.mockClear();@@ -4536,6 +4539,121 @@ describe("PreviewManager", () => {}),),);+ effectIt.effect("saves downloads from agent-driven pages without a Save dialog", () =>+ withManager((manager) =>+ Effect.gen(function* () {+ let humanInput: ((event: unknown, signal?: unknown) => void) | undefined;+ const wc = makeTestPreviewWebContents(vi.fn());+ Object.assign(wc, {+ isDevToolsOpened: () => false,+ loadURL: vi.fn(async () => undefined),+ reload: vi.fn(),+ });+ Object.assign(wc.ipc, {+ on: vi.fn((channel: string, listener: typeof humanInput) => {+ if (channel === "preview:human-input") humanInput = listener;+ }),+ });+ let holdEvaluate = false;+ let releaseEvaluate: (() => void) | undefined;+ Object.assign(wc.debugger, {+ sendCommand: vi.fn(async (method: string, params?: { expression?: string }) => {+ if (method !== "Runtime.evaluate") return undefined;+ if (params?.expression?.includes("matched"))+ return { result: { value: { matched: true } } };+ if (holdEvaluate) {+ holdEvaluate = false;+ await new Promise<void>((resolve) => {+ releaseEvaluate = resolve;+ });+ }+ return { result: { value: 42 } };+ }),+ });+ fromId.mockReturnValue(wc);+ const takeovers = [yield* Deferred.make<void>(), yield* Deferred.make<void>()];+ let takeoverCount = 0;+ let controller = "none";+ yield* manager.subscribeStateChanges((_tabId, state) => {+ const takeover =+ controller !== "human" && state.controller === "human"+ ? takeovers[takeoverCount++]+ : undefined;+ controller = state.controller;+ return takeover ? Deferred.succeed(takeover, undefined).pipe(Effect.asVoid) : Effect.void;+ });+ yield* manager.getBrowserSession();+ yield* manager.getBrowserSession();+ const installs = previewSession.on.mock.calls.filter(+ ([event]) => event === "will-download",+ );+ expect(installs).toHaveLength(1);+ const willDownload = installs[0]![1] as (+ event: unknown,+ item: {+ getFilename: () => string;+ getStartTime: () => number;+ setSavePath: (path: string) => void;+ },+ source: Electron.WebContents,+ ) => void;+ const download = () => {+ const setSavePath = vi.fn();+ willDownload(+ {},+ { getFilename: () => "chart.png", getStartTime: () => 1_790_844_530.5, setSavePath },+ wc,+ );+ return setSavePath;+ };+ yield* manager.createTab("tab_1");+ yield* manager.registerWebview("tab_1", 42);++ expect(download()).not.toHaveBeenCalled();++ yield* manager.automationEvaluate("tab_1", { expression: "42" });+ const startedAt = (1_790_844_530_500).toString(36);+ expect(download()).toHaveBeenCalledWith(+ `/tmp/t3/dev/browser-artifacts/browser-download-${startedAt}-0-chart.png`,+ );+ // Same name, same millisecond: still a separate file.+ expect(download()).toHaveBeenCalledWith(+ `/tmp/t3/dev/browser-artifacts/browser-download-${startedAt}-1-chart.png`,+ );++ humanInput?.({}, { kind: "pointer", x: 10, y: 10, button: 0 });+ yield* Deferred.await(takeovers[0]!);+ expect(download()).not.toHaveBeenCalled();++ // An action still waiting for the page when the human takes over must+ // not mark it as agent-driven again.+ holdEvaluate = true;+ const running = yield* manager+ .automationEvaluate("tab_1", { expression: "42" })+ .pipe(Effect.forkChild({ startImmediately: true }));+ yield* settle(() => releaseEvaluate !== undefined);+ const queued = yield* manager+ .automationEvaluate("tab_1", { expression: "42" })+ .pipe(Effect.forkChild({ startImmediately: true }));+ humanInput?.({}, { kind: "pointer", x: 20, y: 20, button: 0 });+ yield* Deferred.await(takeovers[1]!);+ releaseEvaluate?.();+ yield* Fiber.await(running);+ expect(Exit.isFailure(yield* Fiber.await(queued))).toBe(true);+ expect(download()).not.toHaveBeenCalled();++ // URL-bar navigation hands the page back to the human.+ yield* manager.automationEvaluate("tab_1", { expression: "42" });+ expect(download()).toHaveBeenCalled();+ yield* manager.navigate("tab_1", "https://example.com/report.csv");+ expect(download()).not.toHaveBeenCalled();++ // Reading the page does not make it agent-driven.+ yield* manager.automationWaitFor("tab_1", { text: "Example" });+ expect(download()).not.toHaveBeenCalled();+ }),+ ),+ );});describe("PreviewOperationError", () => {diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.tsindex b97af6f0520..cc1a8f524dc 100644--- a/apps/desktop/src/preview/Manager.ts+++ b/apps/desktop/src/preview/Manager.ts@@ -520,6 +520,9 @@ interface ExpectedAgentInput {*/const POPUP_PROTOCOLS = new Set(["http:", "https:"]);+/** Control actions that only read the page, so they do not make it agent-driven. */+const READ_ONLY_CONTROL_ACTIONS = new Set(["snapshot", "waitFor"]);+const isPopupUrl = (rawUrl: string): boolean => {try {return POPUP_PROTOCOLS.has(new URL(rawUrl).protocol);@@ -685,6 +688,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function// (electron#44618) and now always rejects with NotAllowedError.let pendingRecording: PendingRecording | null = null;const displayMediaHandlerSessions = new WeakSet<Session>();+ const downloadHandlerSessions = new WeakSet<Session>();+ let downloadCount = 0;+ // Preview pages whose latest input came from an agent action, not the human.+ const agentDrivenWebContents = new WeakSet<Electron.WebContents>();let frameCaptureWindowOpen = true;let currentMainWindow: BrowserWindow | undefined;let mainWindowCleanupFiber: Fiber.Fiber<void, never> | undefined;@@ -1487,7 +1494,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(functionconst epoch = (yield* Ref.get(controlEpochRef)).get(tabId) ?? 0;const control = yield* ensureControlSession(wc);const execute = Effect.fn("PreviewManager.executeControlAction")(function* () {- yield* update(tabId, { controller: "agent" });const checkControl = Effect.gen(function* () {const currentEpoch = (yield* Ref.get(controlEpochRef)).get(tabId) ?? 0;if (currentEpoch !== epoch) {@@ -1498,6 +1504,11 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function});}});+ // A human who took over while this action waited for the permit owns+ // the page; marking it agent-driven would hide their Save dialog.+ yield* checkControl;+ if (!READ_ONLY_CONTROL_ACTIONS.has(action)) agentDrivenWebContents.add(wc);+ yield* update(tabId, { controller: "agent" });const send: SendCommand = Effect.fn("PreviewManager.sendCommand")(function* (method, commandParams, sessionId) {yield* checkControl;@@ -1922,6 +1933,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(functionif (isPreviewInputSignal(rawSignal) && (yield* consumeExpectedAgentInput(tabId, rawSignal))) {return;}+ agentDrivenWebContents.delete(wc);yield* Ref.update(controlEpochRef, (epochs) =>replaceMap(epochs, (copy) => {copy.set(tabId, (epochs.get(tabId) ?? 0) + 1);@@ -2476,6 +2488,9 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function);return;}+ // URL-bar navigation hands the page back to the human. The agent's own+ // navigation shares this path; its next action marks the page again.+ agentDrivenWebContents.delete(wc);if (wc.getURL() === url) {yield* attempt({ operation: "navigate.reload", tabId, webContentsId: wc.id }, () =>wc.reload(),@@ -3500,6 +3515,24 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function});};+ // Installed once per session. Electron opens a native Save dialog for a+ // download with no save path, so every export an agent clicked while testing+ // a page put a modal over the whole app. Downloads from a page the agent drove+ // last go to the artifact directory instead. Downloads the human starts keep+ // the Save dialog.+ const installDownloadHandler = (session: Session) => {+ if (downloadHandlerSessions.has(session)) return;+ downloadHandlerSessions.add(session);+ session.on("will-download", (_event, item, source) => {+ if (!agentDrivenWebContents.has(source)) return;+ // The start time keeps names unique across restarts; the count keeps two+ // same-name downloads in one millisecond from overwriting each other.+ const id = `${Math.round(item.getStartTime() * 1000).toString(36)}-${(downloadCount++).toString(36)}`;+ const fileName = `browser-download-${id}-${path.basename(item.getFilename())}`;+ item.setSavePath(path.join(resolvedArtifactDirectory, fileName));+ });+ };+const startRecording = Effect.fn("PreviewManager.startRecording")(function* (tabId: string,options: RecordingInputOptions = DEFAULT_RECORDING_INPUT_OPTIONS,@@ -4624,6 +4657,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(functiongoBack,goForward,hardReload,+ installDownloadHandler,navigate,openPictureInPicture,openDevTools,@@ -5075,13 +5109,15 @@ export const make = Effect.gen(function* PreviewManagerMake() {setMainWindow: operations.setMainWindow,getBrowserSession: Effect.fn("PreviewManager.getBrowserSession")(function* (scope, persistent, namespace) {- return yield* browserSession+ const session = yield* browserSession.getSession(scope, persistent, namespace).pipe(Effect.mapError((cause) => new PreviewOperationError({ operation: "getBrowserSession", cause }),),);+ operations.installDownloadHandler(session);+ return session;},),isBrowserPartition: browserSession.isPartition,