diff options
Diffstat (limited to 'extensions/chrome-profile-bridge/browser-extension/service_worker.js')
| -rw-r--r-- | extensions/chrome-profile-bridge/browser-extension/service_worker.js | 145 |
1 files changed, 98 insertions, 47 deletions
diff --git a/extensions/chrome-profile-bridge/browser-extension/service_worker.js b/extensions/chrome-profile-bridge/browser-extension/service_worker.js index 9ac247c..dc9f45d 100644 --- a/extensions/chrome-profile-bridge/browser-extension/service_worker.js +++ b/extensions/chrome-profile-bridge/browser-extension/service_worker.js @@ -226,36 +226,34 @@ function isPiChromeOwnedTarget(tabId, sessionKey) { return false; } -// Create a fresh automation target for `sessionKey`. If this session already has a tab group, -// create the tab inside that group's window so one Pi session keeps one Chrome tab group (Chrome -// groups cannot span windows). If it has none, give the session its own window: a window shows -// only one tab, so sessions sharing a window would hide each other's tabs, and a hidden tab gets no -// real input and blank screenshots (measured 2026-11-08). Fall back to a tab. When the tab is -// created in a pre-existing window, leave windowId unset so cleanup only closes our tab. +// The window agents' tabs go in: the user's last focused normal window, so every session's tabs +// sit together in one window (as tab groups) instead of a window each. An inactive tab still takes +// trusted input and renders screenshots (measured 2026-11-14), so sharing a window costs nothing. +// Null when no normal window is open; the caller then creates one. +async function agentWindowId() { + if (typeof chrome.windows?.getLastFocused !== "function") return null; + const win = await chrome.windows.getLastFocused({ windowTypes: ["normal"] }).catch(() => null); + if (win && typeof win.id === "number" && !win.incognito) return win.id; + const all = typeof chrome.windows.getAll === "function" ? await chrome.windows.getAll({ windowTypes: ["normal"] }).catch(() => []) : []; + const other = all.find((w) => typeof w.id === "number" && !w.incognito); + return other ? other.id : null; +} + +// Create a fresh automation target for `sessionKey`: an inactive tab in the session's group's +// window if it has a group (Chrome groups cannot span windows), else in the user's window. A new +// window only when Brave has none. When the tab goes in a pre-existing window, windowId stays unset. async function createAutomationTarget(sessionKey, groupTitle) { const existingGroup = groupTitle ? await findGroupRecordByTitle(groupTitle) : null; - if (existingGroup && typeof existingGroup.windowId === "number") { - const tab = await chrome.tabs.create({ url: "about:blank", active: false, windowId: existingGroup.windowId }); - automationTargets.set(sessionKey, { windowId: undefined, tabId: typeof tab.id === "number" ? tab.id : undefined }); + const windowId = existingGroup && typeof existingGroup.windowId === "number" ? existingGroup.windowId : await agentWindowId(); + if (windowId === null && typeof chrome.windows?.create === "function") { + const win = await chrome.windows.create({ url: "about:blank", focused: false }); + const created = win && Array.isArray(win.tabs) ? win.tabs[0] : undefined; + if (!created || typeof created.id !== "number") throw new Error("Chrome created a window without a tab"); + automationTargets.set(sessionKey, { windowId: typeof win.id === "number" ? win.id : undefined, tabId: created.id }); await persistAutomationTargets(); - return tab; + return created; } - if (chrome.windows && typeof chrome.windows.create === "function") { - try { - const win = await chrome.windows.create({ url: "about:blank", focused: false }); - const created = win && Array.isArray(win.tabs) ? win.tabs[0] : undefined; - if (created && typeof created.id === "number") { - automationTargets.set(sessionKey, { windowId: typeof win.id === "number" ? win.id : undefined, tabId: created.id }); - await persistAutomationTargets(); - return created; - } - } catch { - // Window creation can fail (policy, headless, etc.); fall back to a dedicated tab below. - } - } - // Tab fallback: the tab lives in a pre-existing (user/shared) window we did NOT create, so we - // must leave windowId unset — cleanup then closes only our tab, never the user's window. - const tab = await chrome.tabs.create({ url: "about:blank", active: false }); + const tab = await chrome.tabs.create({ url: "about:blank", active: false, ...(windowId !== null ? { windowId } : {}) }); automationTargets.set(sessionKey, { windowId: undefined, tabId: typeof tab.id === "number" ? tab.id : undefined }); await persistAutomationTargets(); return tab; @@ -442,7 +440,12 @@ async function attachDebugger(tabId) { const entry = { detachAt: Date.now() + INPUT_IDLE_DETACH_MS, pointer: { x: 120 + Math.random() * 200, y: 80 + Math.random() * 120 }, debuggee: attachedDebuggee || { tabId } }; attachedTabs.set(tabId, entry); // Page events are what tell us a page opened a dialog; without them nobody answers it. - await cdpRaw(tabId, "Page.enable", {}).catch(() => undefined); + // Agents' tabs are usually inactive, so also let the page believe it has focus: menus and pickers + // that close on blur stay open. Ends when the debugger detaches. + await Promise.all([ + cdpRaw(tabId, "Page.enable", {}).catch(() => undefined), + cdpRaw(tabId, "Emulation.setFocusEmulationEnabled", { enabled: true }).catch(() => undefined), + ]); return entry; } @@ -480,10 +483,11 @@ async function inputDebug(params) { }; } -// Chrome drops trusted CDP input to hidden pages: mouse presses and keys are silently ignored and -// mouse moves can hang waiting for a frame. A page is hidden when its tab is inactive, its window is -// minimized, or (macOS) its window became a native window-tab behind a full-screen window. Check -// before sending input so the caller gets an actionable error instead of a false success. +// A page is hidden when its tab is inactive, its window is minimized, or (macOS) its window is +// covered or on another Space. Measured 2026-11-14 in Brave: an inactive tab still takes trusted +// CDP clicks, key presses, text and mouse moves, and screenshots render it live; only mouseWheel +// hangs waiting for a frame that never comes, so chrome.scroll scrolls hidden pages by script. +// A minimized window is untested, so input there still fails up front with an actionable error. async function pageVisibilityState(tabId) { try { const evaluated = await cdp(tabId, "Runtime.evaluate", { expression: "document.visibilityState", returnByValue: true }); @@ -501,8 +505,20 @@ function hiddenTabReason(tab, win) { return "its window is covered by another window or is on another Space (Chrome treats fully covered windows as hidden)"; } +// The tab and window when trusted input to the page may be dropped (hidden in a minimized window), +// else null. +async function inputRefusingWindow(tab) { + if ((await pageVisibilityState(tab.id)) !== "hidden") return null; + const fresh = await chrome.tabs.get(tab.id).catch(() => tab); + const win = typeof chrome.windows?.get === "function" ? await chrome.windows.get(fresh?.windowId ?? tab.windowId).catch(() => null) : null; + return win?.state === "minimized" ? { fresh, win } : null; +} + async function assertTabVisibleForInput(tab, params, label) { - let state = await pageVisibilityState(tab.id); + const refusing = await inputRefusingWindow(tab); + if (!refusing) return; + const { fresh, win } = refusing; + let state = "hidden"; if (state !== "hidden") return; if (foregroundRequested(params)) { // bringToFront just ran; give Chrome a moment to report the page visible. @@ -512,11 +528,9 @@ async function assertTabVisibleForInput(tab, params, label) { } if (state !== "hidden") return; } - const fresh = await chrome.tabs.get(tab.id).catch(() => tab); - const win = typeof chrome.windows?.get === "function" ? await chrome.windows.get(fresh?.windowId ?? tab.windowId).catch(() => null) : null; const error = new Error( - `${label}: tab ${tab.id} is hidden because ${hiddenTabReason(fresh, win)}. Chrome ignores trusted input to hidden pages, so the events would be dropped. ` + - `Pass background:false for this call (or run /chrome background off) to bring the tab forward. chrome_click and chrome_fill can instead use their DOM fallback (untrusted page events).`, + `${label}: tab ${tab.id} is hidden because ${hiddenTabReason(fresh, win)}. Input to a minimized window may be dropped. ` + + `Pass background:false for this call to bring the tab forward. chrome_click and chrome_fill can instead use their DOM fallback (untrusted page events).`, ); error.hiddenTab = true; error.windowState = win?.state; @@ -1368,6 +1382,22 @@ async function chromeInputFill(params) { } } +// Runs in the page: scroll the innermost scrollable element under (x, y), else the document. +function scrollHiddenPage(x, y, dx, dy) { + const canScroll = (el) => { + const style = getComputedStyle(el); + const yOk = dy !== 0 && /(auto|scroll|overlay)/.test(style.overflowY) && el.scrollHeight > el.clientHeight; + const xOk = dx !== 0 && /(auto|scroll|overlay)/.test(style.overflowX) && el.scrollWidth > el.clientWidth; + return yOk || xOk; + }; + let el = document.elementFromPoint(x, y); + while (el && el !== document.body && el !== document.documentElement && !canScroll(el)) el = el.parentElement; + const target = el && el !== document.body && el !== document.documentElement ? el : (document.scrollingElement || document.documentElement); + const before = { x: target.scrollLeft, y: target.scrollTop }; + target.scrollBy({ left: dx, top: dy, behavior: "instant" }); + return { scrolled: target === document.scrollingElement ? "document" : (target.tagName || "").toLowerCase(), before, after: { x: target.scrollLeft, y: target.scrollTop } }; +} + async function chromeInputScroll(params) { const tab = await getTabByParams(params); await bringToFront(tab, params); @@ -1377,6 +1407,14 @@ async function chromeInputScroll(params) { const x = resolved.rect ? resolved.rect.left + Math.min(resolved.rect.width, 800) / 2 : resolved.x; const y = resolved.rect ? resolved.rect.top + Math.min(resolved.rect.height, 600) / 2 : resolved.y; const totalY = params.deltaY || 0, totalX = params.deltaX || 0; + // Chrome never answers a mouseWheel sent to a hidden page, so scroll it by script instead. + if ((await pageVisibilityState(tab.id)) === "hidden") { + const evaluated = await cdp(tab.id, "Runtime.evaluate", { + expression: `(${scrollHiddenPage.toString()})(${JSON.stringify(x)}, ${JSON.stringify(y)}, ${JSON.stringify(totalX)}, ${JSON.stringify(totalY)})`, + returnByValue: true, + }); + return { input: "script", reason: "tab is hidden (not the window's active tab), where Chrome drops scroll-wheel events", deltaX: totalX, deltaY: totalY, ...(evaluated?.result?.value || {}) }; + } // Profile mimics a trackpad flick: short ramp-up (~15% of events), then geometric decay // with a ~12% drop per event. Gives momentum tail tests something to find, and the small // tail deltas (a handful of <20px events) put IntersectionObserver thresholds in range. @@ -1627,11 +1665,12 @@ async function chromeInputUpload(params) { } // The target opens the native picker when clicked. Intercept the chooser so no OS dialog appears, -// then attach the files to the input Chrome reports. The click is trusted Chrome input when the page -// is visible; a hidden page drops trusted input, so there we call element.click() with a CDP user -// gesture instead (an untrusted event, like chrome_click's DOM fallback) unless domFallback:false. +// then attach the files to the input Chrome reports. The click is trusted Chrome input, also on an +// inactive tab; in a minimized window, where trusted input may be dropped, we call element.click() +// with a CDP user gesture instead (an untrusted event, like chrome_click's DOM fallback) unless +// domFallback:false. async function uploadViaFileChooser(tab, params, paths, objectId, info) { - const hidden = (await pageVisibilityState(tab.id)) === "hidden"; + const hidden = Boolean(await inputRefusingWindow(tab)); if (hidden && params.domFallback === false) await assertTabVisibleForInput(tab, params, "chrome.upload"); await cdp(tab.id, "Page.enable", {}); await cdp(tab.id, "Page.setInterceptFileChooserDialog", { enabled: true }); @@ -1657,7 +1696,7 @@ async function uploadViaFileChooser(tab, params, paths, objectId, info) { input: "chrome", mode: "file-chooser", trigger, - reason: trigger === "activation-click" ? "target tab is hidden; Chrome drops trusted input to hidden pages" : undefined, + reason: trigger === "activation-click" ? "target tab is hidden in a minimized window, where trusted input may be dropped" : undefined, inFrame: info.inFrame || undefined, uploaded: paths.map((path) => ({ path })), }; @@ -1856,17 +1895,25 @@ async function groupTab(tab, title, color) { if (!tab || typeof tab.id !== "number") throw new Error("No tab to group"); const groupTitle = cleanGroupTitle(title); let groupId = tab.groupId; + let createdGroup = false; if (typeof groupId !== "number" || groupId < 0) { // Some browsers omit windowId on freshly created tabs; read it back instead of guessing. const windowId = typeof tab.windowId === "number" ? tab.windowId : (await chrome.tabs.get(tab.id).catch(() => null))?.windowId; const existing = await findGroupByTitle(windowId, groupTitle); // Without createProperties.windowId Chrome creates the group in the *current* (user's) window // and moves the tab there, pulling Pi's automation tab out of its own window as a hidden tab. + createdGroup = existing === null; groupId = existing !== null ? await chrome.tabs.group({ groupId: existing, tabIds: [tab.id] }) : await chrome.tabs.group(typeof windowId === "number" ? { tabIds: [tab.id], createProperties: { windowId } } : { tabIds: [tab.id] }); } - await chrome.tabGroups.update(groupId, { title: groupTitle, color: cleanGroupColor(color), collapsed: false }); + // A new group starts collapsed to one label in the user's window, unless its tab is the one + // showing (collapsing would switch the window to another tab). Leave an existing group as the + // user set it. + const fresh = await chrome.tabs.get(tab.id).catch(() => tab); + const update = { title: groupTitle, color: cleanGroupColor(color) }; + if (createdGroup) update.collapsed = fresh?.active !== true; + await chrome.tabGroups.update(groupId, update); const grouped = await chrome.tabs.get(tab.id); return { tab: await formatTab(grouped), group: await groupRecord(groupId) }; } @@ -1898,19 +1945,20 @@ async function dispatch(action, params) { const existingGroup = await findGroupRecordByTitle(groupTitle); const createParams = { url: params.url || "about:blank", active: foregroundRequested(params) }; if (existingGroup && typeof existingGroup.windowId === "number") createParams.windowId = existingGroup.windowId; - // No group of this session yet: use the window of its automation tab if it has one, else open - // the tab in a window of its own. Never the user's focused window, where Chrome would put it. + // No group of this session yet: use the window of its automation tab if it has one, else the + // user's window. A window of its own only when Brave has no window open. let ownWindow = false; if (createParams.windowId === undefined) { const home = await resolveOwnedAutomationTarget(sessionKeyOf(params)).catch(() => null); - if (home && typeof home.windowId === "number") createParams.windowId = home.windowId; + const windowId = home && typeof home.windowId === "number" ? home.windowId : await agentWindowId(); + if (windowId !== null) createParams.windowId = windowId; else ownWindow = typeof chrome.windows?.create === "function"; } // Register the creation as in flight until the tab is tracked, so early capture (which only // runs in tracked tabs) waits for it instead of skipping the new tab's first page load. const creation = (async () => { const created = ownWindow - ? (await chrome.windows.create({ url: createParams.url, focused: false })).tabs[0] + ? (await chrome.windows.create({ url: createParams.url, focused: createParams.active })).tabs[0] : await chrome.tabs.create(createParams); await trackSessionTab(sessionKeyOf(params), created.id, true); return created; @@ -1944,7 +1992,7 @@ async function dispatch(action, params) { } case "tab.activate": { if (!foregroundRequested(params)) { - throw new Error("Tab activation is blocked by background mode. Ask the user to run /chrome background off to allow foreground work."); + throw new Error("Tab activation is blocked: the call asked for background, or the user turned background mode on (/chrome background on)."); } // Management actions never auto-create an automation target (createOwnedTarget:false): with // no explicit target they act on an owned target if one exists, else error — they must never @@ -2565,6 +2613,9 @@ function foregroundRequested(params) { async function bringToFront(tab, params) { if (!foregroundRequested(params)) return tab; await chrome.windows.update(tab.windowId, { focused: true }); + if (typeof tab.groupId === "number" && tab.groupId >= 0 && chrome.tabGroups) { + await chrome.tabGroups.update(tab.groupId, { collapsed: false }).catch(() => undefined); + } return chrome.tabs.update(tab.id, { active: true }); } |
