Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(chrome-extension): make owned tabs work on Chrome 156 (downloads, observe) (#1179)

Jakub Pilař81b443b47dc4
diff --git a/dodaios/assets/chrome-extension/background.mjs b/dodaios/assets/chrome-extension/background.mjs
index 003e50a377..04b6bdc305 100644
--- a/dodaios/assets/chrome-extension/background.mjs
+++ b/dodaios/assets/chrome-extension/background.mjs
@@ -60,7 +60,40 @@ async function attach(session) {
await cdp(session, "Page.addScriptToEvaluateOnNewDocument", {
source: "Object.defineProperty(window,'open',{value:()=>null,writable:false,configurable:false});",
});
- await cdp(session, "Page.setDownloadBehavior", {behavior: "deny"});
+}
+
+// Chrome 156 refuses Page.setDownloadBehavior to extensions as a browser-level
+// command and does not expose Browser.setDownloadBehavior to them at all. A
+// download announced by an attached owned tab is cancelled instead; a small file
+// can finish before that, so its file is removed. Keyed by URL because Chrome's
+// download items carry no tab id: every announcement is one pending claim that
+// stops exactly one download of that URL, so the user's downloads stay untouched.
+const ownedDownloads = new Map(); // url -> expiry times of pending claims
+const handledDownloads = new Set();
+const ownedDownloadWindow = 2000;
+// onCreated can fire a moment before the announcement; older items are not the tab's.
+const ownedDownloadLead = 500;
+
+function claimOwnedDownload(item) {
+ if (handledDownloads.has(item.id)) return false;
+ const now = Date.now();
+ for (const url of [item.url, item.finalUrl]) {
+ const claims = (ownedDownloads.get(url) || []).filter((until) => until > now);
+ if (!claims.length) continue;
+ claims.shift();
+ if (claims.length) ownedDownloads.set(url, claims); else ownedDownloads.delete(url);
+ handledDownloads.add(item.id);
+ return true;
+ }
+ return false;
+}
+
+async function discardDownload(id) {
+ // Every step runs on its own: a failed cancel must not leave the file on disk.
+ await chrome.downloads.cancel(id).catch(() => { /* Already finished or gone. */ });
+ const [item] = await chrome.downloads.search({id}).catch(() => []);
+ if (item?.state === "complete") await chrome.downloads.removeFile(id).catch(() => { /* File already gone. */ });
+ await chrome.downloads.erase({id}).catch(() => { /* Entry already gone. */ });
}
async function release(session, closeTab = false) {
@@ -306,6 +339,24 @@ chrome.debugger.onDetach.addListener((source) => {
}
}
});
+chrome.debugger.onEvent.addListener((source, method, params) => {
+ if (method !== "Page.downloadWillBegin") return;
+ if (![...sessions.values()].some((session) => session.tabId === source.tabId && session.attached)) return;
+ const now = Date.now();
+ for (const [url, claims] of ownedDownloads) if (claims.every((until) => until <= now)) ownedDownloads.delete(url);
+ ownedDownloads.set(params.url, [...(ownedDownloads.get(params.url) || []), now + ownedDownloadWindow]);
+ // The download item may already exist when the event arrives.
+ const startedAfter = new Date(now - ownedDownloadLead).toISOString();
+ void chrome.downloads.search({url: params.url, startedAfter, orderBy: ["-startTime"]})
+ .then((items) => {
+ const item = items.find(claimOwnedDownload);
+ return item ? discardDownload(item.id) : undefined;
+ })
+ .catch(() => { /* Search failed; onCreated still catches a download that starts later. */ });
+});
+chrome.downloads.onCreated.addListener((item) => {
+ if (claimOwnedDownload(item)) void discardDownload(item.id);
+});
chrome.tabs.onRemoved.addListener((tabId) => {
for (const session of sessions.values()) if (session.tabId === tabId) {
publish(session, {kind: "disconnected"}); void release(session);
diff --git a/dodaios/assets/chrome-extension/manifest.json b/dodaios/assets/chrome-extension/manifest.json
index cdd5c5b06d..f9f36a46fe 100644
--- a/dodaios/assets/chrome-extension/manifest.json
+++ b/dodaios/assets/chrome-extension/manifest.json
@@ -4,7 +4,7 @@
"version": "1.0.0",
"minimum_chrome_version": "120",
"description": "Connect this Chrome profile to Dodaios. Only Dodaios-created, visible tabs are controlled; logins stay in Chrome.",
- "permissions": ["debugger", "tabs", "storage", "alarms", "idle", "declarativeNetRequestWithHostAccess"],
+ "permissions": ["debugger", "downloads", "tabs", "storage", "alarms", "idle", "declarativeNetRequestWithHostAccess"],
"host_permissions": ["http://*/*", "https://*/*"],
"background": {"service_worker": "background.mjs", "type": "module"},
"action": {"default_popup": "popup.html", "default_title": "Dodaios Chrome connection"},
diff --git a/dodaios/assets/chrome-extension/page.mjs b/dodaios/assets/chrome-extension/page.mjs
index 71f780121b..3687aee4b1 100644
--- a/dodaios/assets/chrome-extension/page.mjs
+++ b/dodaios/assets/chrome-extension/page.mjs
@@ -30,7 +30,10 @@ export function inspectPage(mode, input = {}) {
if (mode === "observe") {
state.elements = [...document.querySelectorAll("a,button,input,textarea,select,[role=button],[contenteditable=true]")]
.filter((element) => visible(element) && !sensitive(element)).slice(0, 200);
- state.observation = crypto.randomUUID();
+ // crypto.randomUUID exists only in secure contexts; Chrome 156 does not treat the
+ // extension-created about:blank tab as one. getRandomValues works everywhere.
+ state.observation = typeof crypto.randomUUID === "function" ? crypto.randomUUID()
+ : [...crypto.getRandomValues(new Uint8Array(16))].map((byte) => byte.toString(16).padStart(2, "0")).join("");
// Read visible text nodes only; form values and hidden application data stay in Chrome.
const texts = [];
const walker = document.createTreeWalker(document.body || document.documentElement, NodeFilter.SHOW_TEXT);
diff --git a/tests/chrome-extension/bridge.test.mjs b/tests/chrome-extension/bridge.test.mjs
index 0f90023a90..5068880dbb 100644
--- a/tests/chrome-extension/bridge.test.mjs
+++ b/tests/chrome-extension/bridge.test.mjs
@@ -1,11 +1,16 @@
import test from "node:test";
import assert from "node:assert/strict";
import {inspectPage} from "../../dodaios/assets/chrome-extension/page.mjs";
+import {webcrypto} from "node:crypto";
const store = {}, calls = [], tabs = new Map();
let nextTab = 40, idleState = "active", onTarget = null;
let page = {url: "https://example.com/", identity: "", blocked: false, observation_id: "fresh"};
const event = () => ({addListener() {}});
+const listeners = {};
+const captured = (name) => ({addListener(listener) { listeners[name] = listener; }});
+const downloadItems = new Map();
+let failCancel = false;
const storage = {setAccessLevel: async () => {}, get: async (key) => ({[key]: store[key]}),
set: async (value) => Object.assign(store, value), remove: async (key) => { delete store[key]; }};
globalThis.chrome = {
@@ -24,6 +29,9 @@ globalThis.chrome = {
detach: async (target) => { calls.push(["detach", target.tabId]); },
sendCommand: async (target, method, args) => {
calls.push([method, target.tabId, args]);
+ // Chrome 156 refuses these to extensions; they used to break every ensure.
+ if (method === "Page.setDownloadBehavior") throw new Error("Cannot not access browser-level commands");
+ if (method.startsWith("Browser.")) throw new Error(`'${method}' wasn't found`);
if (method === "Page.getFrameTree") return {frameTree: {frame: {id: "main"}}};
if (method === "Page.createIsolatedWorld") return {executionContextId: 1};
if (method === "Runtime.evaluate") {
@@ -36,7 +44,17 @@ globalThis.chrome = {
}
if (method === "Page.captureScreenshot") return {data: "fake-jpeg"};
return {};
- }, onDetach: event(),
+ }, onDetach: event(), onEvent: captured("debugger.onEvent"),
+ },
+ downloads: {
+ onCreated: captured("downloads.onCreated"),
+ search: async (query) => [...downloadItems.values()].filter((item) => (query.id === undefined || item.id === query.id)
+ && (query.url === undefined || item.url === query.url)
+ && (query.startedAfter === undefined || item.startTime === undefined || item.startTime > query.startedAfter))
+ .sort((a, b) => String(b.startTime).localeCompare(String(a.startTime))).slice(0, query.limit),
+ cancel: async (id) => { calls.push(["downloads.cancel", id]); if (failCancel) throw new Error("cancel failed"); },
+ removeFile: async (id) => { calls.push(["downloads.removeFile", id]); },
+ erase: async (query) => { calls.push(["downloads.erase", query.id]); return [query.id]; },
},
declarativeNetRequest: {updateSessionRules: async (value) => { calls.push(["rules", value]); }},
runtime: {id: "test-extension", getURL: (path) => `chrome-extension://test-extension/${path}`, onMessage: event(), onStartup: event()},
@@ -162,3 +180,114 @@ test("pointer cleanup does not inspect the login page", () => {
assert.equal(removed, true);
delete globalThis.document;
});
+
+test("ensure attaches on Chrome 156, which refuses browser-level download commands to extensions", async () => {
+ const start = calls.length;
+ const current = await session();
+ assert.equal(calls.slice(start).some(([op]) => op.endsWith("setDownloadBehavior")), false);
+ await current.call("shutdown");
+});
+
+const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
+const downloadCalls = (start) => calls.slice(start).filter(([op]) => op.startsWith("downloads."));
+
+test("a download started by an owned tab is cancelled and erased; the user's own downloads are untouched", async () => {
+ const current = await session();
+ const start = calls.length;
+ try {
+ listeners["debugger.onEvent"]({tabId: current.tabId}, "Page.downloadWillBegin", {url: "https://example.com/owned.zip"});
+ const owned = {id: 7, url: "https://example.com/owned.zip", finalUrl: "https://example.com/owned.zip", state: "in_progress"};
+ downloadItems.set(owned.id, owned);
+ listeners["downloads.onCreated"](owned);
+ // The same file downloaded by the user in a normal tab, and an unrelated download.
+ listeners["debugger.onEvent"]({tabId: 999}, "Page.downloadWillBegin", {url: "https://example.com/user.zip"});
+ listeners["downloads.onCreated"]({id: 8, url: "https://example.com/user.zip", state: "in_progress"});
+ listeners["downloads.onCreated"]({id: 9, url: "https://example.com/other.zip", state: "in_progress"});
+ await settle(); await settle();
+ assert.deepEqual(downloadCalls(start), [["downloads.cancel", 7], ["downloads.erase", 7]]);
+ } finally { downloadItems.clear(); await current.call("shutdown"); }
+});
+
+test("an owned-tab download that already finished, or was announced after it was created, loses its file", async () => {
+ const current = await session();
+ const start = calls.length;
+ try {
+ const finished = {id: 11, url: "https://example.com/tiny.txt", finalUrl: "https://example.com/tiny.txt", state: "complete"};
+ downloadItems.set(finished.id, finished);
+ listeners["downloads.onCreated"](finished);
+ listeners["debugger.onEvent"]({tabId: current.tabId}, "Page.downloadWillBegin", {url: finished.url});
+ await settle(); await settle();
+ assert.deepEqual(downloadCalls(start), [["downloads.cancel", 11], ["downloads.removeFile", 11], ["downloads.erase", 11]]);
+ } finally { downloadItems.clear(); await current.call("shutdown"); }
+});
+
+test("downloads in manual takeover belong to the user and are not cancelled", async () => {
+ const current = await session();
+ await current.call("takeover", {enabled: true});
+ const start = calls.length;
+ listeners["debugger.onEvent"]({tabId: current.tabId}, "Page.downloadWillBegin", {url: "https://example.com/manual.pdf"});
+ listeners["downloads.onCreated"]({id: 12, url: "https://example.com/manual.pdf", state: "in_progress"});
+ await settle(); await settle();
+ assert.deepEqual(downloadCalls(start), []);
+ await current.call("shutdown");
+});
+
+test("one owned-tab announcement stops one download; a failed cancel still removes the file", async () => {
+ const current = await session();
+ const start = calls.length;
+ failCancel = true;
+ try {
+ listeners["debugger.onEvent"]({tabId: current.tabId}, "Page.downloadWillBegin", {url: "https://example.com/report.pdf"});
+ const owned = {id: 21, url: "https://example.com/report.pdf", state: "complete"};
+ downloadItems.set(owned.id, owned);
+ listeners["downloads.onCreated"](owned);
+ // The user downloads the same file right after; it is not the agent's.
+ listeners["downloads.onCreated"]({id: 22, url: "https://example.com/report.pdf", state: "in_progress"});
+ await settle(); await settle();
+ assert.deepEqual(downloadCalls(start), [["downloads.cancel", 21], ["downloads.removeFile", 21], ["downloads.erase", 21]]);
+ } finally { failCancel = false; downloadItems.clear(); await current.call("shutdown"); }
+});
+
+test("repeated owned-tab downloads of one URL are all stopped, and an older user download is not claimed", async () => {
+ const current = await session();
+ const start = calls.length;
+ try {
+ // The user started this download in another tab before the owned tab announced the same URL.
+ const older = {id: 31, url: "https://example.com/twice.zip", state: "in_progress", startTime: new Date(Date.now() - 1500).toISOString()};
+ downloadItems.set(older.id, older);
+ // Two announcements arrive before Chrome creates either download item.
+ listeners["debugger.onEvent"]({tabId: current.tabId}, "Page.downloadWillBegin", {url: "https://example.com/twice.zip"});
+ listeners["debugger.onEvent"]({tabId: current.tabId}, "Page.downloadWillBegin", {url: "https://example.com/twice.zip"});
+ await settle(); await settle();
+ for (const id of [32, 33]) {
+ const owned = {id, url: "https://example.com/twice.zip", state: "in_progress", startTime: new Date().toISOString()};
+ downloadItems.set(id, owned);
+ listeners["downloads.onCreated"](owned);
+ }
+ await settle(); await settle();
+ const stopped = downloadCalls(start).filter(([op]) => op === "downloads.cancel").map(([, id]) => id);
+ assert.deepEqual(stopped, [32, 33]);
+ } finally { downloadItems.clear(); await current.call("shutdown"); }
+});
+
+test("observe works where crypto.randomUUID is unavailable (non-secure about:blank)", () => {
+ const original = Object.getOwnPropertyDescriptor(globalThis, "crypto");
+ // Only getRandomValues, as in Chrome 156's extension-created about:blank tab.
+ Object.defineProperty(globalThis, "crypto", {configurable: true,
+ value: {getRandomValues: (bytes) => webcrypto.getRandomValues(bytes)}});
+ globalThis.location = new URL("about:blank");
+ globalThis.getComputedStyle = () => ({visibility: "visible", display: "block"});
+ globalThis.NodeFilter = {SHOW_TEXT: 4};
+ globalThis.innerWidth = 800; globalThis.innerHeight = 600;
+ globalThis.document = {title: "", querySelectorAll: () => [], querySelector: () => null,
+ body: {}, documentElement: {}, createTreeWalker: () => ({nextNode: () => null})};
+ try {
+ const first = inspectPage("observe");
+ assert.match(first.observation_id, /^[0-9a-f-]{32,36}$/);
+ assert.notEqual(inspectPage("observe").observation_id, first.observation_id);
+ } finally {
+ Object.defineProperty(globalThis, "crypto", original);
+ delete globalThis.__jarvisOwnedTab;
+ for (const key of ["document", "location", "getComputedStyle", "NodeFilter", "innerWidth", "innerHeight"]) delete globalThis[key];
+ }
+});