diff options
| author | Igor Soarez <igor@soarez.org> | 2026-11-14 09:15:15 +0000 |
|---|---|---|
| committer | Igor Soarez <igor@soarez.org> | 2026-11-14 09:15:34 +0000 |
| commit | a76fbc3b9b82038ab44c04d6379cc2d45e5cecd8 (patch) | |
| tree | 7cf7425cfbca05a99b42198f78ff3fcf1a6eb5d8 /extensions/chrome-profile-bridge/index.ts | |
| parent | e18559a1240219b977ffc7da2076c09cd96d1dad (diff) | |
tabs: one window for every agent; inactive tabs take input; background off by default
Measured in Brave on 2026-11-14: an inactive tab takes trusted CDP clicks,
key presses, text and mouse moves, and Page.captureScreenshot renders it
live. Only mouseWheel hangs, waiting for a frame. The upstream guard that
refused input to every hidden page was wrong for inactive tabs, and it is
what made a window per session look necessary.
- New sessions' tabs open inactive in the user's last focused window, in
the session's tab group; a window is created only when none is open.
- New groups start collapsed, unless their tab is the one showing, and
expand when a tab in them is brought forward. Existing groups keep the
user's setting.
- Input is refused up front only in a minimized window (untested there).
- chrome_scroll scrolls hidden pages by script instead of the wheel.
- Focus emulation on attach, so blur-sensitive menus stay open.
- Background mode is off by default. Calls still default to background;
background:false or chrome_tab activate brings a tab forward.
- Agent guidance, tool descriptions and docs say so.
Diffstat (limited to 'extensions/chrome-profile-bridge/index.ts')
| -rw-r--r-- | extensions/chrome-profile-bridge/index.ts | 54 |
1 files changed, 28 insertions, 26 deletions
diff --git a/extensions/chrome-profile-bridge/index.ts b/extensions/chrome-profile-bridge/index.ts index 97b9f33..8a5e02d 100644 --- a/extensions/chrome-profile-bridge/index.ts +++ b/extensions/chrome-profile-bridge/index.ts @@ -73,7 +73,7 @@ const DEFAULT_PORT = REMOTE_BRIDGE?.port ?? Number(process.env.PI_CHROME_BRIDGE_ const DEFAULT_TIMEOUT_MS = 30_000; const MAX_TEXT_CHARS = 30_000; const MAX_ELEMENTS = 80; -const BACKGROUND_PARAM_DESCRIPTION = "If true, avoid explicit Chrome focus/tab activation for this call. /chrome background on (default) enforces this for every call and ignores false. Ask the user to run /chrome background off to allow foreground work."; +const BACKGROUND_PARAM_DESCRIPTION = "Default true: work on the tab where it is, without changing what the user sees (an inactive tab takes clicks, typing and screenshots fine). Pass false only when you need the tab showing: it activates the tab and raises its window over what the user is doing. Refused if the user has turned background mode on with /chrome background on."; function resolveRemoteBridge(raw: string | undefined): { host: string; port: number } | undefined { const value = raw?.trim(); @@ -270,7 +270,7 @@ function describeTypeEvidence(result: unknown, typedLength: number, pressEnter: && typeof r.existingTextLengthBefore === "number" && r.existingTextLengthBefore === r.valueLengthAfter && (r.valueRedacted === true || r.valueBefore === r.valueAfter); if (unchanged) { - lines.push("\u26a0 The field value did not change: the keystrokes did not reach this field. It may not have keyboard focus (background/hidden tabs often cannot take focus); focus it with a uid/selector click, or ask the user to run /chrome background off, then verify."); + lines.push("\u26a0 The field value did not change: the keystrokes did not reach this field. It may not have keyboard focus; focus it with a uid/selector click and verify, or retry with background:false to bring the tab forward."); } else if (r.insertedAt === "caret-middle" && typedLength > 0) { lines.push("⚠ Text was spliced into the middle of existing content; chrome_type does NOT replace. Use chrome_fill (or chrome_type replace=true) to replace a field's value."); if (pressEnter) lines.push("⚠ If Enter submitted the form, it submitted the spliced value above, not just your text."); @@ -922,7 +922,8 @@ export default function (pi: ExtensionAPI): void { if (!alreadyLoaded) globalState[PI_CHROME_GLOBAL_KEY] = { version: PI_CHROME_VERSION, root: currentRoot, token: instanceToken }; const bridge = new ChromeProfileBridge(DEFAULT_HOST, DEFAULT_PORT); - let backgroundEnabled = true; + // Off by default: agents may bring a tab forward when they need to (background:false). + let backgroundEnabled = false; let chromeAuthorizedUntil: number | "indefinite" | undefined; // Restore an authorization that survived a /reload. Drop it if it already expired. const persistedAuth = globalState[PI_CHROME_AUTH_KEY]; @@ -1126,14 +1127,16 @@ export default function (pi: ExtensionAPI): void { const authorizedBridgeSend = async (action: string, params: Record<string, unknown>, timeoutMs = DEFAULT_TIMEOUT_MS, signal?: AbortSignal): Promise<unknown> => { requireChromeControlAuthorized(); - // Background on is a session policy, not a default that tool arguments can override. - // Apply it here so tab.new, chrome_launch(url), and tools without a background parameter - // cannot bypass it. Background off still permits per-call background:true. + // Background on (opt-in, /chrome background on) is a session policy that tool arguments cannot + // override. Apply it here so tab.new, chrome_launch(url), and tools without a background + // parameter cannot bypass it. Off (the default) lets each call choose. const typed = params as { background?: boolean; foreground?: boolean }; - const requestedBackground = typed.background ?? (typed.foreground !== undefined ? !typed.foreground : false); + // Unspecified means background, so nothing changes what the user sees unless an agent asks; + // tab.activate exists to bring a tab forward, so it defaults the other way. + const requestedBackground = typed.background ?? (typed.foreground !== undefined ? !typed.foreground : action !== "tab.activate"); const background = backgroundEnabled || requestedBackground; if (action === "tab.activate" && background) { - 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 user turned background mode on (/chrome background on)."); } // Scope every action to this session's dedicated automation target and tab group. const sessionKey = sessionKeyFor(sessionCtx); @@ -1273,7 +1276,7 @@ Capability model (important): - \`chrome_evaluate\` and \`chrome_snapshot\` run in MAIN world via **CDP \`Runtime.evaluate\`**, which is not subject to the page's Content-Security-Policy. They work even on strict-CSP pages (e.g. github.com, many bank/SaaS apps) that block \`'unsafe-eval'\`. \`chrome_navigate initScript\` likewise injects at document_start via CDP and bypasses CSP. \`chrome_screenshot\`, \`chrome_tab\`, and Chrome input also work under any CSP. - Input tools return structured details and support \`includeSnapshot=true\` on click/type/fill/key. Use the fresh snapshot to verify state instead of repeating blindly. If the action started a navigation, the snapshot waits (up to 5s) for the new page. - \`chrome_type\` never replaces: with a uid/selector it appends at the end of the field; without one it types at the current caret. Check its before/after report. Use \`chrome_fill\` to replace a field. -- Chrome ignores real input to hidden pages (inactive tabs, minimized windows, windows behind a macOS full-screen window). Input tools report this instead of silently doing nothing; retry with background:false only when bringing the tab forward is acceptable. +- Inactive (hidden) tabs work: clicks, typing, keys and screenshots reach them without bringing them forward, and chrome_scroll scrolls them by script. Only a minimized window refuses input; pass background:false to bring a tab forward when you need it showing. - \`chrome_cdp\` runs any raw CDP method on a tab (emulation, cookies, PDF, accessibility tree, etc.) when no dedicated chrome_* tool fits; \`chrome_cdp_targets\` diagnoses debugger/overlay conflicts, and \`chrome_clear_overlay\` closes a password manager prompt that blocks a tab (unless you are waiting for the user to use it). Usage rules: @@ -1282,11 +1285,11 @@ Usage rules: 3. \`includeSnapshot=true\` on click/type/fill/key to verify in one round trip. 4. If \`chrome_evaluate\` returns null when you expected a value, the expression evaluated to null/undefined in the page; surface the value via \`JSON.stringify\` to confirm. 5. \`chrome_navigate\` supports an optional \`initScript\` that runs at document_start in MAIN world for the next navigation (good for seeding localStorage or stubbing Date.now). -6. /chrome background on (default) is a hard policy: per-call \`background=false\` cannot override it, new tabs stay inactive, and \`chrome_tab activate\` is blocked. Ask the user to run /chrome background off when they want foreground/watch mode. With background off, per-call \`background=true\` still avoids explicit focus/tab activation. Screenshots use CDP without activating background tabs; debugger failures never fall back to tab activation. Page scripts, trusted input, native prompts, and Chrome/OS behavior can still affect focus. +6. By default every call works in the background: tabs open inactive and nothing changes what the user sees. Pass \`background: false\` on a call (or use \`chrome_tab activate\`) only when you need the tab showing, for example a page that misbehaves while hidden or something the user should watch; it activates the tab and raises its window over what the user is doing. If the user has run /chrome background on, that is refused and you must work without it. 7. If you hit a native file-picker or privileged browser prompt gate, tell the user; generic clicks/typing/CSP gates are handled by Chrome input. 8. Run /chrome doctor when in doubt about connectivity or capabilities. 9. A page can open dialogs you cannot see: alert, confirm, prompt, and the \"Leave site? Changes you made may not be saved\" prompt of a page with unsaved changes. They are dismissed for you (stay, cancel). \`chrome_navigate\` reports one by failing, and \`leaveIfAsked: true\` leaves anyway; use that only when you know nothing unsaved matters, and ask the user when unsure. If a click or key press that should have navigated did nothing, a Leave-site prompt may have stopped it: check the page, then ask the user before discarding anything. -10. Your session has its own browser window, with your tabs in your own colored tab group. Only the active tab of a window is visible, and a hidden tab gets no real input and blank screenshots, so reuse your tab (navigate it) rather than opening new ones; open a second tab only when you need two pages at once, and expect only the active one to take input. Do not open new windows unless the user asks. +10. Your tabs open in the user's Brave window, inactive, in your session's own tab group (collapsed to one label). An inactive tab takes clicks, typing and screenshots normally, so you do not need it showing. Reuse your tab (navigate it) rather than opening new ones, and close tabs you opened when you are done with them. Do not open new windows unless the user asks. 11. If a tool fails saying another extension (a password manager such as 1Password) has a prompt open on the tab, decide whether it is in your way or part of the task. If it is just in your way, call \`chrome_clear_overlay\` for the tab. If you need the user to sign in, authorize or approve something with it, leave it alone and tell the user what you are waiting for. Navigating the tab away also frees it.`; // Shared handlers, dispatched by the unified /chrome command below. @@ -1295,7 +1298,7 @@ Usage rules: const lines: string[] = [ `pi-chrome v${PI_CHROME_VERSION}`, `• Authorization: ${authSummary()}.`, - `• Background: ${backgroundEnabled ? "on (hard)" : "off (foreground/watch mode)"}.`, + `• Background: ${backgroundEnabled ? "on (hard)" : "off (agents may bring a tab forward with background:false; default)"}.`, ]; const status = bridge.status(); const roleLabel = status.remote @@ -1364,8 +1367,7 @@ Usage rules: lines.push(`• Pi hasn't opened its own tab in this session yet.`); } else if (own.visibility === "hidden") { lines.push( - `⚠ Pi's tab is hidden because ${own.hiddenReason ?? "its window is not visible"}. Chrome ignores clicks and typing in hidden tabs, so those tools will fail until it's visible.`, - ` Fix: bring Pi's window forward or uncover it, or run /chrome background off to let Pi bring it forward.`, + `⚠ Pi's tab is hidden because ${own.hiddenReason ?? "its window is not visible"}. Clicks, typing and screenshots still work there; only a minimized window refuses input.`, ); } else if (own.visibility === "visible") { lines.push(`✓ Pi's tab is visible, so clicks and typing will reach it.`); @@ -1383,7 +1385,7 @@ Usage rules: // Existing background setting is the hard policy. No args = toggle; no separate lock mode. const BACKGROUND_DESC: Record<string, string> = { on: "Hard background: pi-chrome will not explicitly focus windows or activate tabs; per-call foreground overrides and tab activation are blocked. Page/Chrome behavior can still affect focus.", - off: "Foreground/watch mode: Chrome may come forward and switch tabs. Per-call background:true still avoids explicit focus/tab activation.", + off: "Default. Calls work in the background unless an agent passes background:false to bring its tab forward.", }; const backgroundHandler = async (ctx: ExtensionContext, args: string) => { @@ -1577,8 +1579,8 @@ Usage rules: ]; } else if (path[0] === "background" && path.length === 1) { candidates = [ - { fullValue: "background on", label: "on", description: "Hard background: block explicit focus/tab activation and per-call foreground overrides. (default)" }, - { fullValue: "background off", label: "off", description: "Bring Chrome to the front so you can watch." }, + { fullValue: "background on", label: "on", description: "Hard background: block explicit focus/tab activation and per-call foreground overrides." }, + { fullValue: "background off", label: "off", description: "Let agents bring a tab forward when they ask to. (default)" }, { fullValue: "background toggle", label: "toggle", description: "Flip whichever way it's currently set." }, { fullValue: "background status", label: "status", description: "Show the current setting." }, ]; @@ -1661,7 +1663,7 @@ Usage rules: pi.registerTool({ name: "chrome_tab", label: "Chrome Tab", - description: "List, create, activate, close, group, ungroup, or inspect tabs in the user's existing Chrome profile via the companion extension. New/grouped tabs always use this session's Pi tab group, in the session's own window; prefer navigating a tab you already have to opening another, since only a window's active tab is visible. Background mode keeps new tabs inactive and blocks activate; ask the user to run /chrome background off for foreground/watch mode. activate/close/group/ungroup require a target (targetId/urlIncludes/titleIncludes); with no target they act on this session's pi-chrome automation tab if one exists, and otherwise error rather than touching the user's active tab.", + description: "List, create, activate, close, group, ungroup, or inspect tabs in the user's existing Chrome profile via the companion extension. New/grouped tabs always use this session's Pi tab group, inactive, in the user's window; prefer navigating a tab you already have to opening another. Inactive tabs take input and screenshots fine; activate only when you need the tab showing (it changes what the user sees). activate/close/group/ungroup require a target (targetId/urlIncludes/titleIncludes); with no target they act on this session's pi-chrome automation tab if one exists, and otherwise error rather than touching the user's active tab.", promptSnippet: "List/open/activate/close/group existing Chrome tabs through the companion extension.", parameters: Type.Object({ action: StringEnum(tabActionValues), @@ -1697,7 +1699,7 @@ Usage rules: name: "chrome_snapshot", label: "Chrome Snapshot", description: - "Inspect a page in the user's existing Chrome profile. Default output is a concise, agent-friendly observation with structural layout/context, stable uids, visible actions, form fields, page hints, and changes since the previous snapshot. Use mode/query/nearUid to zoom instead of dumping the whole page. Background mode (default) blocks explicit focus/tab activation even with background=false. Ask the user to run /chrome background off for foreground/watch mode.", + "Inspect a page in the user's existing Chrome profile. Default output is a concise, agent-friendly observation with structural layout/context, stable uids, visible actions, form fields, page hints, and changes since the previous snapshot. Use mode/query/nearUid to zoom instead of dumping the whole page. Works on inactive tabs without bringing them forward.", promptSnippet: "Observe the current Chrome page: concise summary, structural layout, visible actions, forms, page map, query matches, and stable uids.", parameters: Type.Object({ targetId: Type.Optional(Type.String()), @@ -1802,7 +1804,7 @@ Usage rules: name: "chrome_navigate", label: "Chrome Navigate", description: - "Navigate a Chrome tab to a URL via the companion extension. With no target, navigation goes to pi-chrome's own dedicated automation window/tab — it never replaces the user's active tab. Pass targetId/urlIncludes/titleIncludes only to act on a specific existing tab. Background mode (default) blocks explicit focus/tab activation even with background=false; /chrome background off allows foreground/watch mode. Optionally waits for load completion. Some pages ask \"Leave site? Changes you made may not be saved\" before navigating away; you cannot see that prompt, so it is answered for you: the default is to stay, and the call then fails at once saying so, with the tab unchanged and nothing lost. Retry with leaveIfAsked: true only if you know nothing unsaved matters (you just saved or submitted, or the tab is a throwaway you opened); if you are not sure, ask the user, because leaving discards unsaved work for good. leaveIfAsked applies to this one call only. Any other JavaScript dialog (alert, confirm, prompt) that appears during the navigation is dismissed and reported the same way.", + "Navigate a Chrome tab to a URL via the companion extension. With no target, navigation goes to pi-chrome's own dedicated automation window/tab — it never replaces the user's active tab. Pass targetId/urlIncludes/titleIncludes only to act on a specific existing tab. Works on inactive tabs without bringing them forward. Optionally waits for load completion. Some pages ask \"Leave site? Changes you made may not be saved\" before navigating away; you cannot see that prompt, so it is answered for you: the default is to stay, and the call then fails at once saying so, with the tab unchanged and nothing lost. Retry with leaveIfAsked: true only if you know nothing unsaved matters (you just saved or submitted, or the tab is a throwaway you opened); if you are not sure, ask the user, because leaving discards unsaved work for good. leaveIfAsked applies to this one call only. Any other JavaScript dialog (alert, confirm, prompt) that appears during the navigation is dismissed and reported the same way.", promptSnippet: "Navigate a Chrome tab in the user's existing profile; a page's \"Leave site?\" prompt makes the call fail unless leaveIfAsked is true.", parameters: Type.Object({ url: Type.String(), @@ -1827,7 +1829,7 @@ Usage rules: name: "chrome_evaluate", label: "Chrome Evaluate", description: - "Evaluate JavaScript in an existing Chrome tab through the companion extension. Runs in the page context and returns JSON-serializable values when possible. Background mode (default) blocks explicit focus/tab activation even with background=false; /chrome background off allows foreground/watch mode.", + "Evaluate JavaScript in an existing Chrome tab through the companion extension. Runs in the page context and returns JSON-serializable values when possible. Works on inactive tabs without bringing them forward.", promptSnippet: "Evaluate JavaScript in the active Chrome tab through the companion extension.", parameters: Type.Object({ expression: Type.String(), @@ -1861,7 +1863,7 @@ Usage rules: selector: Type.Optional(Type.String({ description: "CSS selector to click. Prefer uid from chrome_snapshot when available." })), x: Type.Optional(Type.Number({ description: "Viewport x coordinate if uid/selector is omitted." })), y: Type.Optional(Type.Number({ description: "Viewport y coordinate if uid/selector is omitted." })), - domFallback: Type.Optional(Type.Boolean({ description: "If true (default), fall back to DOM-dispatched click if Chrome's CDP input path is blocked (extension overlay, debugger failure, or a hidden tab that ignores trusted input)." })), + domFallback: Type.Optional(Type.Boolean({ description: "If true (default), fall back to DOM-dispatched click if Chrome's CDP input path is blocked (extension overlay, debugger failure, or a minimized window that refuses trusted input)." })), includeSnapshot: Type.Optional(Type.Boolean({ description: "If true, include a fresh chrome_snapshot result after the click." })), maxElements: Type.Optional(Type.Number({ default: MAX_ELEMENTS, description: "Max elements in the included snapshot." })), targetId: Type.Optional(Type.String()), @@ -1926,7 +1928,7 @@ Usage rules: selector: Type.Optional(Type.String({ description: "CSS selector to fill if uid is omitted." })), perCharacter: Type.Optional(Type.Boolean({ default: false, description: "Send individual key events even in contenteditables. Default: one native text insertion for contenteditables; key events for other fields." })), submit: Type.Optional(Type.Boolean({ description: "If true, press Enter after filling." })), - domFallback: Type.Optional(Type.Boolean({ description: "If true (default), fall back to DOM value-setting if Chrome's CDP input path is blocked (extension overlay, debugger failure, or a hidden tab that ignores trusted input)." })), + domFallback: Type.Optional(Type.Boolean({ description: "If true (default), fall back to DOM value-setting if Chrome's CDP input path is blocked (extension overlay, debugger failure, or a minimized window that refuses trusted input)." })), includeSnapshot: Type.Optional(Type.Boolean({ description: "If true, include a fresh chrome_snapshot result after filling." })), maxElements: Type.Optional(Type.Number({ default: MAX_ELEMENTS, description: "Max elements in the included snapshot." })), targetId: Type.Optional(Type.String()), @@ -1951,7 +1953,7 @@ Usage rules: name: "chrome_key", label: "Chrome Key", description: - "Send a keyboard key to an existing Chrome tab (Enter, Escape, Tab, Backspace, Delete, ArrowUp/Down/Left/Right, or one character). Background mode (default) blocks explicit focus/tab activation even with background=false; /chrome background off allows foreground/watch mode. Pass includeSnapshot=true to verify after the keypress.", + "Send a keyboard key to an existing Chrome tab (Enter, Escape, Tab, Backspace, Delete, ArrowUp/Down/Left/Right, or one character). Works on inactive tabs without bringing them forward. Pass includeSnapshot=true to verify after the keypress.", promptSnippet: "Press keys in Chrome through the companion extension.", parameters: Type.Object({ key: Type.String(), @@ -2069,7 +2071,7 @@ Usage rules: name: "chrome_screenshot", label: "Chrome Screenshot", description: - "Capture a screenshot of a Chrome tab via CDP and save it to disk without activating background tabs. Requires debugger access; failures never fall back to activating a tab. Background mode (default) ignores background=false; /chrome background off allows foreground/watch mode.", + "Capture a screenshot of a Chrome tab via CDP and save it to disk without activating background tabs. Requires debugger access; failures never fall back to activating a tab. Inactive tabs render fine; no need to bring them forward.", promptSnippet: "Capture Chrome screenshots and save them under .pi/chrome-screenshots by default.", parameters: Type.Object({ path: Type.Optional(Type.String({ description: "Output path. Defaults to .pi/chrome-screenshots/<timestamp>.<format>." })), @@ -2259,7 +2261,7 @@ Usage rules: name: "chrome_cdp", label: "Chrome CDP Call", description: - "Low-level escape hatch: run one Chrome DevTools Protocol (CDP) method against a tab (no target = this session's automation tab), e.g. Emulation.setDeviceMetricsOverride, Network.getCookies, DOM.getDocument, Page.printToPDF, Accessibility.getFullAXTree. Put CDP fields inside params. Nothing is filtered against a safe list: destructive methods run as given. Prefer dedicated chrome_* tools when they cover the task. Background mode blocks Page.bringToFront and Target.activateTarget, but other methods can still change what the user sees. Screenshot/binary payloads and results over 256 KiB are summarised instead of returned in full. Domain events are not streamed back; only the method's direct result is returned.", + "Low-level escape hatch: run one Chrome DevTools Protocol (CDP) method against a tab (no target = this session's automation tab), e.g. Emulation.setDeviceMetricsOverride, Network.getCookies, DOM.getDocument, Page.printToPDF, Accessibility.getFullAXTree. Put CDP fields inside params. Nothing is filtered against a safe list: destructive methods run as given. Prefer dedicated chrome_* tools when they cover the task. Page.bringToFront and Target.activateTarget are blocked unless the call passes background:false, and other methods can still change what the user sees. Screenshot/binary payloads and results over 256 KiB are summarised instead of returned in full. Domain events are not streamed back; only the method's direct result is returned.", promptSnippet: "Run a raw Chrome DevTools Protocol method against a Chrome tab (low-level escape hatch).", parameters: Type.Object({ method: Type.String({ description: "CDP method name, e.g. \"Runtime.evaluate\" or \"Emulation.setDeviceMetricsOverride\"." }), |
