Skip to content

armgit / orca

Public Imported from GitHub
0

Orca is the place for working with a fleet of agents (e.g. Grok Bot, Claude Code). Run any coding agent with your own subscription. Available on desktop, mobile and remote runtime.

fix(browser): save agent downloads to the requested --path and fail fast when none starts (#36240)

Kelvin Amoaba0c99ccb3da8f
diff --git a/src/cli/handlers/browser-interact.ts b/src/cli/handlers/browser-interact.ts
index 7331b59d14c..adef71f14ad 100644
--- a/src/cli/handlers/browser-interact.ts
+++ b/src/cli/handlers/browser-interact.ts
@@ -13,6 +13,7 @@ import type {
BrowserUploadResult
} from '../../shared/runtime-types'
import type { CommandHandler } from '../dispatch'
+import { resolveRepoPathArgument } from '../repo-path-arguments'
import { printResult } from '../format'
import {
getOptionalNumberFlag,
@@ -211,7 +212,12 @@ export const BROWSER_INTERACT_HANDLERS: Record<string, CommandHandler> = {
},
download: async ({ flags, client, cwd, json }) => {
const selector = getRequiredStringFlag(flags, 'selector')
- const path = getRequiredStringFlag(flags, 'path')
+ const path = resolveRepoPathArgument(
+ getRequiredStringFlag(flags, 'path'),
+ cwd,
+ client.isRemote,
+ 'Remote browser download'
+ )
const target = await getBrowserCommandTarget(flags, cwd, client)
const result = await client.call<unknown>('browser.download', { selector, path, ...target })
printResult(result, json, () => `Downloaded to ${path}`)
diff --git a/src/main/browser/agent-browser-bridge-types.ts b/src/main/browser/agent-browser-bridge-types.ts
index 49579c1d76a..0c77be5831d 100644
--- a/src/main/browser/agent-browser-bridge-types.ts
+++ b/src/main/browser/agent-browser-bridge-types.ts
@@ -11,6 +11,9 @@ export const AGENT_BROWSER_EXIT_DRAIN_MS = 500
export const AGENT_BROWSER_CLEANUP_TIMEOUT_MS = 5_000
export const AGENT_BROWSER_CLEANUP_CONCURRENCY = 4
export const EMBEDDED_NAVIGATION_TIMEOUT_MS = 30_000
+export const AGENT_DOWNLOAD_START_TIMEOUT_MS = 10_000
+// Counted from the request, so the reply beats the CLI's 60s timeout; the download keeps going after.
+export const AGENT_DOWNLOAD_REPLY_DEADLINE_MS = 50_000
export const AGENT_BROWSER_TEXT_ARGUMENT_MAX_BYTES = 8 * 1024
export const AGENT_BROWSER_CLIPBOARD_WRITE_MAX_BYTES = AGENT_BROWSER_TEXT_ARGUMENT_MAX_BYTES
diff --git a/src/main/browser/agent-browser-bridge-utility-commands.ts b/src/main/browser/agent-browser-bridge-utility-commands.ts
index d4e12b1d66d..e36dd0c76d1 100644
--- a/src/main/browser/agent-browser-bridge-utility-commands.ts
+++ b/src/main/browser/agent-browser-bridge-utility-commands.ts
@@ -1,6 +1,13 @@
+import { mkdir } from 'node:fs/promises'
+import path from 'node:path'
import { BrowserError } from './cdp-bridge'
import { assertClipboardTextWriteWithinLimitWithYield } from '../../shared/clipboard-text'
-import { AGENT_BROWSER_CLIPBOARD_WRITE_MAX_BYTES } from './agent-browser-bridge-types'
+import { withTimeout } from '../../shared/promise-timeout-fallback'
+import {
+ AGENT_BROWSER_CLIPBOARD_WRITE_MAX_BYTES,
+ AGENT_DOWNLOAD_REPLY_DEADLINE_MS,
+ AGENT_DOWNLOAD_START_TIMEOUT_MS
+} from './agent-browser-bridge-types'
import type { BrowserBackResult, BrowserReloadResult } from '../../shared/runtime-types'
import { AgentBrowserBridgeMouseCommands } from './agent-browser-bridge-mouse-commands'
@@ -94,14 +101,50 @@ export abstract class AgentBrowserBridgeUtilityCommands extends AgentBrowserBrid
})
}
+ // Orca's will-download handler picks every save path, so agent-browser's own download
+ // (CDP download behavior + rename) never sees the file; claim the download here instead.
async download(
selector: string,
- path: string,
+ savePath: string,
worktreeId?: string,
browserPageId?: string
- ): Promise<unknown> {
- return this.enqueueTargetedCommand(worktreeId, browserPageId, async (sessionName) => {
- return await this.execAgentBrowser(sessionName, ['download', selector, path])
+ ): Promise<{ path: string }> {
+ if (!path.isAbsolute(savePath)) {
+ throw new BrowserError('invalid_argument', `--path must be an absolute path: ${savePath}`)
+ }
+ const replyDeadline = Date.now() + AGENT_DOWNLOAD_REPLY_DEADLINE_MS
+ return this.enqueueTargetedCommand(worktreeId, browserPageId, async (sessionName, target) => {
+ await mkdir(path.dirname(savePath), { recursive: true })
+ const claim = this.browserManager.claimNextDownload(target.webContentsId, savePath)
+ try {
+ await this.execAgentBrowser(sessionName, ['click', selector])
+ if (!(await withTimeout(claim.started, AGENT_DOWNLOAD_START_TIMEOUT_MS, false))) {
+ throw new BrowserError(
+ 'browser_download_not_started',
+ `Clicking ${selector} did not start a download within ${AGENT_DOWNLOAD_START_TIMEOUT_MS / 1000}s.`
+ )
+ }
+ const finished = await withTimeout(
+ claim.finished,
+ Math.max(0, replyDeadline - Date.now()),
+ null
+ )
+ if (!finished) {
+ throw new BrowserError(
+ 'browser_download_in_progress',
+ `The download is still in progress and will be saved to ${savePath}.`
+ )
+ }
+ if (finished.status !== 'completed') {
+ throw new BrowserError(
+ 'browser_download_failed',
+ finished.error ?? `The download was ${finished.status}.`
+ )
+ }
+ return { path: savePath }
+ } finally {
+ claim.release()
+ }
})
}
diff --git a/src/main/browser/browser-manager-download-creation.ts b/src/main/browser/browser-manager-download-creation.ts
index 7170118e087..ca0496b6836 100644
--- a/src/main/browser/browser-manager-download-creation.ts
+++ b/src/main/browser/browser-manager-download-creation.ts
@@ -10,10 +10,24 @@ import {
import type { BrowserDownloadFinishedEvent } from '../../shared/browser-guest-events'
import { BrowserManagerQueries } from './browser-manager-queries'
+export type BrowserDownloadClaim = {
+ started: Promise<boolean>
+ finished: Promise<BrowserDownloadFinishedEvent>
+ release: () => void
+}
+
+type PendingDownloadClaim = {
+ savePath: string
+ start: (started: boolean) => void
+ finish: (event: BrowserDownloadFinishedEvent) => void
+}
+
export abstract class BrowserManagerDownloadCreation extends BrowserManagerQueries {
private unownedDownloadOwnerResolver: ((webContentsId: number) => string | null) | null = null
private readonly requestedFilenames = new WeakMap<Electron.DownloadItem, string>()
private readonly requestedSavePaths = new WeakMap<Electron.DownloadItem, string>()
+ private readonly extensionDownloads = new WeakSet<Electron.DownloadItem>()
+ private readonly downloadClaimsByGuestId = new Map<number, PendingDownloadClaim>()
/**
* Extension pages and workers are never registered as tabs, so their downloads would wait
@@ -23,6 +37,11 @@ export abstract class BrowserManagerDownloadCreation extends BrowserManagerQueri
this.unownedDownloadOwnerResolver = resolver
}
+ /** chrome.downloads items are the extension's, so an agent `download` claim never takes them. */
+ markExtensionDownload(item: Electron.DownloadItem): void {
+ this.extensionDownloads.add(item)
+ }
+
/** chrome.downloads `filename`: names the item before its destination is reserved. */
requestDownloadFilename(item: Electron.DownloadItem, filename: string): void {
this.requestedFilenames.set(item, filename)
@@ -33,6 +52,27 @@ export abstract class BrowserManagerDownloadCreation extends BrowserManagerQueri
this.requestedSavePaths.set(item, savePath)
}
+ /** Agent `download`: saves the next download this page (or its popups) starts to `savePath`. */
+ claimNextDownload(guestWebContentsId: number, savePath: string): BrowserDownloadClaim {
+ const started = Promise.withResolvers<boolean>()
+ const finished = Promise.withResolvers<BrowserDownloadFinishedEvent>()
+ const claim: PendingDownloadClaim = {
+ savePath,
+ start: started.resolve,
+ finish: finished.resolve
+ }
+ this.downloadClaimsByGuestId.set(guestWebContentsId, claim)
+ return {
+ started: started.promise,
+ finished: finished.promise,
+ release: () => {
+ if (this.downloadClaimsByGuestId.get(guestWebContentsId) === claim) {
+ this.downloadClaimsByGuestId.delete(guestWebContentsId)
+ }
+ }
+ }
+ }
+
handleGuestWillDownload(args: { guestWebContentsId: number; item: Electron.DownloadItem }): void {
const { guestWebContentsId, item } = args
const downloadId = randomUUID()
@@ -72,13 +112,21 @@ export abstract class BrowserManagerDownloadCreation extends BrowserManagerQueri
const adoptedTabId = ownerContext
? null
: (this.unownedDownloadOwnerResolver?.(guestWebContentsId) ?? null)
- const decision = routeBrowserClientDownload({
- guestWebContentsId:
- ownerContext?.rootGuestWebContentsId ??
- (adoptedTabId ? this.getGuestWebContentsId(adoptedTabId) : null) ??
- guestWebContentsId
- })
+ const ownerGuestWebContentsId =
+ ownerContext?.rootGuestWebContentsId ??
+ (adoptedTabId ? this.getGuestWebContentsId(adoptedTabId) : null) ??
+ guestWebContentsId
+ const decision = routeBrowserClientDownload({ guestWebContentsId: ownerGuestWebContentsId })
const clientRoute = decision.kind === 'remote' ? decision.route : null
+ // Extension pages and chrome.downloads start their own downloads, never the agent's click.
+ const isExtensionDownload = adoptedTabId !== null || this.extensionDownloads.has(item)
+ const claim =
+ decision.kind === 'local' && !isExtensionDownload
+ ? this.downloadClaimsByGuestId.get(ownerGuestWebContentsId)
+ : null
+ if (claim) {
+ this.downloadClaimsByGuestId.delete(ownerGuestWebContentsId)
+ }
const destination = (() => {
if (clientRoute) {
return {
@@ -91,7 +139,7 @@ export abstract class BrowserManagerDownloadCreation extends BrowserManagerQueri
if (decision.kind === 'blocked') {
return null
}
- const chosenPath = this.requestedSavePaths.get(item)
+ const chosenPath = claim?.savePath ?? this.requestedSavePaths.get(item)
if (chosenPath) {
return { filename: path.basename(chosenPath), savePath: chosenPath, reservationKey: null }
}
@@ -123,9 +171,11 @@ export abstract class BrowserManagerDownloadCreation extends BrowserManagerQueri
transientState: null,
terminalEvent: null,
startedSent: false,
- cleanup: null
+ cleanup: null,
+ onFinished: claim?.finish ?? null
}
this.downloadsById.set(downloadId, download)
+ claim?.start(true)
const browserTabId = ownerContext?.browserTabId ?? adoptedTabId
if (browserTabId) {
diff --git a/src/main/browser/browser-manager-download-lifecycle.ts b/src/main/browser/browser-manager-download-lifecycle.ts
index abcf611e0e0..5f841f4f19e 100644
--- a/src/main/browser/browser-manager-download-lifecycle.ts
+++ b/src/main/browser/browser-manager-download-lifecycle.ts
@@ -215,6 +215,7 @@ export abstract class BrowserManagerDownloadLifecycle extends BrowserManagerDown
error
}
download.terminalEvent = event
+ download.onFinished?.(event)
if (download.browserTabId) {
this.sendDownloadStarted(downloadId)
this.sendDownloadFinished(download.browserTabId, event)
diff --git a/src/main/browser/browser-manager-downloads.test.ts b/src/main/browser/browser-manager-downloads.test.ts
index a0c60192b2b..e780548b327 100644
--- a/src/main/browser/browser-manager-downloads.test.ts
+++ b/src/main/browser/browser-manager-downloads.test.ts
@@ -242,6 +242,43 @@ describe('browserManager', () => {
expect(item.setSavePath).toHaveBeenCalledWith(chosen)
})
+ it("saves the page's next download where an agent asked and reports when it finishes", async () => {
+ webContentsFromIdMock.mockReturnValue(null)
+ const agentPath = join('/work', 'out', 'report.csv')
+ const claim = browserManager.claimNextDownload(414, agentPath)
+
+ const claimed = createDownloadItem()
+ browserManager.handleGuestWillDownload({ guestWebContentsId: 414, item: claimed })
+ await expect(claim.started).resolves.toBe(true)
+ expect(claimed.setSavePath).toHaveBeenCalledWith(agentPath)
+
+ const doneEvent = { preventDefault: () => {}, defaultPrevented: false }
+ getDownloadItemEventHandler(claimed, 'once', 'done')?.(doneEvent, 'completed')
+ await expect(claim.finished).resolves.toMatchObject({
+ status: 'completed',
+ savePath: agentPath
+ })
+
+ const next = createDownloadItem()
+ browserManager.handleGuestWillDownload({ guestWebContentsId: 414, item: next })
+ expect(next.setSavePath).toHaveBeenCalledWith(join('/downloads', 'report.csv'))
+ claim.release()
+ })
+
+ it("leaves an extension's save-dialog download where the user chose during an agent claim", () => {
+ webContentsFromIdMock.mockReturnValue(null)
+ const claim = browserManager.claimNextDownload(415, join('/work', 'out', 'report.csv'))
+ const item = createDownloadItem()
+ const chosen = join('/elsewhere', 'backup.json')
+
+ browserManager.markExtensionDownload(item)
+ browserManager.requestDownloadSavePath(item, chosen)
+ browserManager.handleGuestWillDownload({ guestWebContentsId: 415, item })
+
+ expect(item.setSavePath).toHaveBeenCalledWith(chosen)
+ claim.release()
+ })
+
it('flushes started and terminal snapshots for downloads that finish before registration', () => {
const rendererSendMock = vi.fn()
const guest = {
diff --git a/src/main/browser/browser-manager-types.ts b/src/main/browser/browser-manager-types.ts
index 76268eec29d..2eb440c686c 100644
--- a/src/main/browser/browser-manager-types.ts
+++ b/src/main/browser/browser-manager-types.ts
@@ -119,6 +119,7 @@ export type ActiveDownload = {
terminalEvent: BrowserDownloadFinishedEvent | null
startedSent: boolean
cleanup: (() => void) | null
+ onFinished: ((event: BrowserDownloadFinishedEvent) => void) | null
}
export function safeOrigin(rawUrl: string): string {
diff --git a/src/main/browser/extensions/api/downloads.test.ts b/src/main/browser/extensions/api/downloads.test.ts
index ae922d6da8d..cd55b65d49d 100644
--- a/src/main/browser/extensions/api/downloads.test.ts
+++ b/src/main/browser/extensions/api/downloads.test.ts
@@ -8,6 +8,7 @@ const mocks = vi.hoisted(() => {
emitted,
requestDownloadFilename: vi.fn(),
requestDownloadSavePath: vi.fn(),
+ markExtensionDownload: vi.fn(),
chooseSavePath: vi.fn(async (): Promise<string | null> => null)
}
})
@@ -18,7 +19,8 @@ vi.mock('../../browser-manager', () => ({
browserManager: {
getTabIdForWebContentsId: () => 'tab-1',
requestDownloadFilename: mocks.requestDownloadFilename,
- requestDownloadSavePath: mocks.requestDownloadSavePath
+ requestDownloadSavePath: mocks.requestDownloadSavePath,
+ markExtensionDownload: mocks.markExtensionDownload
}
}))
vi.mock('../browser-extension-api-host', () => ({
diff --git a/src/main/browser/extensions/api/downloads.ts b/src/main/browser/extensions/api/downloads.ts
index ffd99491966..803a6ad1bc1 100644
--- a/src/main/browser/extensions/api/downloads.ts
+++ b/src/main/browser/extensions/api/downloads.ts
@@ -178,6 +178,7 @@ function startDownload(
}
clearTimeout(timer)
caller.session.off('will-download', onWillDownload)
+ browserManager.markExtensionDownload(item)
if (place.savePath !== undefined) {
browserManager.requestDownloadSavePath(item, place.savePath)
} else if (place.filename !== undefined) {