Skip to content

A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.

Limit Bot downloads to its workspace and working folder

Fei24111a4414368f22
diff --git a/app/src/bot-views.mjs b/app/src/bot-views.mjs
index 75d85c0c..4d2d311a 100644
--- a/app/src/bot-views.mjs
+++ b/app/src/bot-views.mjs
@@ -1,12 +1,14 @@
import { randomBytes, randomUUID } from 'node:crypto'
-import { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'
+import { mkdirSync, readFileSync, realpathSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'
import { rm } from 'node:fs/promises'
import { createServer } from 'node:http'
-import { dirname, join } from 'node:path'
+import { tmpdir } from 'node:os'
+import { basename, dirname, isAbsolute, join, relative as relativePath, resolve, sep } from 'node:path'
import { WebSocketServer } from 'ws'
import { allowedNavigation, requestAllowed } from './bot-browser.mjs'
const LOOPBACK = new Set(['127.0.0.1', '::1', '::ffff:127.0.0.1'])
+const PLAYWRIGHT_ARTIFACT_PREFIX = 'playwright-artifacts-'
const rectOf = rect => ({
x: Math.max(0, Math.round(rect?.left ?? 0)),
y: Math.max(0, Math.round(rect?.top ?? 0)),
@@ -16,6 +18,16 @@ const rectOf = rect => ({
const BOT_ID = /^session-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu
export const isBotId = value => typeof value === 'string' && BOT_ID.test(value)
+function containsPath(root, target) {
+ const relative = relativePath(resolve(root), resolve(target))
+ return relative === '' || (relative !== '..' && !relative.startsWith(`..${sep}`) && !isAbsolute(relative))
+}
+
+function isDirectChild(root, target) {
+ const relative = relativePath(resolve(root), resolve(target))
+ return relative !== '' && relative !== '..' && !relative.startsWith(`..${sep}`) && !relative.includes(sep) && !isAbsolute(relative)
+}
+
export class BotViews {
#window
#WebContentsView
@@ -30,6 +42,7 @@ export class BotViews {
#address
#onChange
#downloadPaths = new Map()
+ #downloadRoots = new Map()
#statePath
#saved = {}
#active = new Map()
@@ -189,6 +202,33 @@ export class BotViews {
}
}
+ #allowedDownloadPath(botId, requested) {
+ if (typeof requested !== 'string' || !isAbsolute(requested)) return undefined
+ const target = resolve(requested)
+ const roots = (this.#downloadRoots.get(botId) ?? []).filter(root => containsPath(root, target))
+ const temporaryRoot = resolve(tmpdir())
+ let temporaryRealRoot
+ try {
+ temporaryRealRoot = realpathSync(temporaryRoot)
+ } catch {}
+ const isArtifact = temporaryRealRoot !== undefined && [temporaryRoot, temporaryRealRoot].some(root =>
+ isDirectChild(root, target) && basename(target).startsWith(PLAYWRIGHT_ARTIFACT_PREFIX))
+ if (roots.length === 0 && !isArtifact) return undefined
+ try {
+ mkdirSync(target, { recursive: true })
+ const realTarget = realpathSync(target)
+ const inRoot = roots.some(root => {
+ try { return containsPath(realpathSync(root), realTarget) } catch { return false }
+ })
+ const inArtifacts = isArtifact && temporaryRealRoot !== undefined
+ && isDirectChild(temporaryRealRoot, realTarget)
+ && basename(realTarget).startsWith(PLAYWRIGHT_ARTIFACT_PREFIX)
+ return inRoot || inArtifacts ? target : undefined
+ } catch {
+ return undefined
+ }
+ }
+
place(tabId, rect, visible = rect !== null) {
const entry = this.#views.get(tabId)
if (!entry) return false
@@ -241,13 +281,22 @@ export class BotViews {
for (const entry of [...this.#views.values()]) if (entry.botId === botId) await this.close(botId, entry.tabId)
for (const [token, id] of this.#tokens) if (id === botId) this.#tokens.delete(token)
this.#downloadPaths.delete(botId)
+ this.#downloadRoots.delete(botId)
this.#held.delete(botId)
delete this.#saved[botId]
this.#persist()
}
- async endpoint(botId) {
+ async endpoint(botId, { downloadRoots } = {}) {
if (this.#held.has(botId)) throw new Error('The user has taken over this browser.')
+ if (downloadRoots !== undefined) {
+ if (!Array.isArray(downloadRoots) || downloadRoots.length > 4 || !Array.from(downloadRoots).every(root => typeof root === 'string' && isAbsolute(root))) {
+ throw new Error('Invalid browser download roots.')
+ }
+ this.#downloadRoots.set(botId, [...new Set(downloadRoots.map(root => resolve(root)))])
+ this.#downloadPaths.delete(botId)
+ for (const entry of this.#views.values()) if (entry.botId === botId) entry.downloadPath = undefined
+ }
if (!this.#address) await new Promise(resolve => this.#server.once('listening', resolve))
if (this.sync(botId).length === 0) {
const saved = this.#saved[botId]
@@ -436,8 +485,9 @@ export class BotViews {
try {
if (method === 'Browser.getVersion') { reply({ protocolVersion: '1.3', product: `Chrome/${process.versions.chrome}`, userAgent: `Electron/${process.versions.electron} Chrome/${process.versions.chrome}`, jsVersion: process.versions.v8 }); return }
if (method === 'Browser.setDownloadBehavior') {
- this.#downloadPaths.set(botId, params.downloadPath)
- for (const entry of targets()) entry.downloadPath = params.downloadPath
+ const downloadPath = params.behavior === 'allow' ? this.#allowedDownloadPath(botId, params.downloadPath) : undefined
+ this.#downloadPaths.set(botId, downloadPath)
+ for (const entry of targets()) entry.downloadPath = downloadPath
reply({}); return
}
if (method === 'Browser.cancelDownload') {
diff --git a/app/src/main.mjs b/app/src/main.mjs
index fc5f4bda..6691ade5 100644
--- a/app/src/main.mjs
+++ b/app/src/main.mjs
@@ -159,7 +159,12 @@ async function start() {
host = newHost()
host.onMessage(message => {
if (message?.type !== 'ds-bot:browser-endpoint' || typeof message.id !== 'string' || !isBotId(message.botId)) return
- void botViews.endpoint(message.botId).then(url => {
+ const downloadRoots = message.downloadRoots
+ if (!Array.isArray(downloadRoots) || downloadRoots.length > 4 || !Array.from(downloadRoots).every(root => typeof root === 'string' && isAbsolute(root))) {
+ host?.send({ type: 'ds-bot:browser-endpoint-response', id: message.id, error: 'Could not create the browser endpoint.' })
+ return
+ }
+ void botViews.endpoint(message.botId, { downloadRoots }).then(url => {
host?.send({ type: 'ds-bot:browser-endpoint-response', id: message.id, url })
}).catch(() => host?.send({ type: 'ds-bot:browser-endpoint-response', id: message.id, error: 'Could not create the browser endpoint.' }))
})
diff --git a/app/test/bot-views.test.mjs b/app/test/bot-views.test.mjs
index 2e81bf45..68e633f3 100644
--- a/app/test/bot-views.test.mjs
+++ b/app/test/bot-views.test.mjs
@@ -1,6 +1,6 @@
import assert from 'node:assert/strict'
import { EventEmitter } from 'node:events'
-import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { existsSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { test } from 'node:test'
@@ -60,6 +60,15 @@ test('Bot endpoint identifiers follow DSH session.create IDs', () => {
assert.equal(isBotId('session-1'), false)
})
+test('Bot endpoints accept only up to four absolute download roots', async t => {
+ const { manager } = fixture()
+ t.after(() => manager.dispose())
+ await assert.rejects(() => manager.endpoint('a', { downloadRoots: ['relative'] }), /Invalid browser download roots/u)
+ await assert.rejects(() => manager.endpoint('a', { downloadRoots: new Array(1) }), /Invalid browser download roots/u)
+ await assert.rejects(() => manager.endpoint('a', { downloadRoots: ['/a', '/b', '/c', '/d', '/e'] }), /Invalid browser download roots/u)
+ assert.match(await manager.endpoint('a', { downloadRoots: ['/a', '/b', '/c', '/d'] }), /^ws:\/\//u)
+})
+
function openSocket(url, options) {
return new Promise((resolve, reject) => {
const socket = new WebSocket(url, options)
@@ -152,10 +161,11 @@ test('CDP relay rejects invalid paths and Origin headers', async t => {
test('CDP download behavior saves to the Bot path and emits download events', async t => {
const { manager, handlers, views } = fixture()
t.after(() => manager.dispose())
- const downloadPath = mkdtempSync(join(tmpdir(), 'bot-views-download-'))
- t.after(() => rmSync(downloadPath, { recursive: true, force: true }))
+ const rootPath = mkdtempSync(join(tmpdir(), 'bot-views-download-root-'))
+ const downloadPath = join(rootPath, 'downloads')
+ t.after(() => rmSync(rootPath, { recursive: true, force: true }))
const entry = manager.create('a')
- const socket = await openSocket(await manager.endpoint('a'))
+ const socket = await openSocket(await manager.endpoint('a', { downloadRoots: [rootPath] }))
t.after(() => socket.close())
const discovered = await request(socket, 1, 'Target.attachToTarget', { targetId: entry.tabId, flatten: true })
assert.ok(discovered.result.sessionId)
@@ -191,10 +201,50 @@ test('CDP download behavior saves to the Bot path and emits download events', as
assert.equal(sessionId.length > 0, true)
})
+test('download roots are isolated per Bot', async t => {
+ const { manager, handlers, views } = fixture()
+ t.after(() => manager.dispose())
+ const rootA = mkdtempSync(join(tmpdir(), 'bot-views-download-a-'))
+ const rootB = mkdtempSync(join(tmpdir(), 'bot-views-download-b-'))
+ t.after(() => {
+ rmSync(rootA, { recursive: true, force: true })
+ rmSync(rootB, { recursive: true, force: true })
+ })
+ const entryA = manager.create('a')
+ const entryB = manager.create('b')
+ const [endpointA, endpointB] = await Promise.all([
+ manager.endpoint('a', { downloadRoots: [rootA] }),
+ manager.endpoint('b', { downloadRoots: [rootB] }),
+ ])
+ const socketA = await openSocket(endpointA)
+ const socketB = await openSocket(endpointB)
+ t.after(() => { socketA.close(); socketB.close() })
+ await request(socketA, 1, 'Target.attachToTarget', { targetId: entryA.tabId, flatten: true })
+ await request(socketB, 2, 'Target.attachToTarget', { targetId: entryB.tabId, flatten: true })
+ await request(socketA, 3, 'Browser.setDownloadBehavior', { behavior: 'allow', downloadPath: rootA })
+ await request(socketB, 4, 'Browser.setDownloadBehavior', { behavior: 'allow', downloadPath: rootA })
+ let savedByA
+ const accepted = Object.assign(new EventEmitter(), {
+ setSavePath(path) { savedByA = path },
+ getURL() { return 'https://example.com/file' },
+ getFilename() { return 'report.pdf' },
+ })
+ handlers.get('bot:a')({ preventDefault() { throw new Error('Bot A download was refused') } }, accepted, views[0].webContents)
+ assert.match(savedByA, new RegExp(`^${rootA.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}[/\\\\]`, 'u'))
+ let preventedForB = false
+ const refused = Object.assign(new EventEmitter(), {
+ setSavePath() { throw new Error('Bot B must not use Bot A download root') },
+ getURL() { return 'https://example.com/file' },
+ getFilename() { return 'report.pdf' },
+ })
+ handlers.get('bot:b')({ preventDefault() { preventedForB = true } }, refused, views[1].webContents)
+ assert.equal(preventedForB, true)
+})
+
test('cancelling a relay download removes its save path', async t => {
const { manager, handlers, views } = fixture()
t.after(() => manager.dispose())
- const downloadPath = mkdtempSync(join(tmpdir(), 'bot-views-cancel-'))
+ const downloadPath = mkdtempSync(join(tmpdir(), 'playwright-artifacts-bot-views-cancel-'))
t.after(() => rmSync(downloadPath, { recursive: true, force: true }))
const entry = manager.create('a')
const socket = await openSocket(await manager.endpoint('a'))
@@ -223,6 +273,76 @@ test('cancelling a relay download removes its save path', async t => {
assert.equal(existsSync(savePath), false)
})
+test('CDP rejects outside, traversal, and symlink download paths and cancels downloads', async t => {
+ const { manager, handlers, views } = fixture()
+ t.after(() => manager.dispose())
+ const rootPath = mkdtempSync(join(tmpdir(), 'bot-views-download-root-'))
+ const outsidePath = mkdtempSync(join(tmpdir(), 'bot-views-download-outside-'))
+ symlinkSync(outsidePath, join(rootPath, 'outside-link'))
+ t.after(() => {
+ rmSync(rootPath, { recursive: true, force: true })
+ rmSync(outsidePath, { recursive: true, force: true })
+ })
+ const entry = manager.create('a')
+ const socket = await openSocket(await manager.endpoint('a', { downloadRoots: [rootPath] }))
+ t.after(() => socket.close())
+ await request(socket, 1, 'Target.attachToTarget', { targetId: entry.tabId, flatten: true })
+ const refusedPaths = [
+ '/etc/x',
+ join(rootPath, '..', 'bot-views-download-escape'),
+ join(rootPath, 'outside-link'),
+ ]
+ let id = 2
+ for (const downloadPath of refusedPaths) {
+ await request(socket, id++, 'Browser.setDownloadBehavior', { behavior: 'allow', downloadPath: rootPath })
+ const response = await request(socket, id++, 'Browser.setDownloadBehavior', { behavior: 'allow', downloadPath })
+ assert.deepEqual(response.result, {})
+ let prevented = false
+ let savePath
+ const item = Object.assign(new EventEmitter(), {
+ setSavePath(path) { savePath = path },
+ getURL() { return 'https://example.com/file' },
+ getFilename() { return 'report.pdf' },
+ })
+ handlers.get('bot:a')({ preventDefault() { prevented = true } }, item, views[0].webContents)
+ assert.equal(prevented, true)
+ assert.equal(savePath, undefined)
+ }
+ await request(socket, id++, 'Browser.setDownloadBehavior', { behavior: 'allow', downloadPath: rootPath })
+ await request(socket, id, 'Browser.setDownloadBehavior', { behavior: 'deny', downloadPath: rootPath })
+ let denied = false
+ const item = Object.assign(new EventEmitter(), {
+ setSavePath() { throw new Error('denied downloads must not get a save path') },
+ getURL() { return 'https://example.com/file' },
+ getFilename() { return 'report.pdf' },
+ })
+ handlers.get('bot:a')({ preventDefault() { denied = true } }, item, views[0].webContents)
+ assert.equal(denied, true)
+})
+
+test('CDP accepts a direct Playwright artifacts directory under os.tmpdir()', async t => {
+ const { manager, handlers, views } = fixture()
+ t.after(() => manager.dispose())
+ const downloadPath = mkdtempSync(join(tmpdir(), 'playwright-artifacts-bot-views-'))
+ t.after(() => rmSync(downloadPath, { recursive: true, force: true }))
+ const entry = manager.create('a')
+ const socket = await openSocket(await manager.endpoint('a'))
+ t.after(() => socket.close())
+ await request(socket, 1, 'Target.attachToTarget', { targetId: entry.tabId, flatten: true })
+ const response = await request(socket, 2, 'Browser.setDownloadBehavior', { behavior: 'allow', downloadPath })
+ assert.deepEqual(response.result, {})
+ let savePath
+ const item = Object.assign(new EventEmitter(), {
+ setSavePath(path) { savePath = path },
+ getURL() { return 'https://example.com/file' },
+ getFilename() { return 'report.pdf' },
+ })
+ let prevented = false
+ handlers.get('bot:a')({ preventDefault() { prevented = true } }, item, views[0].webContents)
+ assert.equal(prevented, false)
+ assert.match(savePath, new RegExp(`^${downloadPath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}[/\\\\]`, 'u'))
+})
+
test('user hold closes relay sockets, rejects endpoints, and allows a new endpoint after give-back', async t => {
const { manager } = fixture()
t.after(() => manager.dispose())
diff --git a/browser-plugins/test/write-safety.test.js b/browser-plugins/test/write-safety.test.js
index fc746b77..cf42e7c8 100644
--- a/browser-plugins/test/write-safety.test.js
+++ b/browser-plugins/test/write-safety.test.js
@@ -162,6 +162,49 @@ async function setup(t, actionTimeout = 500, options = {}) {
return { fixture, profileRoot, session }
}
+async function mountedDownloadAndUpload(t, rootsFor) {
+ const fixture = await fixtureServer()
+ const profileRoot = await mkdtemp(join(tmpdir(), 'browser-mounted-download-'))
+ const { roots, ...destinations } = rootsFor(profileRoot)
+ await Promise.all(roots.map(root => mkdir(root, { recursive: true })))
+ let cleanup
+ let tool
+ t.after(async () => {
+ await cleanup?.()
+ await fixture.close()
+ await rm(profileRoot, { recursive: true, force: true })
+ })
+ mountBrowserPlugin({
+ effect(create) { cleanup = create() },
+ tools: { register(value) { tool = value } },
+ }, {
+ toolDefs: [{
+ name: 'browser_open',
+ needsBrowser: true,
+ async execute(args, { session }) {
+ const downloaded = await session.open(args.downloadUrl)
+ const snapshot = await session.open(args.pageUrl)
+ const uploaded = await session.upload(findRef(snapshot, 'Upload file'), [args.path])
+ return `${downloaded}\n${uploaded}`
+ },
+ }],
+ defineTool: value => value,
+ keyOf: async () => 'bot',
+ profileRoot,
+ downloadRoot: join(profileRoot, 'legacy-downloads'),
+ downloadRoots: async () => roots,
+ uploadRoots: async () => roots,
+ headless: true,
+ playwrightUrl,
+ })
+ const result = await tool.execute({
+ downloadUrl: new URL('download', fixture.url).href,
+ pageUrl: fixture.url,
+ path: join(roots[0], 'report.txt'),
+ }, { agent: { id: 'bot' } })
+ return { ...destinations, result }
+}
+
test('unlabeled POST submits, GET forms, and links are not gated', async (t) => {
const { fixture, session } = await setup(t)
const actions = []
@@ -477,6 +520,28 @@ test('standalone uploads without configured roots are refused', async (t) => {
assert.doesNotMatch(await session.snapshotText(), /notes\.txt/)
})
+test('mounted downloads and uploads use the Bot working directory', async t => {
+ const { result, working } = await mountedDownloadAndUpload(t, profileRoot => ({
+ roots: [join(profileRoot, 'working'), join(profileRoot, 'team')],
+ working: join(profileRoot, 'working'),
+ }))
+ assert.match(result, /Downloaded "report\.txt" to /u)
+ assert.ok(result.includes(join(working, 'report.txt')))
+ assert.match(result, /report\.txt/u)
+ assert.equal(await readFile(join(working, 'report.txt'), 'utf8'), 'download contents')
+})
+
+test('mounted downloads and uploads fall back to the team folder', async t => {
+ const { result, team } = await mountedDownloadAndUpload(t, profileRoot => ({
+ roots: [join(profileRoot, 'team')],
+ team: join(profileRoot, 'team'),
+ }))
+ assert.match(result, /Downloaded "report\.txt" to /u)
+ assert.ok(result.includes(join(team, 'report.txt')))
+ assert.match(result, /report\.txt/u)
+ assert.equal(await readFile(join(team, 'report.txt'), 'utf8'), 'download contents')
+})
+
test('opening a direct attachment URL saves the download instead of throwing', async (t) => {
const { fixture, profileRoot, session } = await setup(t)
const actions = []
diff --git a/docs/plans/2026-10-21-browser-plugins.md b/docs/plans/2026-10-21-browser-plugins.md
index 548fdd67..62910613 100644
--- a/docs/plans/2026-10-21-browser-plugins.md
+++ b/docs/plans/2026-10-21-browser-plugins.md
@@ -21,8 +21,8 @@ Bot 是长期身份。登录应该跟着 Bot 走,而不是跟着某一段对
- 只有发帖、上传、下载、删除需要用户授权。Bot 在设置的「浏览器」页获得匹配网站和操作类型的预授权时直接执行;否则走 DSH 审批卡片,审批只允许本次操作。预授权可设过期时间。
- 删除无论有没有预授权,都先返回核对快照;Bot 必须在检查目标后用 `browser_click` 的 `confirm: true` 再点同一个元素,且页面 URL 和标签都必须匹配,才进入正常授权流程。
- 付款、购买、转账等操作永远不由 Bot 执行;付款详情也不由 Bot 输入。Bot 调用 `browser_handoff`(或脚本里的 `handoff`),由用户完成。登录或验证码也可交给用户;交接后点击、输入、打开页面都会停住,直到 `browser_resume`。不另设域名名单,也不拦截内网地址。
-- 上传只允许使用 Bot 的工作目录或 `browser-downloads/<botId>/` 中的文件,链接目标在校验前解析。
-- 已授权的发帖、上传、下载、删除若结果未知,会按来源记录,要求先用快照核实;页面仍未观察前,不允许重复同来源的操作。下载文件保存到 Bot 独立的 `browser-downloads/<botId>/` 目录。
+- 上传只允许使用 Bot 的工作目录、团队目录或 `browser-downloads/<botId>/` 中的文件,链接目标在校验前解析。
+- 已授权的发帖、上传、下载、删除若结果未知,会按来源记录,要求先用快照核实;页面仍未观察前,不允许重复同来源的操作。下载文件保存到 Bot 的工作目录;没有工作目录时保存到团队目录。
- 三个插件:
- `refs`:打开、快照、按编号点击和填写、截图。每一步留在会话里,可以核对。快照会读进开放的 Shadow DOM 和同源 iframe。
- `script`:一次提交一段 JavaScript,帮手已经在作用域里。这是 Hermes `browser_exec` 和 ego heredoc 的形状。
diff --git a/ds-bot/src/host/browser-plugins.js b/ds-bot/src/host/browser-plugins.js
index 9de923ae..0bc84e05 100644
--- a/ds-bot/src/host/browser-plugins.js
+++ b/ds-bot/src/host/browser-plugins.js
@@ -1,6 +1,6 @@
// The whole team uses one browser plugin. Each Bot still gets its own profile
// directory, including the group Sessions where that Bot speaks.
-import { join } from 'node:path'
+import { isAbsolute, join } from 'node:path'
import { randomUUID } from 'node:crypto'
import { defineTool } from '@deepseek-ai/dsh-tools'
import { completeDeepseek } from './browser/deepseek.js'
@@ -10,7 +10,7 @@ import * as script from './browser/script.js'
import * as task from './browser/task.js'
export const browserPlugins = { refs, script, task }
-function appBrowserEndpoint(botId) {
+export function appBrowserEndpoint(botId, downloadRoots) {
if (typeof process.send !== 'function') throw new Error('The app browser relay is unavailable.')
const id = randomUUID()
return new Promise((resolve, reject) => {
@@ -26,7 +26,7 @@ function appBrowserEndpoint(botId) {
else reject(new Error(message.error || 'The app browser relay is unavailable.'))
}
process.on('message', receive)
- process.send({ type: 'ds-bot:browser-endpoint', id, botId }, error => {
+ process.send({ type: 'ds-bot:browser-endpoint', id, botId, downloadRoots }, error => {
if (error) receive({ type: 'ds-bot:browser-endpoint-response', id, error: error.message })
})
})
@@ -112,16 +112,22 @@ export function install(rt) {
? rt.config.browserHeadless
: !process.env.DISPLAY
const downloadRoot = join(rt.home, 'browser-downloads')
+ async function downloadRoots(botId) {
+ await rt.load()
+ const team = rt.teamFolder()
+ const requested = rt.workDirOf({ botId })
+ const working = requested !== undefined && await rt.isFolder(requested) ? requested : team
+ return [...new Set([working, team].filter(root => typeof root === 'string' && isAbsolute(root)))]
+ }
mountBrowserPlugin(rt.ctx, {
toolDefs: plugin.tools ?? plugin.toolDefs,
defineTool,
profileRoot: join(rt.home, 'browser-profiles'),
downloadRoot,
+ downloadRoots,
async uploadRoots(botId) {
- await rt.load()
- const requested = rt.workDirOf({ botId })
- const working = requested !== undefined && await rt.isFolder(requested) ? requested : rt.teamFolder()
- return [working, join(downloadRoot, botId)].filter(Boolean)
+ const roots = await downloadRoots(botId)
+ return [...new Set([...roots, join(downloadRoot, botId)])]
},
headless,
playwrightUrl,
diff --git a/ds-bot/src/host/browser/mount.js b/ds-bot/src/host/browser/mount.js
index 926bb781..8d4428d3 100644
--- a/ds-bot/src/host/browser/mount.js
+++ b/ds-bot/src/host/browser/mount.js
@@ -30,9 +30,9 @@ export const browserOutput = {
/**
* @param {any} ctx
- * @param {{ toolDefs: any[], defineTool: Function, keyOf: (exec: any) => Promise<string|undefined>, profileRoot: string, downloadRoot?: string, uploadRoots?: (botId: string) => Promise<string[]>, headless: boolean, playwrightUrl?: string, executablePath?: string, actionTimeout?: number, authorize?: (exec: any, botId: string, action: any) => Promise<void>, complete?: Function, connect?: (botId: string) => Promise<string>, getHold?: (botId: string) => any, onHold?: (botId: string, hold: any) => void, subscribeHolds?: (listener: (botId: string, hold: any) => void) => (() => void) | undefined, openSession?: typeof openBotBrowser }} options
+ * @param {{ toolDefs: any[], defineTool: Function, keyOf: (exec: any) => Promise<string|undefined>, profileRoot: string, downloadRoot?: string, downloadRoots?: (botId: string) => Promise<string[]>, uploadRoots?: (botId: string) => Promise<string[]>, headless: boolean, playwrightUrl?: string, executablePath?: string, actionTimeout?: number, authorize?: (exec: any, botId: string, action: any) => Promise<void>, complete?: Function, connect?: (botId: string, downloadRoots?: string[]) => Promise<string>, getHold?: (botId: string) => any, onHold?: (botId: string, hold: any) => void, subscribeHolds?: (listener: (botId: string, hold: any) => void) => (() => void) | undefined, openSession?: typeof openBotBrowser }} options
*/
-export function mountBrowserPlugin(ctx, { toolDefs, defineTool, keyOf, profileRoot, downloadRoot, uploadRoots, headless, playwrightUrl, executablePath, actionTimeout, authorize, complete, connect, getHold, onHold, subscribeHolds, openSession = openBotBrowser }) {
+export function mountBrowserPlugin(ctx, { toolDefs, defineTool, keyOf, profileRoot, downloadRoot, downloadRoots, uploadRoots, headless, playwrightUrl, executablePath, actionTimeout, authorize, complete, connect, getHold, onHold, subscribeHolds, openSession = openBotBrowser }) {
const sessions = new Map()
const unsubscribeHolds = subscribeHolds?.((botId, hold) => {
if (hold?.by !== 'user') return
@@ -60,15 +60,16 @@ export function mountBrowserPlugin(ctx, { toolDefs, defineTool, keyOf, profileRo
if (getHold?.(botId)?.by === 'user') throw new Error('The user has taken over this browser. Wait for them to give it back.')
let session = sessions.get(botId)
if (spec.needsBrowser && session === undefined) {
+ const roots = downloadRoots ? await downloadRoots(botId) : undefined
session = await openSession({
botId,
profileRoot,
- downloadDir: join(downloadRoot ?? join(profileRoot, 'browser-downloads'), botId),
+ downloadDir: roots === undefined ? join(downloadRoot ?? join(profileRoot, 'browser-downloads'), botId) : roots[0],
headless,
playwrightUrl,
executablePath,
actionTimeout,
- connect,
+ connect: connect ? id => connect(id, roots ?? []) : undefined,
getHold: () => getHold?.(botId),
onHold: hold => onHold?.(botId, hold),
uploadRoots: uploadRoots ? () => uploadRoots(botId) : undefined,
diff --git a/ds-bot/test/browser-plugins.test.js b/ds-bot/test/browser-plugins.test.js
index 82e0550f..2f9e8df4 100644
--- a/ds-bot/test/browser-plugins.test.js
+++ b/ds-bot/test/browser-plugins.test.js
@@ -5,6 +5,8 @@ import { join } from 'node:path'
import { test } from 'node:test'
import { apply, createRuntime } from '../index.js'
import { gateScope } from '../src/host/browser/gate.js'
+import { appBrowserEndpoint } from '../src/host/browser-plugins.js'
+import { mountBrowserPlugin } from '../src/host/browser/mount.js'
import { systemPrompt as refsPrompt, toolDefs as refsTools } from '../src/host/browser/refs.js'
import { fakeApproval, fakeContext } from './fake-ctx.js'
@@ -90,6 +92,64 @@ function browserExec(botId = 'b2', sessionId = botId) {
}
}
+test('app browser endpoint carries download roots for the Bot resolved from the exec', async () => {
+ const originalSend = process.send
+ const roots = ['/workspace/b2', '/workspace']
+ let request
+ const tools = new Map()
+ let cleanup
+ process.send = (message, callback) => {
+ request = message
+ callback?.()
+ queueMicrotask(() => process.emit('message', {
+ type: 'ds-bot:browser-endpoint-response',
+ id: message.id,
+ url: 'ws://127.0.0.1:1234/devtools/browser/token',
+ }))
+ return true
+ }
+ try {
+ mountBrowserPlugin({
+ effect(create) { cleanup = create() },
+ tools: { register(tool) { tools.set(tool.name, tool) } },
+ }, {
+ toolDefs: [{ name: 'browser_open', needsBrowser: true, execute: () => 'opened' }],
+ defineTool: value => value,
+ keyOf: async exec => exec.agent.id,
+ profileRoot: '/profiles',
+ downloadRoot: '/legacy-downloads',
+ downloadRoots: async botId => {
+ assert.equal(botId, 'b2')
+ return roots
+ },
+ uploadRoots: async botId => {
+ assert.equal(botId, 'b2')
+ return roots
+ },
+ headless: true,
+ connect: appBrowserEndpoint,
+ openSession: async options => {
+ assert.equal(options.botId, 'b2')
+ assert.equal(options.downloadDir, roots[0])
+ assert.deepEqual(await options.uploadRoots(), roots)
+ await options.connect(options.botId)
+ return { close: async () => {} }
+ },
+ })
+ const result = await tools.get('browser_open').execute({ botId: 'other' }, { agent: { id: 'b2' } })
+ assert.deepEqual(request, {
+ type: 'ds-bot:browser-endpoint',
+ id: request.id,
+ botId: 'b2',
+ downloadRoots: roots,
+ })
+ assert.equal(result, 'opened')
+ } finally {
+ await cleanup?.()
+ process.send = originalSend
+ }
+})
+
test('no browser plugin is mounted unless one is selected for the team', (t) => {
const { ctx, stop } = start({})
t.after(stop)