Skip to content

A full-featured download manager.

feat(bridge): persist and reconcile paired download handoffs (#2535)

Dr_rOotfc8bcb7fbfa0
diff --git a/e2e/bridge/README.md b/e2e/bridge/README.md
index f17a18d3..afca1bb6 100644
--- a/e2e/bridge/README.md
+++ b/e2e/bridge/README.md
@@ -286,3 +286,22 @@ git worktree remove --force ../motrix-turbo-srv
`remote-extension-firefox-wss.spec.ts` are the active browser-extension WSS
lifecycle gates, covering pairing, download submission, restart, revocation,
and re-pairing through real browsers.
+
+## Local handoff candidate integration
+
+Build the candidate MDXP checkout first. Run the following from the Motrix checkout with a Node-compatible SQLite native module and the bundled aria2 binary available.
+
+```sh
+MOTRIX_HANDOFF_SDK=/path/to/built/mdxp-checkout \
+ node --import tsx scripts/verify-local-download-handoff.mjs
+```
+
+The test creates a new database and lockbox for each run under `output/ci/download-handoff/`. A synthetic authenticated extension session uses the candidate SDK over inherited JSON-RPC pipes. The fixture registers four methods on an isolated dispatcher and supplies a direct HTTP task snapshot. The SQLite journal, task storage, encryption and engine adapter are the shared host implementations.
+
+The parent terminates its own peers after prepare, after commit but before its reply, and after engine acceptance but before activation cleanup. The report records the candidate revision, task and engine IDs, source request count and file SHA-256. An ambiguous engine start remains unresolved when the reserved ID cannot be found. Production capability advertisement, pairing, browser decisions and host task-manager startup are outside this harness.
+
+To drive the same transaction from Chromium, also set `MOTRIX_EXTENSION_DIR` to the local extension checkout with its Chromium build, and optionally `CHROME_BINARY` to Chrome for Testing. The isolated extension loads the release-click listener, confirmation service, packaged popup style and confirmation form. The driver enters a filename and request header and clicks Add. A binding on that extension page forwards the frozen download to the candidate RPC client. The file server rejects a second file request. Browser evidence is recorded alongside the task, engine and digest checks. This checks the pre-request link path; production MBP1/WebSocket negotiation and late native-download cancellation are separate integrations.
+
+### Local paired browser acceptance
+
+From the extension checkout, set `MOTRIX_HOST_DIR` to this checkout and `MOTRIX_HANDOFF_SDK` to the built candidate SDK. Run `pnpm test:chromium-confirmation --paired-handoff` and `pnpm test:firefox-takeover --paired-handoff`. The extension drives the production MBP1 client against a separate loopback WebSocket bridge and the shared journal. An out-of-band test operator enters the host-generated code. Accepted transfers use a real aria2 engine; the lost-reply case closes the socket after commit and reconciles with status on a newly authenticated connection. The host fixture accepts only its generated loopback files and isolated output directory. Normal product builds do not advertise the candidate by default.
diff --git a/e2e/bridge/README.zh-CN.md b/e2e/bridge/README.zh-CN.md
index 95c88c9c..b68bffb2 100644
--- a/e2e/bridge/README.zh-CN.md
+++ b/e2e/bridge/README.zh-CN.md
@@ -255,3 +255,22 @@ git worktree remove --force ../motrix-turbo-srv
- `remote-extension-wss.spec.ts` 与
`remote-extension-firefox-wss.spec.ts` 是当前启用的 browser-extension WSS
生命周期门禁,通过真实浏览器覆盖配对、下载提交、重启、撤销和重新配对。
+
+## 下载交接候选协议的本地集成
+
+先在候选 MDXP 工作目录构建 SDK,再从 Motrix 仓库运行下列命令。需要 Node ABI 的 SQLite 原生模块和仓库配套的 aria2。
+
+```sh
+MOTRIX_HANDOFF_SDK=/path/to/built/mdxp-checkout \
+ node --import tsx scripts/verify-local-download-handoff.mjs
+```
+
+每次运行在 `output/ci/download-handoff/` 下创建独立数据库和密钥文件。测试使用合成的已认证扩展身份,通过继承的 JSON-RPC 管道调用候选 SDK。测试入口在隔离调度器上注册四个方法,并构造直接 HTTP 任务快照;SQLite 账本、任务存储、加密和引擎适配器均使用两端共享的主仓实现。
+
+父进程分别在 prepare 完成、commit 已写库但未回复,以及引擎已接受但尚未清理待启动记录时终止测试子进程。报告记录候选提交、任务 ID、引擎 GID、源站请求数和文件 SHA-256。对可能已经启动但查不到原 GID 的任务,账本保留待核对状态。生产能力声明、配对、浏览器确认和主机任务管理器的启动接线仍需单独验收。
+
+要由 Chromium 驱动同一笔事务,再将 `MOTRIX_EXTENSION_DIR` 指向已完成 Chromium 构建的扩展工作目录,并可通过 `CHROME_BINARY` 指定 Chrome for Testing。隔离扩展加载请求前点击监听器、确认服务、发行产物样式和确认表单。驱动填写文件名和请求头,点击“添加”;仅该扩展页面可用的测试绑定将冻结的选项交给本地候选 RPC 客户端。文件源拒绝第二次文件请求。报告同时记录确认时的请求数、浏览器下载项、宿主任务、引擎 GID 和文件摘要。本用例覆盖首次请求前的直链;生产 MBP1/WebSocket 能力协商及已创建浏览器下载项的停止时序仍需分别接入。
+
+### 本地配对浏览器验收
+
+从扩展仓库运行,将 `MOTRIX_HOST_DIR` 指向此仓库,`MOTRIX_HANDOFF_SDK` 指向已构建的候选 SDK,分别执行 `pnpm test:chromium-confirmation --paired-handoff` 和 `pnpm test:firefox-takeover --paired-handoff`。真实扩展 MBP1 客户端连接隔离的本机 WebSocket 桥,测试操作员从独立通道输入宿主生成的配对码。已接受任务由真实 aria2 下载;丢回执用例在 commit 后关闭连接,并通过重新认证的新连接查询原账本。测试宿主仅接收临时文件源和隔离目录。正常产品构建默认保持既有能力声明。
diff --git a/scripts/local-handoff-browser.mjs b/scripts/local-handoff-browser.mjs
new file mode 100644
index 00000000..ec20c292
--- /dev/null
+++ b/scripts/local-handoff-browser.mjs
@@ -0,0 +1,173 @@
+// Disposable extension page. Only its Playwright binding can reach the local
+// candidate client; the test file origin has no RPC or operator endpoint.
+import assert from 'node:assert/strict'
+import { execFileSync } from 'node:child_process'
+import {
+ copyFile,
+ mkdir,
+ mkdtemp,
+ readdir,
+ readFile,
+ writeFile,
+} from 'node:fs/promises'
+import path from 'node:path'
+import { chromium } from 'playwright'
+import { build } from 'vite'
+
+export async function confirmLocalHandoff({
+ root,
+ extensionRoot,
+ origin,
+ submit,
+ requestCount,
+}) {
+ const base = path.join(root, 'output/playwright/manual/download-handoff')
+ await mkdir(base, { recursive: true })
+ const dir = await mkdtemp(path.join(base, 'run-'))
+ const ext = path.join(dir, 'extension')
+ const sources = [
+ ['release-click-content', 'content.js'],
+ ['local-host-handoff', 'runner.js'],
+ ]
+ for (const [entry, filename] of sources) {
+ await build({
+ root: extensionRoot,
+ configFile: false,
+ publicDir: false,
+ logLevel: 'error',
+ define: { 'process.env.NODE_ENV': JSON.stringify('production') },
+ resolve: { alias: { '@': path.join(extensionRoot, 'src') } },
+ build: {
+ outDir: ext,
+ emptyOutDir: false,
+ lib: {
+ entry: path.join(extensionRoot, 'scripts/fixtures', `${entry}.ts`),
+ name: 'fixture',
+ formats: ['iife'],
+ fileName: () => filename,
+ },
+ },
+ })
+ }
+ await writeFile(
+ path.join(ext, 'manifest.json'),
+ JSON.stringify({
+ manifest_version: 3,
+ name: 'Local candidate handoff acceptance',
+ version: '1',
+ permissions: ['storage', 'tabs', 'downloads'],
+ host_permissions: ['http://127.0.0.1/*'],
+ background: { service_worker: 'worker.js' },
+ content_scripts: [
+ {
+ matches: ['http://127.0.0.1/*'],
+ js: ['content.js'],
+ run_at: 'document_start',
+ },
+ ],
+ })
+ )
+ await writeFile(
+ path.join(ext, 'worker.js'),
+ 'chrome.runtime.onInstalled.addListener(()=>{})'
+ )
+ // Use the packaged popup's layout so the driver exercises pointer hit testing.
+ const shipped = path.join(extensionRoot, 'dist/chromium')
+ const popup = await readFile(path.join(shipped, 'popup.html'), 'utf8')
+ const css = popup.match(
+ /<link rel="stylesheet"[^>]+href="(\/assets\/[\w.-]+\.css)"/
+ )?.[1]
+ assert.ok(css, 'Build the Chromium extension before browser acceptance')
+ const assets = path.join(ext, 'assets')
+ await mkdir(assets, { recursive: true })
+ for (const file of await readdir(path.join(shipped, 'assets'))) {
+ if (file === path.basename(css) || /\.woff2?$/.test(file))
+ await copyFile(
+ path.join(shipped, 'assets', file),
+ path.join(assets, file)
+ )
+ }
+ await writeFile(
+ path.join(ext, 'runner.html'),
+ `<!doctype html><meta charset="utf-8"><link rel="stylesheet" href="${css}"><body><script src="runner.js"></script></body>`
+ )
+ const ctx = await chromium.launchPersistentContext(
+ path.join(dir, 'profile'),
+ {
+ channel: 'chromium',
+ executablePath: process.env.CHROME_BINARY,
+ headless: true,
+ viewport: { width: 400, height: 600 },
+ ignoreDefaultArgs: ['--disable-extensions'],
+ args: [`--load-extension=${ext}`, `--disable-extensions-except=${ext}`],
+ }
+ )
+ try {
+ const sw =
+ ctx.serviceWorkers()[0] ?? (await ctx.waitForEvent('serviceworker'))
+ const runner = ctx.pages()[0]
+ const runnerUrl = new URL('runner.html', sw.url()).href
+ let submissions = 0,
+ taskId
+ await runner.exposeBinding(
+ 'submitLocalCandidate',
+ async (source, download) => {
+ assert.equal(source.frame.url(), runnerUrl)
+ assert.equal(++submissions, 1)
+ assert.equal(
+ download.selection.primary.url,
+ `${origin}/download/click-live`
+ )
+ assert.equal(download.meta.suggestedFilename, 'handoff.bin')
+ assert.equal(
+ download.selection.primary.headers['X-Motrix-Test-Context'],
+ 'fixture'
+ )
+ const result = await submit(download)
+ taskId = result.taskId
+ return result
+ }
+ )
+ await runner.goto(runnerUrl)
+ await runner.evaluate(
+ (origin) => window.installLocalCandidate(origin),
+ origin
+ )
+ const site = await ctx.newPage()
+ await site.goto(`${origin}/start/click-live`)
+ const link = site.getByRole('link', { name: 'Download' })
+ await link.focus()
+ await site.waitForSelector('html[data-fixture-ready]')
+ await link.click()
+ await runner.bringToFront()
+ const dialog = runner.getByRole('dialog')
+ await dialog.waitFor()
+ const browserItems = () =>
+ runner.evaluate(async () => (await chrome.downloads.search({})).length)
+ assert.equal(requestCount(), 0)
+ assert.equal(await browserItems(), 0)
+ await dialog.locator('input[id$="-filename"]').fill('handoff.bin')
+ await dialog.locator('summary').click()
+ await dialog
+ .locator('textarea[id$="-headers"]')
+ .fill('X-Motrix-Test-Context: fixture')
+ await dialog.getByRole('button', { name: 'Add', exact: true }).click()
+ await dialog.waitFor({ state: 'hidden', timeout: 60000 })
+ assert.ok(taskId)
+ assert.equal(submissions, 1)
+ assert.equal(await browserItems(), 0)
+ return {
+ browser: ctx.browser().version(),
+ extensionRevision: execFileSync('git', ['rev-parse', 'HEAD'], {
+ cwd: extensionRoot,
+ encoding: 'utf8',
+ }).trim(),
+ requestsAtConfirmation: 0,
+ nativeItems: 0,
+ submissions,
+ taskId,
+ }
+ } finally {
+ await ctx.close()
+ }
+}
diff --git a/scripts/paired-handoff-host.mjs b/scripts/paired-handoff-host.mjs
new file mode 100644
index 00000000..27585dca
--- /dev/null
+++ b/scripts/paired-handoff-host.mjs
@@ -0,0 +1,223 @@
+// Local acceptance composition root: a real loopback MBP1 host, prompt, journal
+// and engine. The inherited IPC channel is the isolated operator's display.
+import assert from 'node:assert/strict'
+import { createHash, randomBytes, randomUUID } from 'node:crypto'
+import { mkdir, mkdtemp, readFile } from 'node:fs/promises'
+import path from 'node:path'
+import { pathToFileURL } from 'node:url'
+import { Mbp1CredentialStore } from '../src/core/bridge/credential-store.ts'
+import { FilePairingStore } from '../src/core/bridge/file-pairing-store.ts'
+import { journalHandoffModule } from '../src/core/bridge/journal-handoff-module.ts'
+import { PairingPromptController } from '../src/core/bridge/pairing-prompt-controller.ts'
+import { PairingService } from '../src/core/bridge/pairing-service.ts'
+import { FileRegistryStoreAdapter } from '../src/core/bridge/registry-store-adapter.ts'
+import { TrustedExtensionRegistry } from '../src/core/bridge/trusted-extension-registry.ts'
+import { WebSocketBridgeServer } from '../src/core/bridge/web-socket-bridge-server.ts'
+import { LibsodiumSecretStore } from '../src/core/plugin/secret-store-libsodium.ts'
+import { DownloadHandoffJournal } from '../src/core/session/download-handoff-journal.ts'
+import { MotrixDatabase } from '../src/core/session/motrix-database.ts'
+import { TaskInstancePhase, TaskKind } from '../src/shared/types/task.ts'
+import { connectAdapter, spawnAria2ForTest } from '../src/test-utils/aria2.ts'
+import { makeInstanceRow, makeTaskRow } from '../src/test-utils/task-rows.ts'
+
+const sdk = await import(
+ pathToFileURL(path.resolve(process.env.MOTRIX_HANDOFF_SDK, 'dist/node.js'))
+)
+const root = path.resolve(import.meta.dirname, '../output/ci/paired-handoff')
+await mkdir(root, { recursive: true })
+const dir = await mkdtemp(path.join(root, 'run-'))
+const origin = process.env.MOTRIX_FIXTURE_ORIGIN
+assert.equal(new URL(origin).hostname, '127.0.0.1')
+const pairing = new PairingService(
+ new FilePairingStore(path.join(dir, 'pairing.json'))
+)
+const registry = new TrustedExtensionRegistry(
+ new FileRegistryStoreAdapter(path.join(dir, 'registry.json')),
+ []
+)
+await pairing.load()
+await registry.load()
+let pairPrompts = 0
+const prompts = new PairingPromptController({
+ onEnqueued: (prompt) => {
+ pairPrompts++
+ process.send({ event: 'pairing-prompt', code: prompt.code })
+ return 'delivered'
+ },
+})
+const db = new MotrixDatabase(path.join(dir, 'motrix.db'))
+db.init()
+const journal = new DownloadHandoffJournal(
+ db,
+ await LibsodiumSecretStore.create({ userDataDir: dir }),
+ () => true
+)
+const engine = await spawnAria2ForTest({ baseDir: dir })
+const { adapter, disconnect } = await connectAdapter(engine)
+const history = []
+const operationKeys = new Map()
+let authenticated = 0
+let dropReply = false
+const module = journalHandoffModule(sdk, journal, {
+ ttlMs: 120000,
+ directory: async (download) => {
+ const u = new URL(download.selection.primary.url)
+ assert.equal(u.origin, origin)
+ assert.ok(
+ [
+ '/download/paired-accept',
+ '/download/paired-rejected',
+ '/download/paired-lost',
+ ].includes(u.pathname)
+ )
+ if (u.pathname.endsWith('rejected'))
+ throw sdk.makeMdxpError(
+ sdk.ErrorCodes.InvalidParams,
+ 'Fixture directory unavailable'
+ )
+ if (download.saveDir !== undefined) assert.equal(download.saveDir, dir)
+ return dir
+ },
+ materialize: ({ taskId, engineId, saveDir, canonicalPayload }) => {
+ assert.equal(saveDir, dir)
+ const u = new URL(JSON.parse(canonicalPayload).selection.primary.url)
+ const name = path.basename(u.pathname) + '.bin'
+ dropReply = u.pathname.endsWith('lost')
+ const file = path.join(dir, name)
+ return {
+ task: {
+ ...makeTaskRow(taskId, TaskKind.Direct),
+ source: 'bridge',
+ saveDir: dir,
+ name,
+ finalName: name,
+ finalPath: file,
+ },
+ instances: [
+ {
+ ...makeInstanceRow(
+ randomUUID(),
+ taskId,
+ engineId,
+ TaskInstancePhase.HttpDownload
+ ),
+ uris: [u.href],
+ diskPath: file,
+ },
+ ],
+ }
+ },
+ committed: async (taskId, ctx) => {
+ await journal.activate(taskId, {
+ contains: async (gid) => (await adapter.getTaskStatus(gid)) !== null,
+ start: (intent) => {
+ const input = JSON.parse(intent.canonicalPayload)
+ const u = new URL(input.selection.primary.url)
+ return adapter.createDownload({
+ gid: intent.engineId,
+ saveDir: intent.saveDir,
+ filename: path.basename(u.pathname) + '.bin',
+ uris: [u.href],
+ headers: input.selection.primary.headers,
+ connections: 1,
+ })
+ },
+ })
+ if (dropReply) {
+ dropReply = false
+ const session = server.getSession(ctx.sessionKey)
+ assert.ok(session)
+ session.envelope.close()
+ }
+ },
+})
+for (const [method, binding] of Object.entries(module.methods)) {
+ const handle = binding.handle
+ binding.handle = (params, ctx) => {
+ operationKeys.set(params.operationId, {
+ instanceId: params.instanceId,
+ operationId: params.operationId,
+ principal: ctx.sessionKey,
+ })
+ history.push({
+ method: method
+ .split('.')
+ .at(-1)
+ .replace(/^./, (c) => c.toUpperCase()),
+ id: params.operationId,
+ })
+ return handle(params, ctx)
+ }
+}
+const server = new WebSocketBridgeServer({
+ pairing,
+ registry,
+ motrixVersion: '2.4.3',
+ appVersion: '2.4.3',
+ runtime: 'electron',
+ ffmpegAvailable: false,
+ localToken: randomBytes(32).toString('hex'),
+ instanceId: randomUUID(),
+ serverGeneration: randomUUID(),
+ credentials: await Mbp1CredentialStore.load(
+ path.join(dir, 'credentials.json')
+ ),
+ isOfficialId: () => false,
+ queueMbp1Dialog: (req) => prompts.enqueue(req),
+ onExtensionAuthenticated: () => {
+ authenticated++
+ },
+ extensionHandoff: module,
+})
+const port = await server.start('127.0.0.1', 0)
+process.send({ event: 'ready', port, instanceId: journal.instanceId })
+let stopping = false
+async function shutdown() {
+ if (stopping) return
+ stopping = true
+ await server.stop()
+ await pairing.stopAndDrain()
+ disconnect()
+ await engine.kill()
+ db.close()
+ process.exit(0)
+}
+process.on('disconnect', shutdown)
+process.on('message', async (m) => {
+ if (m === 'close') return shutdown()
+ if (m?.action !== 'snapshot') return
+ try {
+ const name = m.name
+ assert.match(name, /^paired-(accept|lost|rejected|cancel|browser)$/)
+ const tasks = db.getAllTasks().filter((t) => t.task.name === name + '.bin')
+ let sha256 = null
+ if (tasks.length) {
+ const end = Date.now() + 8000
+ while (Date.now() < end) {
+ const status = await adapter.getTaskStatus(tasks[0].instances[0].gid)
+ if (status?.status === 'completed') {
+ sha256 = createHash('sha256')
+ .update(await readFile(tasks[0].task.finalPath))
+ .digest('hex')
+ break
+ }
+ await new Promise((r) => setTimeout(r, 40))
+ }
+ }
+ process.send({
+ event: 'snapshot',
+ name,
+ authenticated,
+ pairPrompts,
+ states: [...new Set(history.map((h) => h.id))].map(
+ (id) => journal.status(operationKeys.get(id)).state
+ ),
+ history: history.splice(0),
+ tasks: tasks.map((t) => t.task.motrixId),
+ outbox: journal.pendingActivations(),
+ sha256,
+ })
+ } catch (error) {
+ process.send({ event: 'failure', message: error.message })
+ }
+})
diff --git a/scripts/verify-local-download-handoff.mjs b/scripts/verify-local-download-handoff.mjs
new file mode 100644
index 00000000..d3566d2e
--- /dev/null
+++ b/scripts/verify-local-download-handoff.mjs
@@ -0,0 +1,454 @@
+// Local candidate integration. Uses the real dispatcher, host DB and engine;
+// the isolated IPC harness supplies the authenticated-session fixture.
+import assert from 'node:assert/strict'
+import { execFileSync, fork } from 'node:child_process'
+import { createHash, randomUUID } from 'node:crypto'
+import { once } from 'node:events'
+import { mkdir, mkdtemp, readFile, writeFile } from 'node:fs/promises'
+import { createServer } from 'node:http'
+import { Socket } from 'node:net'
+import path from 'node:path'
+import { fileURLToPath, pathToFileURL } from 'node:url'
+import { MdxpDispatcher } from '../src/core/bridge/mdxp-dispatcher.ts'
+import { LibsodiumSecretStore } from '../src/core/plugin/secret-store-libsodium.ts'
+import {
+ DownloadHandoffJournal,
+ HandoffJournalRefusal,
+} from '../src/core/session/download-handoff-journal.ts'
+import { MotrixDatabase } from '../src/core/session/motrix-database.ts'
+import { TaskInstancePhase, TaskKind } from '../src/shared/types/task.ts'
+import { connectAdapter, spawnAria2ForTest } from '../src/test-utils/aria2.ts'
+import { makeInstanceRow, makeTaskRow } from '../src/test-utils/task-rows.ts'
+
+const root = path.resolve(import.meta.dirname, '..')
+const candidate = process.env.MOTRIX_HANDOFF_SDK
+if (!candidate)
+ throw new Error(
+ 'Set MOTRIX_HANDOFF_SDK to the built local MDXP candidate checkout'
+ )
+const sdk = await import(
+ pathToFileURL(path.join(path.resolve(candidate), 'dist/node.js')).href
+)
+const methods = sdk.Methods
+const sha = (bytes) => createHash('sha256').update(bytes).digest('hex')
+const principal = 'local-fixture:installation'
+async function peer(input) {
+ const { dir, stage, operationId, url, port, secret } = input
+ const db = new MotrixDatabase(path.join(dir, 'motrix.db'))
+ db.init()
+ const journal = new DownloadHandoffJournal(
+ db,
+ await LibsodiumSecretStore.create({ userDataDir: dir }),
+ () => stage === 'prepare'
+ )
+ const ctx = {
+ identity: { kind: 'extension' },
+ sessionKey: principal,
+ isReady: () => true,
+ isAuthorized: () => true,
+ }
+ const dispatcher = new MdxpDispatcher()
+ function register(name, run) {
+ dispatcher.register(
+ methods[`DownloadHandoff${name}`],
+ sdk[`DownloadHandoff${name}ParamsSchema`],
+ async (p, session) => {
+ assert.equal(session.identity.kind, 'extension')
+ assert.ok(
+ session.isReady() && session.isAuthorized() && session.sessionKey
+ )
+ try {
+ const state = await run({ ...p, principal: session.sessionKey }, p)
+ return sdk[`DownloadHandoff${name}ResultSchema`].parse({
+ instanceId: p.instanceId,
+ operationId: p.operationId,
+ ...state,
+ })
+ } catch (error) {
+ if (!(error instanceof HandoffJournalRefusal)) throw error
+ const code = {
+ 'instance-changed': sdk.ErrorCodes.HandoffInstanceChanged,
+ 'payload-conflict': sdk.ErrorCodes.HandoffPayloadConflict,
+ 'not-accepting': sdk.ErrorCodes.CapabilityNotSupported,
+ }[error.reason]
+ // fromStdio uses the same vscode-jsonrpc ResponseError class as its transport.
+ throw new sdk.ResponseError(code, error.message)
+ }
+ }
+ )
+ }
+ register('Prepare', (key, p) => {
+ if (p.download.saveDir !== undefined) assert.equal(p.download.saveDir, dir)
+ return journal.prepare(
+ key,
+ sdk.canonicalDownloadHandoffPayload(p.download),
+ dir,
+ 120_000
+ )
+ })
+ register('Status', (key) => journal.status(key))
+ register('Abort', (key) => journal.abort(key))
+ register('Commit', (key, p) =>
+ journal.commit(key, p.payloadHash, (intent) => {
+ const frozen = JSON.parse(intent.canonicalPayload)
+ assert.equal(intent.saveDir, dir)
+ assert.equal(frozen.selection.primary.url, url)
+ const dest = path.join(dir, 'handoff.bin')
+ return {
+ task: {
+ ...makeTaskRow(intent.taskId, TaskKind.Direct),
+ source: 'bridge',
+ saveDir: dir,
+ name: 'handoff.bin',
+ finalName: 'handoff.bin',
+ finalPath: dest,
+ },
+ instances: [
+ {
+ ...makeInstanceRow(
+ randomUUID(),
+ intent.taskId,
+ intent.engineId,
+ TaskInstancePhase.HttpDownload
+ ),
+ uris: [url],
+ diskPath: dest,
+ },
+ ],
+ }
+ })
+ )
+ // The inherited pipes carry real JSON-RPC. The IPC channel carries only
+ // test barriers so killing a peer can lose its reply without losing evidence.
+ const inputPipe = new Socket({ fd: 4, readable: true, writable: false })
+ const outputPipe = new Socket({ fd: 5, readable: false, writable: true })
+ const connection = sdk.fromStdio({ input: inputPipe, output: outputPipe })
+ for (const name of ['Prepare', 'Commit', 'Status', 'Abort']) {
+ const method = methods[`DownloadHandoff${name}`]
+ connection.onRequest(method, async (params) => {
+ const response = await dispatcher.dispatch(method, params, ctx)
+ if (stage === 'commit' && name === 'Commit') {
+ process.send({ checkpoint: 'commit-before-reply' })
+ await new Promise(() => {})
+ }
+ return response
+ })
+ }
+ connection.listen()
+ process.send({ checkpoint: 'ready', instanceId: journal.instanceId })
+ const [command] = await once(process, 'message')
+ if (command !== 'activate') throw new Error('Unexpected local barrier')
+ const status = journal.status({
+ principal,
+ instanceId: input.instanceId,
+ operationId,
+ })
+ assert.equal(status.state, 'committed')
+ assert.equal(status.taskId, input.taskId)
+ assert.equal(db.getAllTasks().length, 1)
+ const [instance] = db.getTask(status.taskId).instances
+ const { adapter, disconnect } = await connectAdapter({ port, secret })
+ try {
+ const activated = await journal.activate(status.taskId, {
+ contains: async (gid) => (await adapter.getTaskStatus(gid)) !== null,
+ start: async (intent) => {
+ assert.equal(stage, 'start')
+ const frozen = sdk.DownloadHandoffPayloadSchema.parse(
+ JSON.parse(intent.canonicalPayload)
+ )
+ const gid = await adapter.createDownload({
+ uris: [frozen.selection.primary.url],
+ headers: frozen.selection.primary.headers,
+ filename: frozen.meta.suggestedFilename,
+ saveDir: intent.saveDir,
+ gid: intent.engineId,
+ connections: 1,
+ })
+ assert.equal(gid, instance.gid)
+ // The parent kills this peer after engine acceptance, before SQLite cleanup.
+ process.send({ checkpoint: 'start', gid })
+ await new Promise(() => {})
+ },
+ })
+ assert.equal(activated, 'activated')
+ assert.deepEqual(journal.pendingActivations(), [])
+ assert.equal(
+ await journal.activate(status.taskId, {
+ contains: async () => false,
+ start: () => assert.fail('second dispatch'),
+ }),
+ 'absent'
+ )
+ return {
+ state: status.state,
+ taskId: status.taskId,
+ gid: instance.gid,
+ outbox: 0,
+ }
+ } finally {
+ disconnect()
+ connection.dispose()
+ inputPipe.destroy()
+ outputPipe.destroy()
+ db.close()
+ }
+}
+
+if (process.argv.includes('--peer')) {
+ process.once('message', async (input) => {
+ try {
+ const data = await peer(input)
+ process.send({ checkpoint: input.stage, ...data })
+ // Deliberately leave prepared/committed DB connections open at the barrier.
+ if (input.stage === 'recover') process.disconnect()
+ } catch (error) {
+ process.send({ error: String(error) })
+ process.exitCode = 1
+ process.disconnect()
+ }
+ })
+} else {
+ const output = path.join(root, 'output/ci/download-handoff')
+ await mkdir(output, { recursive: true })
+ const dir = await mkdtemp(path.join(output, 'run-'))
+ const bytes = Buffer.alloc(256 * 1024, 0x35)
+ const requests = []
+ const server = createServer((req, res) => {
+ if (req.url === '/start/click-live') {
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' })
+ res.end(
+ `<a href="/download/click-live" data-dl-file="click-live" data-dl-bytes="${bytes.length}">Download</a>`
+ )
+ return
+ }
+ if (req.url !== '/download/click-live') {
+ res.writeHead(404).end()
+ return
+ }
+ requests.push({
+ method: req.method,
+ usesFrozenHeader: req.headers['x-motrix-test-context'] === 'fixture',
+ })
+ if (
+ requests.length !== 1 ||
+ req.method !== 'GET' ||
+ !requests[0].usesFrozenHeader
+ ) {
+ res.writeHead(410).end()
+ return
+ }
+ res.writeHead(200, {
+ 'content-type': 'application/octet-stream',
+ 'content-length': bytes.length,
+ })
+ res.end(bytes)
+ })
+ server.listen(0, '127.0.0.1')
+ await once(server, 'listening')
+ const url = `http://127.0.0.1:${server.address().port}/download/click-live`
+ let engine
+ const evidence = {
+ status: 'running',
+ hostRevision: execFileSync('git', ['rev-parse', 'HEAD'], {
+ cwd: root,
+ encoding: 'utf8',
+ }).trim(),
+ sdkVersion: (
+ await import(
+ pathToFileURL(path.join(path.resolve(candidate), 'package.json')).href,
+ { with: { type: 'json' } }
+ )
+ ).default.version,
+ sdkRevision: execFileSync('git', ['rev-parse', 'HEAD'], {
+ cwd: path.resolve(candidate),
+ encoding: 'utf8',
+ }).trim(),
+ checkpoints: [],
+ }
+ try {
+ engine = await spawnAria2ForTest({ baseDir: dir })
+ const example = {
+ source: { pageUrl: url, pageTitle: 'local integration', detectedAt: 42 },
+ selection: {
+ kind: 'direct',
+ primary: { url, headers: { 'X-Motrix-Test-Context': 'fixture' } },
+ },
+ meta: { suggestedFilename: 'handoff.bin', qualityLabel: 'local' },
+ saveDir: dir,
+ }
+ const runHandoff = async (download) => {
+ const operationId = randomUUID()
+ let instanceId, taskId, gid
+ const hash = sha(sdk.canonicalDownloadHandoffPayload(download))
+ for (const stage of ['prepare', 'commit', 'start', 'recover']) {
+ const child = fork(fileURLToPath(import.meta.url), ['--peer'], {
+ execArgv: ['--import', 'tsx'],
+ stdio: ['ignore', 'inherit', 'inherit', 'ipc', 'pipe', 'pipe'],
+ })
+ const exited = once(child, 'exit')
+ const timer = setTimeout(() => child.kill('SIGKILL'), 15000)
+ const client = sdk.fromStdio({
+ input: child.stdio[5],
+ output: child.stdio[4],
+ })
+ client.listen()
+ const nextBarrier = async () => {
+ const [message] = await Promise.race([
+ once(child, 'message'),
+ exited.then(() => {
+ throw new Error(`peer exited before ${stage}`)
+ }),
+ ])
+ if (message.error) throw new Error(message.error)
+ return message
+ }
+ try {
+ const ready = nextBarrier()
+ child.send({
+ stage,
+ dir,
+ url,
+ instanceId,
+ taskId,
+ operationId,
+ port: engine.port,
+ secret: engine.secret,
+ })
+ const init = await ready
+ assert.equal(init.checkpoint, 'ready')
+ if (instanceId) assert.equal(init.instanceId, instanceId)
+ instanceId = init.instanceId
+ const key = { instanceId, operationId }
+ const call = async (name, params) =>
+ sdk[`DownloadHandoff${name}ResultSchema`].parse(
+ await client.sendRequest(
+ methods[`DownloadHandoff${name}`],
+ params
+ )
+ )
+ if (stage === 'prepare') {
+ const prepared = await call('Prepare', { ...key, download })
+ assert.equal(prepared.state, 'prepared')
+ assert.equal(prepared.payloadHash, hash)
+ taskId = prepared.taskId
+ assert.deepEqual(
+ await call('Prepare', { ...key, download }),
+ prepared
+ )
+ await assert.rejects(
+ call('Prepare', {
+ ...key,
+ download: {
+ ...download,
+ meta: {
+ ...download.meta,
+ suggestedFilename: 'different.bin',
+ },
+ },
+ }),
+ { code: sdk.ErrorCodes.HandoffPayloadConflict }
+ )
+ await assert.rejects(
+ call('Status', { ...key, instanceId: randomUUID() }),
+ { code: sdk.ErrorCodes.HandoffInstanceChanged }
+ )
+ assert.equal(requests.length, 0)
+ evidence.checkpoints.push({
+ stage,
+ taskId,
+ sourceRequests: requests.length,
+ })
+ } else if (stage === 'commit') {
+ const prior = await call('Status', key)
+ assert.equal(prior.state, 'prepared')
+ assert.equal(prior.taskId, taskId)
+ const barrier = nextBarrier()
+ const lost = client
+ .sendRequest(methods.DownloadHandoffCommit, {
+ ...key,
+ payloadHash: hash,
+ })
+ .then(
+ () => false,
+ () => true
+ )
+ assert.equal((await barrier).checkpoint, 'commit-before-reply')
+ assert.equal(requests.length, 0)
+ child.kill('SIGKILL')
+ await exited
+ client.dispose()
+ assert.equal(await lost, true)
+ evidence.checkpoints.push({
+ stage,
+ replyLost: true,
+ sourceRequests: requests.length,
+ })
+ } else {
+ const committed = await call('Status', key)
+ assert.equal(committed.state, 'committed')
+ assert.equal(committed.taskId, taskId)
+ assert.deepEqual(
+ await call('Commit', { ...key, payloadHash: hash }),
+ committed
+ )
+ assert.deepEqual(await call('Abort', key), committed)
+ const barrier = nextBarrier()
+ child.send('activate')
+ const data = await barrier
+ assert.equal(data.checkpoint, stage)
+ if (stage === 'start') gid = data.gid
+ else {
+ assert.equal(data.gid, gid)
+ assert.equal(data.outbox, 0)
+ }
+ evidence.checkpoints.push(data)
+ }
+ } finally {
+ if (child.exitCode === null && child.signalCode === null)
+ child.kill('SIGKILL')
+ await exited
+ client.dispose()
+ clearTimeout(timer)
+ }
+ }
+ return { taskId }
+ }
+ if (process.env.MOTRIX_EXTENSION_DIR) {
+ const { confirmLocalHandoff } = await import(
+ './local-handoff-browser.mjs'
+ )
+ evidence.browser = await confirmLocalHandoff({
+ root,
+ extensionRoot: path.resolve(process.env.MOTRIX_EXTENSION_DIR),
+ origin: new URL(url).origin,
+ submit: runHandoff,
+ requestCount: () => requests.length,
+ })
+ } else await runHandoff(example)
+ const end = Date.now() + 5000
+ do {
+ const content = await readFile(path.join(dir, 'handoff.bin')).catch(() =>
+ Buffer.alloc(0)
+ )
+ if (sha(content) === sha(bytes)) {
+ evidence.sha256 = sha(content)
+ break
+ }
+ await new Promise((r) => setTimeout(r, 50))
+ } while (Date.now() < end)
+ assert.deepEqual(requests, [{ method: 'GET', usesFrozenHeader: true }])
+ assert.equal(evidence.sha256, sha(bytes))
+ evidence.requests = requests
+ evidence.status = 'passed'
+ } catch (error) {
+ evidence.status = 'failed'
+ throw error
+ } finally {
+ await engine?.kill()
+ server.closeAllConnections()
+ await new Promise((r) => server.close(r))
+ const report = path.join(dir, 'report.json')
+ await writeFile(report, `${JSON.stringify(evidence, null, 2)}\n`)
+ console.log(evidence.status, report)
+ }
+}
diff --git a/src/core/bridge/bridge-connection.ts b/src/core/bridge/bridge-connection.ts
index 9bda8076..2db69be0 100644
--- a/src/core/bridge/bridge-connection.ts
+++ b/src/core/bridge/bridge-connection.ts
@@ -1,3 +1,4 @@
+import type { ExtensionHandoffMethod } from './extension-handoff'
// Installs the vscode-jsonrpc v9 Node runtime abstraction layer (RAL) into the
// same vscode-jsonrpc instance mdxp's createMdxpConnection uses. Required before
// any MessageConnection.listen(); side-effect import, kept adjacent to the
@@ -104,6 +105,15 @@ export class BridgeConnection {
this.mdxp.onRequest(method, handler)
}
+ onRoutedRequest(
+ method:
+ | ExtensionHandoffMethod
+ | keyof import('@motrix/mdxp').MdxpRequestMap,
+ handler: (params: unknown) => Promise<unknown>
+ ): void {
+ this.mdxp.raw.onRequest(method, handler)
+ }
+
/** Register a typed notification handler. */
onNotification: MdxpConnection['onNotification'] = (name, handler) => {
this.mdxp.onNotification(name, handler)
diff --git a/src/core/bridge/extension-handoff.ts b/src/core/bridge/extension-handoff.ts
new file mode 100644
index 00000000..23fa283b
--- /dev/null
+++ b/src/core/bridge/extension-handoff.ts
@@ -0,0 +1,27 @@
+import type { ZodType } from 'zod'
+import type { MdxpSessionContext } from './mdxp-session-context'
+
+// The host supplies the schemas from its candidate SDK. The stable build
+// registers none of these operations unless the complete module is installed.
+export const extensionHandoffMethods = [
+ 'download/handoff.prepare',
+ 'download/handoff.commit',
+ 'download/handoff.status',
+ 'download/handoff.abort',
+] as const
+export type ExtensionHandoffMethod = (typeof extensionHandoffMethods)[number]
+export interface ExtensionHandoffModule {
+ capability(): {
+ version: 1
+ instanceId: string
+ maxPreparedTtlMs: number
+ acceptingNew: boolean
+ }
+ methods: Record<
+ ExtensionHandoffMethod,
+ {
+ schema: ZodType
+ handle: (params: unknown, session: MdxpSessionContext) => Promise<unknown>
+ }
+ >
+}
diff --git a/src/core/bridge/handlers/initialize-handler.ts b/src/core/bridge/handlers/initialize-handler.ts
index 3f40778a..f9f7057a 100644
--- a/src/core/bridge/handlers/initialize-handler.ts
+++ b/src/core/bridge/handlers/initialize-handler.ts
@@ -4,9 +4,11 @@ import {
type InitializeResult,
makeMdxpError,
} from '@motrix/mdxp'
+import type { ExtensionHandoffModule } from '../extension-handoff'
import type { MdxpSessionContext } from '../mdxp-session-context'
export interface InitializeHandlerDeps {
+ handoffCapability?: ExtensionHandoffModule['capability']
motrixVersion: string
runtime: 'electron' | 'server'
ffmpegAvailable: boolean | (() => Promise<boolean>)
@@ -90,6 +92,9 @@ async function buildResult(
runtime: deps.runtime,
},
capabilities: {
+ ...(deps.handoffCapability
+ ? { downloadHandoff: deps.handoffCapability() }
+ : {}),
ffmpegAvailable,
selectionKinds: ffmpegAvailable
? ['direct', 'hls', 'dash', 'mux']
diff --git a/src/core/bridge/journal-handoff-module.ts b/src/core/bridge/journal-handoff-module.ts
new file mode 100644
index 00000000..d81d315a
--- /dev/null
+++ b/src/core/bridge/journal-handoff-module.ts
@@ -0,0 +1,151 @@
+import {
+ type Activation,
+ type DownloadHandoffJournal,
+ HandoffJournalRefusal,
+ type HandoffKey,
+} from '@core/session/download-handoff-journal'
+import type { TaskWithInstances } from '@core/session/motrix-database'
+import {
+ type DownloadSubmitParams,
+ ErrorCodes,
+ makeMdxpError,
+} from '@motrix/mdxp'
+import type { ZodType } from 'zod'
+import type { ExtensionHandoffModule } from './extension-handoff'
+import type { MdxpSessionContext } from './mdxp-session-context'
+
+type Key = Pick<HandoffKey, 'instanceId' | 'operationId'>
+interface WireSdk {
+ DownloadHandoffPrepareParamsSchema: ZodType<
+ Key & { download: DownloadSubmitParams }
+ >
+ DownloadHandoffCommitParamsSchema: ZodType<Key & { payloadHash: string }>
+ DownloadHandoffStatusParamsSchema: ZodType<Key>
+ DownloadHandoffAbortParamsSchema: ZodType<Key>
+ canonicalDownloadHandoffPayload(value: unknown): string
+ ErrorCodes: { HandoffInstanceChanged: number; HandoffPayloadConflict: number }
+}
+export function journalHandoffModule(
+ sdk: WireSdk,
+ journal: DownloadHandoffJournal,
+ host: {
+ ttlMs: number
+ directory: (
+ download: DownloadSubmitParams,
+ ctx: MdxpSessionContext
+ ) => Promise<string>
+ materialize: (
+ intent: Activation,
+ ctx: MdxpSessionContext
+ ) => TaskWithInstances
+ committed: (taskId: string, ctx: MdxpSessionContext) => Promise<void>
+ }
+): ExtensionHandoffModule {
+ if (
+ !Number.isSafeInteger(host.ttlMs) ||
+ host.ttlMs < 1 ||
+ host.ttlMs > 120000
+ )
+ throw new Error('Invalid handoff preparation lifetime')
+ type Reply = ReturnType<DownloadHandoffJournal['status']>
+ function method<T extends Key>(
+ schema: ZodType<T>,
+ run: (
+ key: HandoffKey,
+ p: T,
+ ctx: MdxpSessionContext
+ ) => Reply | Promise<Reply>
+ ) {
+ return {
+ schema,
+ handle: async (value: unknown, ctx: MdxpSessionContext) => {
+ // Dispatch has already validated value against this exact schema.
+ const p = value as T
+ if (
+ !ctx.isAuthorized() ||
+ !ctx.isReady() ||
+ ctx.identity.kind !== 'extension' ||
+ !ctx.sessionKey
+ )
+ throw makeMdxpError(
+ ErrorCodes.PermissionDenied,
+ 'Paired extension required'
+ )
+ try {
+ const state = await run(
+ {
+ instanceId: p.instanceId,
+ operationId: p.operationId,
+ principal: ctx.sessionKey,
+ },
+ p,
+ ctx
+ )
+ return {
+ instanceId: p.instanceId,
+ operationId: p.operationId,
+ ...state,
+ }
+ } catch (error) {
+ if (error instanceof HandoffJournalRefusal)
+ throw makeMdxpError(
+ {
+ 'instance-changed': sdk.ErrorCodes.HandoffInstanceChanged,
+ 'payload-conflict': sdk.ErrorCodes.HandoffPayloadConflict,
+ 'not-accepting': ErrorCodes.CapabilityNotSupported,
+ }[error.reason],
+ error.message
+ )
+ throw error
+ }
+ },
+ }
+ }
+ return {
+ capability: () => ({
+ version: 1,
+ instanceId: journal.instanceId,
+ maxPreparedTtlMs: host.ttlMs,
+ acceptingNew: journal.acceptingNewOperations,
+ }),
+ methods: {
+ 'download/handoff.prepare': method(
+ sdk.DownloadHandoffPrepareParamsSchema,
+ async (key, p, ctx) => {
+ const canonical = sdk.canonicalDownloadHandoffPayload(p.download)
+ return journal.prepare(
+ key,
+ canonical,
+ () => host.directory(p.download, ctx),
+ host.ttlMs,
+ () => ctx.isAuthorized() && ctx.isReady()
+ )
+ }
+ ),
+ 'download/handoff.status': method(
+ sdk.DownloadHandoffStatusParamsSchema,
+ (key) => journal.status(key)
+ ),
+ 'download/handoff.abort': method(
+ sdk.DownloadHandoffAbortParamsSchema,
+ (key) => journal.abort(key)
+ ),
+ 'download/handoff.commit': method(
+ sdk.DownloadHandoffCommitParamsSchema,
+ async (key, p, ctx) => {
+ const state = await journal.commit(key, p.payloadHash, (intent) => {
+ if (!ctx.isAuthorized() || !ctx.isReady())
+ throw makeMdxpError(
+ ErrorCodes.PermissionDenied,
+ 'Extension no longer authorized'
+ )
+ return host.materialize(intent, ctx)
+ })
+ if (state.state === 'committed')
+ await host.committed(state.taskId, ctx)
+ return state
+ }
+ ),
+ },
+ }
+}
diff --git a/src/core/bridge/web-socket-bridge-server.ts b/src/core/bridge/web-socket-bridge-server.ts
index ad4509ca..dffd61dc 100644
--- a/src/core/bridge/web-socket-bridge-server.ts
+++ b/src/core/bridge/web-socket-bridge-server.ts
@@ -44,6 +44,10 @@ import {
transportIdentityForPrincipal,
} from './credential-store'
import type { DeviceCodeService } from './device-code-service'
+import {
+ type ExtensionHandoffModule,
+ extensionHandoffMethods,
+} from './extension-handoff'
import { createInitializeHandler } from './handlers/initialize-handler'
import {
type ReadHandlerDeps,
@@ -89,6 +93,7 @@ export interface PairRequestArgs {
}
export interface BridgeServerOptions {
+ extensionHandoff?: ExtensionHandoffModule | undefined
pairing: PairingService
registry: TrustedExtensionRegistry
motrixVersion: string
@@ -336,7 +341,10 @@ export type MethodHandlers = {
* is deliberately excluded (extensions add via `download/submit`); it stays
* reachable only over the agent-facing unary `POST /mdxp` transport.
*/
-const EXTENSION_WS_CONTROL_PLANE = [
+const EXTENSION_WS_METHODS = [
+ Methods.DownloadSubmit,
+ Methods.DownloadCancel,
+ ...extensionHandoffMethods,
Methods.DownloadDirectories,
Methods.TaskList,
Methods.TaskGet,
@@ -630,12 +638,32 @@ export class WebSocketBridgeServer {
}
},
})
+ const handoff = opts.extensionHandoff
+ if (handoff) {
+ for (const method of extensionHandoffMethods) {
+ const handler = handoff.methods[method]
+ this.dispatcher.register(method, handler.schema, (params, ctx) => {
+ if (
+ !ctx.isAuthorized() ||
+ !ctx.isReady() ||
+ ctx.identity.kind !== 'extension' ||
+ !ctx.sessionKey
+ )
+ throw makeMdxpError(
+ ErrorCodes.PermissionDenied,
+ 'Authenticated extension session required'
+ )
+ return handler.handle(params, ctx)
+ })
+ }
+ }
// `motrix/initialize` is always available; the shell registers domain
// methods (download/*) later via setHandlers().
this.dispatcher.register(
'motrix/initialize',
InitializeParamsSchema,
createInitializeHandler({
+ ...(handoff ? { handoffCapability: () => handoff.capability() } : {}),
motrixVersion: opts.motrixVersion,
runtime: opts.runtime,
ffmpegAvailable: opts.ffmpegAvailable,
@@ -1167,7 +1195,7 @@ export class WebSocketBridgeServer {
* `engine/status`) on the dispatcher, backed by the shell's managers. Call
* BEFORE start(), like setHandlers(). These methods are reachable both via
* the unary `POST /mdxp` transport (agent-facing) AND — for the methods in
- * `EXTENSION_WS_CONTROL_PLANE` — over the extension WebSocket for a paired
+ * `EXTENSION_WS_METHODS` — over the extension WebSocket for a paired
* session. `download/add` remains `POST /mdxp` only.
*/
registerReadMethods(deps: ReadHandlerDeps): void {
@@ -2531,31 +2559,14 @@ export class WebSocketBridgeServer {
authorization
) as never
)
- if (this.dispatcher.has('download/submit')) {
- conn.onRequest(
- 'download/submit',
- (params) => authorizedDispatch('download/submit', params) as never
- )
- }
- if (this.dispatcher.has('download/cancel')) {
- conn.onRequest(
- 'download/cancel',
- (params) => authorizedDispatch('download/cancel', params) as never
- )
- }
- // Control-plane over WS: a paired session may drive task management + read
- // stats/engine. Additive — handlers/schemas live on the shared dispatcher.
- const wireDispatched = (
- method: (typeof EXTENSION_WS_CONTROL_PLANE)[number]
- ) => {
- if (this.dispatcher.has(method)) {
- conn.onRequest(
- method,
- (params) => authorizedDispatch(method, params) as never
+ // All domain requests use the same authorization and tracked-dispatch gate.
+ // The dispatcher contains handoff handlers only when a host installed them.
+ for (const method of EXTENSION_WS_METHODS) {
+ if (this.dispatcher.has(method))
+ conn.onRoutedRequest(method, (params) =>
+ authorizedDispatch(method, params)
)
- }
}
- for (const method of EXTENSION_WS_CONTROL_PLANE) wireDispatched(method)
// system/ping is universal — wire it unconditionally.
conn.onRequest('system/ping', (params) => ({
sentAt: params.sentAt,
diff --git a/src/core/session/download-handoff-journal.test.ts b/src/core/session/download-handoff-journal.test.ts
new file mode 100644
index 00000000..faa2504b
--- /dev/null
+++ b/src/core/session/download-handoff-journal.test.ts
@@ -0,0 +1,257 @@
+import { createHash, randomUUID } from 'node:crypto'
+import { mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import path from 'node:path'
+import { LibsodiumSecretStore } from '@core/plugin/secret-store-libsodium'
+import { TaskInstancePhase, TaskKind } from '@shared/types/task'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { makeInstanceRow, makeTaskRow } from '../../test-utils/task-rows'
+import {
+ type Activation,
+ DownloadHandoffJournal,
+ type HandoffKey,
+} from './download-handoff-journal'
+import { MotrixDatabase } from './motrix-database'
+
+const payload =
+ '{"headers":{"Authorization":"synthetic-test-secret"},"url":"https://files.example/file"}'
+const hash = createHash('sha256').update(payload).digest('hex')
+function snapshot({ taskId, engineId, saveDir }: Activation) {
+ return {
+ task: {
+ ...makeTaskRow(taskId, TaskKind.Direct),
+ saveDir,
+ source: 'bridge' as const,
+ },
+ instances: [
+ makeInstanceRow(
+ randomUUID(),
+ taskId,
+ engineId,
+ TaskInstancePhase.HttpDownload
+ ),
+ ],
+ }
+}
+
+describe('shared Desktop and Server handoff database', () => {
+ let dir: string
+ let db: MotrixDatabase
+ let journal: DownloadHandoffJournal
+ let key: HandoffKey
+ let enabled: boolean
+ let time: number
+ async function open() {
+ db = new MotrixDatabase(path.join(dir, 'motrix.db'))
+ db.init()
+ const secrets = await LibsodiumSecretStore.create({ userDataDir: dir })
+ journal = new DownloadHandoffJournal(
+ db,
+ secrets,
+ () => enabled,
+ () => time
+ )
+ }
+ beforeEach(async () => {
+ dir = mkdtempSync(path.join(tmpdir(), 'motrix-handoff-'))
+ enabled = true
+ time = 1000
+ await open()
+ key = {
+ instanceId: journal.instanceId,
+ principal: 'extension:fixture',
+ operationId: randomUUID(),
+ }
+ })
+ afterEach(() => {
+ db.close()
+ rmSync(dir, { recursive: true, force: true })
+ })
+ it('freezes preparation across restarts and commits the task and activation exactly once while draining', async () => {
+ const first = await journal.prepare(key, payload, dir, 30000)
+ if (first.state !== 'prepared') throw new Error('expected a reservation')
+ expect(db.getAllTasks()).toHaveLength(0)
+ expect(journal.pendingActivations()).toEqual([])
+ const { sealed } = db.database
+ .prepare('SELECT sealed FROM handoff_operations')
+ .get() as { sealed: string }
+ expect(sealed).toMatch(/^box:/)
+ expect(sealed).not.toContain('synthetic-test-secret')
+ db.close()
+ time += 400
+ enabled = false
+ await open()
+ expect(
+ await journal.prepare(key, payload, path.join(dir, 'new-default'), 2500)
+ ).toEqual(first)
+ await expect(
+ journal.prepare({ ...key, operationId: randomUUID() }, payload, dir, 1000)
+ ).rejects.toThrow('disabled')
+ const next = await journal.commit(key, hash, (intent) => {
+ expect(intent.saveDir).toBe(dir)
+ expect(intent.canonicalPayload).toBe(payload)
+ return snapshot(intent)
+ })
+ expect(next).toEqual({
+ state: 'committed',
+ taskId: first.taskId,
+ payloadHash: hash,
+ })
+ db.close()
+ await open()
+ expect(journal.status(key)).toEqual(next)
+ expect(
+ await journal.commit(key, hash, () => {
+ throw Error('duplicate task')
+ })
+ ).toEqual(next)
+ expect(journal.pendingActivations()).toEqual([first.taskId])
+ expect(db.getTask(first.taskId)?.instances[0]?.gid).toMatch(
+ /^[a-f0-9]{16}$/
+ )
+ expect(journal.abort(key)).toEqual(next)
+ db.deleteTask(first.taskId)
+ expect(journal.pendingActivations()).toEqual([])
+ expect(journal.status(key)).toEqual(next)
+ })
+ it('rolls back both task and receipt when the activation write fails', async () => {
+ const prepared = await journal.prepare(key, payload, dir, 30000)
+ db.database.exec(
+ "CREATE TEMP TRIGGER interrupt_activation BEFORE INSERT ON handoff_activations BEGIN SELECT RAISE(ABORT, 'injected failure'); END"
+ )
+ await expect(journal.commit(key, hash, snapshot)).rejects.toThrow(
+ 'injected failure'
+ )
+ expect(db.getAllTasks()).toHaveLength(0)
+ expect(journal.status(key)).toEqual(prepared)
+ expect(journal.pendingActivations()).toEqual([])
+ db.database.exec('DROP TRIGGER interrupt_activation')
+ expect((await journal.commit(key, hash, snapshot)).state).toBe('committed')
+ })
+ it('preserves tombstones, hash conflicts and identity isolation across restart', async () => {
+ expect(journal.status(key)).toEqual({ state: 'not-found' })
+ expect(journal.abort(key)).toEqual({ state: 'aborted' })
+ db.close()
+ await open()
+ expect((await journal.prepare(key, payload, dir, 100)).state).toBe(
+ 'aborted'
+ )
+ const other = { ...key, principal: 'other-installation' }
+ expect((await journal.prepare(other, payload, dir, 100)).state).toBe(
+ 'prepared'
+ )
+ await expect(
+ journal.prepare(other, `${payload} `, dir, 100)
+ ).rejects.toThrow('conflict')
+ await expect(
+ journal.commit(other, '0'.repeat(64), snapshot)
+ ).rejects.toThrow('conflict')
+ expect(() => journal.abort({ ...other, instanceId: randomUUID() })).toThrow(
+ 'mismatch'
+ )
+ time += 100
+ expect((await journal.commit(other, hash, snapshot)).state).toBe('expired')
+ expect(journal.abort(other).state).toBe('expired')
+ expect(db.getAllTasks()).toHaveLength(0)
+ })
+ it('keeps a refused frozen directory inactive and rejects a reset instance', async () => {
+ const prep = await journal.prepare(key, payload, dir, 1000)
+ await expect(
+ journal.commit(key, hash, () => {
+ throw new Error('directory no longer permitted')
+ })
+ ).rejects.toThrow('no longer permitted')
+ expect(journal.status(key)).toEqual(prep)
+ expect(db.getAllTasks()).toHaveLength(0)
+ expect(journal.pendingActivations()).toHaveLength(0)
+ db.close()
+ rmSync(path.join(dir, 'motrix.db'))
+ await open()
+ expect(journal.instanceId).not.toBe(key.instanceId)
+ expect(() => journal.status(key)).toThrow('instance mismatch')
+ })
+ it('allows only one engine create when two recovery workers race', async () => {
+ const prep = await journal.prepare(key, payload, dir, 1000)
+ if (prep.state !== 'prepared') throw Error('expected reservation')
+ await journal.commit(key, hash, snapshot)
+ const other = new MotrixDatabase(path.join(dir, 'motrix.db'))
+ other.init()
+ try {
+ const second = new DownloadHandoffJournal(
+ other,
+ await LibsodiumSecretStore.create({ userDataDir: dir }),
+ () => false,
+ () => time
+ )
+ const start = vi.fn(async (intent: Activation) => intent.engineId)
+ const engine = { contains: async () => false, start }
+ const outcomes = await Promise.all([
+ journal.activate(prep.taskId, engine),
+ second.activate(prep.taskId, engine),
+ ])
+ expect(outcomes).toContain('activated')
+ expect(start).toHaveBeenCalledTimes(1)
+ expect(second.pendingActivations()).toEqual([])
+ } finally {
+ other.close()
+ }
+ })
+ it('does not evict a terminal receipt to make room for a new operation', async () => {
+ const bounded = new DownloadHandoffJournal(
+ db,
+ await LibsodiumSecretStore.create({ userDataDir: dir }),
+ () => true,
+ () => time,
+ 1
+ )
+ expect(bounded.abort(key).state).toBe('aborted')
+ const other = { ...key, operationId: randomUUID() }
+ await expect(bounded.prepare(other, payload, dir, 1000)).rejects.toThrow(
+ 'full'
+ )
+ expect(() => bounded.abort(other)).toThrow('full')
+ expect(bounded.status(other).state).toBe('not-found')
+ expect((await bounded.prepare(key, payload, dir, 1000)).state).toBe(
+ 'aborted'
+ )
+ })
+ it('fences delayed commits behind abort or expiry during async decryption', async () => {
+ await journal.prepare(key, payload, dir, 100)
+ const commit = journal.commit(key, hash, snapshot)
+ journal.abort(key)
+ expect((await commit).state).toBe('aborted')
+ const second = { ...key, operationId: randomUUID() }
+ await journal.prepare(second, payload, dir, 100)
+ const late = journal.commit(second, hash, snapshot)
+ time += 100
+ expect((await late).state).toBe('expired')
+ expect(db.getAllTasks()).toHaveLength(0)
+ })
+ it('reconciles an engine acknowledgement lost across restart without dispatching a second time', async () => {
+ const first = await journal.prepare(key, payload, dir, 100)
+ if (first.state !== 'prepared') throw Error('expected prepared')
+ await journal.commit(key, hash, snapshot)
+ const engineIds = new Set<string>()
+ const engine = {
+ contains: async (id: string) => engineIds.has(id),
+ start: vi.fn(async (intent: Activation) => {
+ engineIds.add(intent.engineId)
+ throw Error('lost engine acknowledgement')
+ }),
+ }
+ await expect(journal.activate(first.taskId, engine)).rejects.toThrow(
+ 'lost engine acknowledgement'
+ )
+ db.close()
+ await open()
+ expect(
+ await journal.activate(first.taskId, {
+ ...engine,
+ contains: async () => false,
+ })
+ ).toBe('unresolved')
+ expect(await journal.activate(first.taskId, engine)).toBe('activated')
+ expect(engine.start).toHaveBeenCalledTimes(1)
+ expect(journal.pendingActivations()).toEqual([])
+ })
+})
diff --git a/src/core/session/download-handoff-journal.ts b/src/core/session/download-handoff-journal.ts
new file mode 100644
index 00000000..a8d7a0ed
--- /dev/null
+++ b/src/core/session/download-handoff-journal.ts
@@ -0,0 +1,369 @@
+import { createHash, randomUUID } from 'node:crypto'
+import { isAbsolute } from 'node:path'
+import { newEngineTaskId, newTaskId } from '@core/lib/ids'
+import type { SecretStore } from '@core/plugin/capabilities/secret-store'
+import {
+ TaskInstancePhase,
+ TaskKind,
+ TaskStatus,
+ TaskType,
+} from '@shared/types/task'
+import type Database from 'better-sqlite3'
+import { durableSqliteWrite } from './durable-sqlite-write'
+import type { MotrixDatabase, TaskWithInstances } from './motrix-database'
+
+/** Storage failures keep their original errors. The transport adapter maps
+ * these three expected protocol decisions to its SDK's typed error codes. */
+export class HandoffJournalRefusal extends Error {
+ constructor(
+ readonly reason: 'instance-changed' | 'payload-conflict' | 'not-accepting'
+ ) {
+ super(
+ {
+ 'instance-changed': 'Handoff instance mismatch',
+ 'payload-conflict': 'Handoff payload conflict',
+ 'not-accepting': 'New handoffs disabled',
+ }[reason]
+ )
+ }
+}
+
+/** principal is derived from the authenticated installation, never the wire payload. */
+export interface HandoffKey {
+ principal: string
+ instanceId: string
+ operationId: string
+}
+type Status =
+ | { state: 'not-found' | 'aborted' | 'expired' }
+ | {
+ state: 'prepared'
+ taskId: string
+ payloadHash: string
+ expiresAt: number
+ }
+ | { state: 'committed'; taskId: string; payloadHash: string }
+
+interface Row {
+ state: 'prepared' | 'committed' | 'aborted' | 'expired'
+ task_id: string | null
+ payload_hash: string | null
+ engine_id: string | null
+ expires_at: number | null
+ save_dir: string | null
+ sealed: string | null
+}
+export interface Activation {
+ taskId: string
+ engineId: string
+ saveDir: string
+ canonicalPayload: string
+}
+const digest = (payload: string) =>
+ createHash('sha256').update(payload, 'utf8').digest('hex')
+const TABLES = ['handoff_instance', 'handoff_operations', 'handoff_activations']
+const schema = `
+ CREATE TABLE handoff_instance (singleton INTEGER PRIMARY KEY CHECK(singleton=1), instance_id TEXT NOT NULL);
+ CREATE TABLE handoff_operations (
+ principal TEXT NOT NULL, operation_id TEXT NOT NULL, state TEXT NOT NULL CHECK(state IN ('prepared','committed','expired','aborted')),
+ task_id TEXT UNIQUE, engine_id TEXT UNIQUE, payload_hash TEXT, expires_at INTEGER, save_dir TEXT, sealed TEXT,
+ PRIMARY KEY(principal,operation_id),
+ CHECK(state!='prepared' OR (task_id IS NOT NULL AND engine_id IS NOT NULL AND payload_hash IS NOT NULL AND expires_at IS NOT NULL AND save_dir IS NOT NULL AND sealed IS NOT NULL))
+ );
+ CREATE INDEX handoff_expiry ON handoff_operations(expires_at) WHERE state='prepared';
+ CREATE TABLE handoff_activations (
+ task_id TEXT PRIMARY KEY REFERENCES tasks(motrix_id) ON DELETE CASCADE,
+ engine_id TEXT NOT NULL UNIQUE, save_dir TEXT NOT NULL, sealed TEXT NOT NULL,
+ state TEXT NOT NULL CHECK(state IN ('pending','dispatching'))
+ );
+`
+function result(row?: Row): Status {
+ if (!row) return { state: 'not-found' }
+ if (
+ row.state === 'prepared' &&
+ row.task_id &&
+ row.payload_hash &&
+ row.expires_at !== null
+ )
+ return {
+ state: 'prepared',
+ taskId: row.task_id,
+ payloadHash: row.payload_hash,
+ expiresAt: row.expires_at,
+ }
+ if (row.state === 'committed' && row.task_id && row.payload_hash)
+ return {
+ state: 'committed',
+ taskId: row.task_id,
+ payloadHash: row.payload_hash,
+ }
+ if (row.state === 'aborted' || row.state === 'expired')
+ return { state: row.state }
+ throw new Error('Incomplete handoff record')
+}
+/** Opened only by hosts opting into local handoff integration. Mutating callbacks
+ * are synchronous SQLite work. No engine or source I/O runs in a transaction. */
+export class DownloadHandoffJournal {
+ readonly instanceId: string
+ private readonly db: Database.Database
+ constructor(
+ private readonly storage: MotrixDatabase,
+ private readonly secrets: SecretStore,
+ private readonly acceptingNew: () => boolean,
+ private readonly now: () => number = Date.now,
+ private readonly capacity = 100_000
+ ) {
+ const db = storage.database
+ this.db = db
+ this.instanceId = this.write(() => {
+ const tables = db
+ .prepare(
+ "SELECT name FROM sqlite_master WHERE type='table' AND name IN (?,?,?)"
+ )
+ .all(...TABLES)
+ if (tables.length === 0) {
+ db.exec(schema)
+ db.prepare('INSERT INTO handoff_instance VALUES(1,?)').run(randomUUID())
+ } else if (tables.length !== TABLES.length)
+ throw new Error('Incomplete handoff database')
+ return this.generation()
+ })
+ }
+ get acceptingNewOperations() {
+ return this.acceptingNew() && this.secrets.available()
+ }
+ private write<T>(fn: () => T) {
+ return durableSqliteWrite(this.db, fn, 'handoff', true)
+ }
+ private generation() {
+ const row = this.db
+ .prepare('SELECT instance_id FROM handoff_instance WHERE singleton=1')
+ .get() as { instance_id: string } | undefined
+ if (!row?.instance_id) throw new Error('Missing handoff instance')
+ return row.instance_id
+ }
+ private assertInstance(expected = this.instanceId) {
+ if (expected !== this.instanceId || expected !== this.generation())
+ throw new HandoffJournalRefusal('instance-changed')
+ }
+ private read(key: HandoffKey, hash?: string) {
+ this.assertInstance(key.instanceId)
+ if (!key.principal || !key.operationId)
+ throw new Error('Missing handoff key')
+ this.db
+ .prepare(
+ "UPDATE handoff_operations SET state='expired', sealed=NULL,save_dir=NULL,expires_at=NULL WHERE state='prepared' AND expires_at<=?"
+ )
+ .run(this.now())
+ const row = this.db
+ .prepare(
+ 'SELECT * FROM handoff_operations WHERE principal=? AND operation_id=?'
+ )
+ .get(key.principal, key.operationId) as Row | undefined
+ if (hash !== undefined && row?.payload_hash && row.payload_hash !== hash)
+ throw new HandoffJournalRefusal('payload-conflict')
+ return row
+ }
+ private reserveCapacity() {
+ const { n } = this.db
+ .prepare('SELECT COUNT(*) AS n FROM handoff_operations')
+ .get() as { n: number }
+ if (n >= this.capacity) throw new Error('Handoff ledger is full')
+ }
+ status(key: HandoffKey) {
+ return this.write(() => result(this.read(key)))
+ }
+ async prepare(
+ key: HandoffKey,
+ canonicalPayload: string,
+ directory: string | (() => Promise<string>),
+ ttlMs: number,
+ authorized: () => boolean = () => true
+ ) {
+ const hash = digest(canonicalPayload)
+ const previous = this.write(() => result(this.read(key, hash)))
+ if (previous.state !== 'not-found') return previous
+ if (!this.acceptingNew()) throw new HandoffJournalRefusal('not-accepting')
+ const saveDir =
+ typeof directory === 'string' ? directory : await directory()
+ if (
+ !isAbsolute(saveDir) ||
+ !Number.isSafeInteger(ttlMs) ||
+ ttlMs < 1 ||
+ ttlMs > 120000
+ )
+ throw new Error('Invalid handoff preparation')
+ const sealed = await this.secrets.encrypt(canonicalPayload)
+ return this.write(() => {
+ if (!authorized()) throw new Error('Handoff authorization changed')
+ const stored = this.read(key, hash)
+ if (stored) return result(stored)
+ if (!this.acceptingNew()) throw new HandoffJournalRefusal('not-accepting')
+ this.reserveCapacity()
+ this.db
+ .prepare(
+ "INSERT INTO handoff_operations(principal,operation_id,state,task_id,engine_id,payload_hash,expires_at,save_dir,sealed) VALUES(?,?,'prepared',?,?,?,?,?,?)"
+ )
+ .run(
+ key.principal,
+ key.operationId,
+ newTaskId(),
+ newEngineTaskId(undefined, 'handoff'),
+ hash,
+ this.now() + ttlMs,
+ saveDir,
+ sealed
+ )
+ return result(this.read(key))
+ })
+ }
+ abort(key: HandoffKey) {
+ return this.write(() => {
+ const row = this.read(key)
+ if (!row) {
+ this.reserveCapacity()
+ this.db
+ .prepare(
+ "INSERT INTO handoff_operations(principal,operation_id,state) VALUES(?,?,'aborted')"
+ )
+ .run(key.principal, key.operationId)
+ } else if (row.state === 'prepared') {
+ this.db
+ .prepare(
+ "UPDATE handoff_operations SET state='aborted',sealed=NULL,save_dir=NULL,expires_at=NULL WHERE principal=? AND operation_id=?"
+ )
+ .run(key.principal, key.operationId)
+ }
+ return result(this.read(key))
+ })
+ }
+ async commit(
+ key: HandoffKey,
+ hash: string,
+ materialize: (intent: Activation) => TaskWithInstances
+ ) {
+ const row = this.write(() => this.read(key, hash))
+ if (row?.state !== 'prepared') return result(row)
+ if (!row.sealed) throw new Error('Missing prepared payload')
+ const canonicalPayload = await this.secrets.decrypt(row.sealed)
+ if (digest(canonicalPayload) !== hash)
+ throw new Error('Stored handoff payload mismatch')
+ return this.write(() => {
+ const current = this.read(key, hash)
+ if (current?.state !== 'prepared') return result(current)
+ const {
+ task_id: taskId,
+ engine_id: engineId,
+ save_dir: saveDir,
+ sealed,
+ } = current
+ if (!taskId || !engineId || !saveDir || !sealed)
+ throw new Error('Incomplete handoff reservation')
+ // materialize must revalidate the currently permitted frozen directory.
+ const snapshot = materialize({
+ taskId,
+ engineId,
+ saveDir,
+ canonicalPayload,
+ })
+ if (
+ snapshot.task.kind !== TaskKind.Direct ||
+ snapshot.task.taskType !== TaskType.Http ||
+ snapshot.task.source !== 'bridge' ||
+ snapshot.task.aggStatus !== TaskStatus.Queued ||
+ snapshot.instances[0]?.phase !== TaskInstancePhase.HttpDownload ||
+ snapshot.instances[0]?.status !== TaskStatus.Queued ||
+ snapshot.task.motrixId !== taskId ||
+ snapshot.task.saveDir !== saveDir ||
+ snapshot.instances.length !== 1 ||
+ snapshot.instances[0]?.gid !== engineId ||
+ snapshot.instances[0]?.motrixId !== taskId
+ )
+ throw new Error('Handoff task does not match reservation')
+ this.storage.insertReservedTask(snapshot)
+ this.db
+ .prepare("INSERT INTO handoff_activations VALUES(?,?,?,?,'pending')")
+ .run(taskId, engineId, saveDir, sealed)
+ this.db
+ .prepare(
+ "UPDATE handoff_operations SET state='committed',sealed=NULL,save_dir=NULL,expires_at=NULL WHERE principal=? AND operation_id=?"
+ )
+ .run(key.principal, key.operationId)
+ return result(this.read(key))
+ })
+ }
+
+ /** Unknown dispatch outcomes remain recorded. A second worker may reconcile
+ * the reserved engine ID, but cannot issue another create for an in-flight ID. */
+ async activate(
+ taskId: string,
+ engine: {
+ contains: (id: string) => Promise<boolean>
+ start: (intent: Activation) => Promise<string>
+ }
+ ): Promise<'activated' | 'unresolved' | 'absent'> {
+ const job = this.write(() => {
+ this.assertInstance()
+ const row = this.db
+ .prepare(
+ 'SELECT a.*, o.payload_hash FROM handoff_activations a JOIN handoff_operations o USING(task_id) WHERE task_id=?'
+ )
+ .get(taskId) as
+ | {
+ engine_id: string
+ save_dir: string
+ sealed: string
+ payload_hash: string
+ state: 'pending' | 'dispatching'
+ }
+ | undefined
+ return row
+ })
+ if (!job) return 'absent'
+ const exists = await engine.contains(job.engine_id)
+ if (exists && job.state === 'pending') return 'unresolved'
+ if (!exists) {
+ if (job.state === 'dispatching') return 'unresolved'
+ const canonicalPayload = await this.secrets.decrypt(job.sealed)
+ if (digest(canonicalPayload) !== job.payload_hash)
+ throw new Error('Stored activation payload mismatch')
+ const claim = this.write(() => {
+ this.assertInstance()
+ return (
+ this.db
+ .prepare(
+ "UPDATE handoff_activations SET state='dispatching' WHERE task_id=? AND engine_id=? AND state='pending'"
+ )
+ .run(taskId, job.engine_id).changes === 1
+ )
+ })
+ if (!claim) return 'unresolved'
+ if (
+ (await engine.start({
+ taskId,
+ engineId: job.engine_id,
+ saveDir: job.save_dir,
+ canonicalPayload,
+ })) !== job.engine_id
+ )
+ throw new Error('Unexpected engine identity')
+ }
+ this.write(() => {
+ this.assertInstance()
+ this.db
+ .prepare(
+ 'DELETE FROM handoff_activations WHERE task_id=? AND engine_id=?'
+ )
+ .run(taskId, job.engine_id)
+ })
+ return 'activated'
+ }
+ pendingActivations(): string[] {
+ this.assertInstance()
+ return (
+ this.db
+ .prepare('SELECT task_id FROM handoff_activations ORDER BY rowid')
+ .all() as { task_id: string }[]
+ ).map((row) => row.task_id)
+ }
+}
diff --git a/src/core/session/durable-sqlite-write.ts b/src/core/session/durable-sqlite-write.ts
new file mode 100644
index 00000000..ba825d27
--- /dev/null
+++ b/src/core/session/durable-sqlite-write.ts
@@ -0,0 +1,28 @@
+import type Database from 'better-sqlite3'
+export function durableSqliteWrite<T>(
+ db: Database.Database,
+ run: () => T,
+ owner: string,
+ immediate = false
+): T {
+ if (db.inTransaction)
+ throw new Error(`${owner} durability requires an outermost transaction`)
+ const previous = db.pragma('synchronous', { simple: true }) as number
+ // Keep stronger caller settings; change this connection only, outside a
+ // transaction. No awaits or unrelated writes can enter this sync boundary.
+ const previousFull =
+ process.platform === 'darwin'
+ ? (db.pragma('fullfsync', { simple: true }) as number)
+ : undefined
+ try {
+ // SQLite's FULL synchronous level alone uses fsync on macOS. The WAL
+ // must reach stable storage before a mutation on a separate download disk.
+ if (previousFull === 0) db.pragma('fullfsync = ON')
+ if (previous < 2) db.pragma('synchronous = FULL')
+ const transaction = db.transaction(run)
+ return immediate ? transaction.immediate() : transaction()
+ } finally {
+ if (previous < 2) db.pragma(`synchronous = ${previous}`)
+ if (previousFull === 0) db.pragma('fullfsync = OFF')
+ }
+}
diff --git a/src/core/session/finalize-journal-repository.ts b/src/core/session/finalize-journal-repository.ts
index e879ceee..b20be7fa 100644
--- a/src/core/session/finalize-journal-repository.ts
+++ b/src/core/session/finalize-journal-repository.ts
@@ -21,6 +21,7 @@ import {
} from '@core/plugin/finalize/reserved-identity'
import type Database from 'better-sqlite3'
import { z } from 'zod'
+import { durableSqliteWrite } from './durable-sqlite-write'
import { TASK_DELETED_FINALIZE_REASON } from './finalize-journal-lifecycle'
interface RawFinalizeJournal {
@@ -326,25 +327,7 @@ export class SqliteFinalizeJournalRepository
/** Critical filesystem intents must reach the WAL before native mutation. */
private durableTransaction<T>(run: () => T): T {
- if (this.db.inTransaction)
- throw new Error('finalize durability requires an outermost transaction')
- const previous = this.db.pragma('synchronous', { simple: true }) as number
- // Keep stronger caller settings; change this connection only, outside a
- // transaction. No awaits or unrelated writes can enter this sync boundary.
- const previousFull =
- process.platform === 'darwin'
- ? (this.db.pragma('fullfsync', { simple: true }) as number)
- : undefined
- try {
- // SQLite's FULL synchronous level alone uses fsync on macOS. The WAL
- // must reach stable storage before a mutation on a separate download disk.
- if (previousFull === 0) this.db.pragma('fullfsync = ON')
- if (previous < 2) this.db.pragma('synchronous = FULL')
- return this.db.transaction(run)()
- } finally {
- if (previous < 2) this.db.pragma(`synchronous = ${previous}`)
- if (previousFull === 0) this.db.pragma('fullfsync = OFF')
- }
+ return durableSqliteWrite(this.db, run, 'finalize')
}
private requireRecord(journalId: string): FinalizeJournalRecord {
diff --git a/src/core/session/motrix-database.test.ts b/src/core/session/motrix-database.test.ts
index 3341009d..1052b783 100644
--- a/src/core/session/motrix-database.test.ts
+++ b/src/core/session/motrix-database.test.ts
@@ -8,7 +8,6 @@ import {
TaskKind,
TaskStatus,
TaskType,
- TransitionPhase,
} from '@shared/types/task'
import type {
TaskDiagnosisOccurrence,
@@ -16,6 +15,7 @@ import type {
} from '@shared/types/task-occurrence'
import Database from 'better-sqlite3'
import { describe, expect, it } from 'vitest'
+import { makeInstanceRow, makeTaskRow } from '../../test-utils/task-rows'
import {
MotrixDatabase,
type NewNotificationInput,
@@ -1726,64 +1726,3 @@ function makeDiagnosisOccurrence(
...overrides,
}
}
-
-function makeTaskRow(motrixId: string, kind: TaskKind): TaskRow {
- return {
- motrixId,
- name: motrixId,
- kind,
- taskType: kind === TaskKind.Bt ? TaskType.Bt : TaskType.Http,
- category: null,
- priority: 0,
- tags: null,
- createdAt: 1700000000,
- updatedAt: 1700000001,
- finalPath: '',
- finalName: '',
- torrentMetaPath: null,
- infoHash: null,
- totalBytes: 0,
- downloadedBytes: 0,
- sizeWhenDone: 0,
- fileCount: 0,
- isPrivate: false,
- trackers: [],
- pieceLength: 0,
- aggStatus: TaskStatus.Queued,
- finishedAt: null,
- errorMessage: null,
- errorCode: null,
- errorDetailKey: null,
- errorDetailParams: null,
- diagnosisRevision: 0,
- uploadedBytesBaseline: 0,
- source: 'user',
- sourceMeta: null,
- }
-}
-
-function makeInstanceRow(
- instanceId: string,
- motrixId: string,
- gid: string | null,
- phase: TaskInstancePhase
-): TaskInstanceRow {
- return {
- instanceId,
- motrixId,
- gid,
- phase,
- status: TaskStatus.Queued,
- progress: 0,
- totalBytes: 0,
- downloadedBytes: 0,
- uploadedBytes: 0,
- diskPath: '',
- transitionPhase: TransitionPhase.Idle,
- uris: [],
- uriHash: null,
- payload: {},
- createdAt: 1700000000,
- updatedAt: 1700000001,
- }
-}
diff --git a/src/core/session/motrix-database.ts b/src/core/session/motrix-database.ts
index 47ae0fcf..de7000a5 100644
--- a/src/core/session/motrix-database.ts
+++ b/src/core/session/motrix-database.ts
@@ -563,6 +563,17 @@ export class MotrixDatabase {
}
}
+ /** Insert a newly reserved task inside the caller's SQLite transaction.
+ * Keep the snapshot cache cold: the outer transaction can still roll back. */
+ insertReservedTask(payload: TaskWithInstances): void {
+ if (!this.db.inTransaction)
+ throw new Error('Reserved task insertion requires a transaction')
+ if (this.stmtGetTask.get(payload.task.motrixId))
+ throw new Error('Reserved task already exists')
+ this.writeRow(payload)
+ this.lastPersistedSig.delete(payload.task.motrixId)
+ }
+
saveTaskWithInstances(payload: TaskWithInstances): void {
this.db.transaction(() => {
this.writeRow(payload)
diff --git a/src/main/bridge/index.ts b/src/main/bridge/index.ts
index c1a28e92..64b2006d 100644
--- a/src/main/bridge/index.ts
+++ b/src/main/bridge/index.ts
@@ -14,6 +14,7 @@ import {
} from '@core/bridge/credential-store'
import { DeviceCodeService } from '@core/bridge/device-code-service'
import { EndpointFileWriter } from '@core/bridge/endpoint-file-writer'
+import type { ExtensionHandoffModule } from '@core/bridge/extension-handoff'
import {
createExtensionIdentityResolver,
parseDevTrustedExtensions,
@@ -410,6 +411,7 @@ export async function syncNativeMessagingManifests(args: {
}
export async function bootstrapBridge(args: {
+ extensionHandoff?: ExtensionHandoffModule
getMainWindow: () => Electron.BrowserWindow | null
motrixVersion: string
ffmpegAvailable: boolean | (() => Promise<boolean>)
@@ -700,6 +702,7 @@ export async function bootstrapBridge(args: {
}
server = new WebSocketBridgeServer({
+ extensionHandoff: args.extensionHandoff,
pairing,
registry,
motrixVersion: args.motrixVersion,
diff --git a/src/server/bridge/bootstrap.ts b/src/server/bridge/bootstrap.ts
index 4bf8e4dc..98f554be 100644
--- a/src/server/bridge/bootstrap.ts
+++ b/src/server/bridge/bootstrap.ts
@@ -10,6 +10,7 @@ import { BridgeEventBus } from '@core/bridge/bridge-event-bus'
import { BridgeOwnership } from '@core/bridge/bridge-ownership'
import { DeviceCodeService } from '@core/bridge/device-code-service'
import { EndpointFileWriter } from '@core/bridge/endpoint-file-writer'
+import type { ExtensionHandoffModule } from '@core/bridge/extension-handoff'
import { recoverExtensionPairingProjectionWriterLock } from '@core/bridge/file-extension-pairing-projection-store'
import { FilePairingStore } from '@core/bridge/file-pairing-store'
import type { ReadHandlerDeps } from '@core/bridge/handlers/read-handlers'
@@ -91,6 +92,7 @@ export interface ServerExtensionReceiver {
}
export interface ServerBridgeOptions {
+ extensionHandoff?: ExtensionHandoffModule
/** Couples NAS credential ownership and per-request account checks. The
* composition root must provide a real vendor authority before enabling it. */
nasAccounts?: NasAccountAuthority
@@ -299,6 +301,9 @@ export async function bootstrapBridgeForServer(
)
const server = new WebSocketBridgeServer({
+ ...(extensionReceiver && opts.extensionHandoff
+ ? { extensionHandoff: opts.extensionHandoff }
+ : {}),
pairing,
registry,
motrixVersion: opts.motrixVersion,
diff --git a/src/test-utils/aria2.ts b/src/test-utils/aria2.ts
index 03d7b27a..003f2d13 100644
--- a/src/test-utils/aria2.ts
+++ b/src/test-utils/aria2.ts
@@ -37,7 +37,7 @@ export interface SpawnAria2Options {
// Resolve the bundled binary path relative to the repo root.
// `src/test-utils/` sits two levels below the repo root.
-const REPO_ROOT = path.resolve(__dirname, '../..')
+const REPO_ROOT = path.resolve(import.meta.dirname, '../..')
const EXTRA_DIR = path.resolve(REPO_ROOT, 'extra')
export function bundledAria2ExtraDir(): string {
diff --git a/src/test-utils/task-rows.ts b/src/test-utils/task-rows.ts
new file mode 100644
index 00000000..a55bebe2
--- /dev/null
+++ b/src/test-utils/task-rows.ts
@@ -0,0 +1,68 @@
+import type { TaskInstanceRow, TaskRow } from '@core/session/motrix-database'
+import {
+ type TaskInstancePhase,
+ TaskKind,
+ TaskStatus,
+ TaskType,
+ TransitionPhase,
+} from '@shared/types/task'
+export function makeTaskRow(motrixId: string, kind: TaskKind): TaskRow {
+ return {
+ motrixId,
+ name: motrixId,
+ kind,
+ taskType: kind === TaskKind.Bt ? TaskType.Bt : TaskType.Http,
+ category: null,
+ priority: 0,
+ tags: null,
+ createdAt: 1700000000,
+ updatedAt: 1700000001,
+ finalPath: '',
+ finalName: '',
+ torrentMetaPath: null,
+ infoHash: null,
+ totalBytes: 0,
+ downloadedBytes: 0,
+ sizeWhenDone: 0,
+ fileCount: 0,
+ isPrivate: false,
+ trackers: [],
+ pieceLength: 0,
+ aggStatus: TaskStatus.Queued,
+ finishedAt: null,
+ errorMessage: null,
+ errorCode: null,
+ errorDetailKey: null,
+ errorDetailParams: null,
+ diagnosisRevision: 0,
+ uploadedBytesBaseline: 0,
+ source: 'user',
+ sourceMeta: null,
+ }
+}
+
+export function makeInstanceRow(
+ instanceId: string,
+ motrixId: string,
+ gid: string | null,
+ phase: TaskInstancePhase
+): TaskInstanceRow {
+ return {
+ instanceId,
+ motrixId,
+ gid,
+ phase,
+ status: TaskStatus.Queued,
+ progress: 0,
+ totalBytes: 0,
+ downloadedBytes: 0,
+ uploadedBytes: 0,
+ diskPath: '',
+ transitionPhase: TransitionPhase.Idle,
+ uris: [],
+ uriHash: null,
+ payload: {},
+ createdAt: 1700000000,
+ updatedAt: 1700000001,
+ }
+}