From 3292fef710b5ccd57c00e1a24743785de4a21ab5 Mon Sep 17 00:00:00 2001 From: leo Date: Wed, 2 Dec 2026 16:31:08 +0900 Subject: [PATCH 1/5] =?UTF-8?q?fix(diagnostics):=20=E8=AF=B4=E6=98=8E?= =?UTF-8?q?=E8=BF=9E=E6=8E=A5=E7=8A=B6=E6=80=81=E3=80=81=E8=A1=A8=E5=8D=95?= =?UTF-8?q?=E7=A1=AE=E8=AE=A4=E5=92=8C=E6=B8=85=E7=90=86=E5=A4=B1=E8=B4=A5?= =?UTF-8?q?=E5=8E=9F=E5=9B=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 10 +- README.zh.md | 10 +- cli/src/connect.rs | 41 ++- cli/src/main.rs | 45 ++- cli/src/native/actions.rs | 118 ++++++-- cli/src/native/browser.rs | 239 ++++++++++++--- cli/src/native/clipboard_policy_tests.rs | 85 ++++++ cli/src/native/site_policy.rs | 277 ++++++++++++------ cli/src/output.rs | 35 ++- cli/src/profiles.rs | 121 +++++--- cli/tests/relay_diagnostics.rs | 101 +++++++ docs/en/permissions.html | 1 + docs/en/real-chrome.html | 39 +-- docs/en/troubleshooting.html | 1 + docs/permissions.html | 1 + docs/real-chrome.html | 36 +-- docs/troubleshooting.html | 1 + skill-data/core/SKILL.md | 2 +- skill-data/core/references/commands.md | 10 +- skill-data/core/references/connection.md | 33 ++- .../core/references/trust-boundaries.md | 4 + skill-data/real-chrome/SKILL.md | 65 ++-- 22 files changed, 953 insertions(+), 322 deletions(-) create mode 100644 cli/tests/relay_diagnostics.rs diff --git a/README.md b/README.md index 28ea310526..899881a680 100644 --- a/README.md +++ b/README.md @@ -264,7 +264,7 @@ Install the [**chrome-use** extension from the Chrome Web Store](https://chromew ```bash chrome-use extension install # register the native-messaging host (one-time) chrome-use open https://x.com/home -chrome-use status # relay, profile, extension, and session health +chrome-use status # Chrome process, native host, relay, and session health ``` On macOS/Linux, `chrome-use extension install` also registers the native host in existing custom data directories of running Chromium-family browsers started with `--user-data-dir=`. For a browser that is not running or cannot be discovered, use `chrome-use extension install --user-data-dir "/path/Chrome Data"`; `--user-data-dir=` is also accepted and the option may be repeated. Every explicit directory must already exist. The command lists written manifests and reads back their name and launcher path. This confirms registration only: reopen the side panel in that Chrome or wait for automatic reconnection. Windows uses HKCU registration and rejects this option. Discovery scans only the current user’s processes. Failures in discovered directories warn and skip that registration; default and explicit directory failures remain errors (retry with `--user-data-dir`). Successful custom registrations are recorded in `~/.chrome-use/custom-host-dirs.json` for status and uninstall even when the browser is stopped. Recording failures warn that uninstall may leave manifests behind. @@ -285,6 +285,8 @@ start because it is missing or has an unsupported executable format. Execution permission denials and errors from an already-started SQLite query remain explicit errors; locked or corrupt databases are not retried with another tool. +If the relay is offline, run `chrome-use status` and `chrome-use browsers`. Open the intended profile if Chrome is stopped. If the native host needs repair or the extension popup in that profile says **Not paired**, run `chrome-use extension install --all-profiles`, fully quit Chrome, and reopen it. If the extension is paired and the relay stays offline, reopen the popup or reload the extension at `chrome://extensions`. Retry `chrome-use connect --browser ` to verify the connection. + `extension install` is the one-time setup. `chrome-use extension connect` (alias `chrome-use reconnect`) re-attaches to an already-installed extension's relay without reinstalling anything. Chrome still shows its "chrome-use started debugging this browser" bar on attached agent tabs; `chrome-use extension connect --silent` removes it by restarting Chrome once with `--silent-debugger-extension-api` (tabs and logins are restored; it refuses when several Chrome instances are running). `--keep-banner` leaves Chrome alone, and without either flag it asks first in an interactive terminal. `chrome-use reconnect` and `extension connect --browser ` restart Chrome only with `--silent`, and never when the selected profile's relay is refusing connections. All AI sessions in a Chrome profile share one background agent window, with one tab group per session; your own window stays separate. Existing windows with verified agent ownership are reused, including fullscreen windows. Unknown ownership or failed placeholder cleanup refuses instead of creating more windows. User tabs are never moved or deleted to reclaim a window. If you open or drag your own tabs into the agent window, that window becomes yours: agent tabs already there keep working, and new agent tabs go to one fresh agent window that later sessions share. @@ -455,7 +457,7 @@ Regular Human pointer clicks now use a seeded 60–200ms settling pause after mo | `chrome-use auth login --bwu [--item ]` | Fill the current login page from Bitwarden; handles TOTP and supported passkey second factors | | `chrome-use auth login --bwu --passkey` | Sign in with a vault passkey in `--launch` mode (bwu 0.9.0+) | | `chrome-use auth login --1password [--item ]` | Fill the current login page from 1Password (username, password and TOTP; no passkeys) | -| `chrome-use status` | Relay transport, recent debugger timeouts, duplicate installs, extension version skew, and session health. With ab-connect 0.5.50+, host disconnect schedules a first retry after 1s, with repeated failures backing off to 30s. Dead-socket command/event waits fail; old replies are not replayed. Failed sends/lost replies report action_outcome_unknown with retryable: false. Check the page before repeating an interrupted write | +| `chrome-use status` | Chrome process state, native host registration, relay transport, recent debugger timeouts, duplicate installs, extension version skew, and session health. With ab-connect 0.5.50+, host disconnect schedules a first retry after 1s, with repeated failures backing off to 30s. Dead-socket command/event waits fail; old replies are not replayed. Failed sends/lost replies report action_outcome_unknown with retryable: false. Check the page before repeating an interrupted write | | `chrome-use close --forget-untracked` | Explicit recovery for stale ownership records with no tab identity. Requires two valid registry absence reads; reports ownershipDropped and does not claim those Chrome tabs were closed. Cannot be combined with a tab or --all | `set device "iPhone 13"` uses a 390 × 844 CSS viewport at 3× scale and an iOS 15 user agent. @@ -736,6 +738,8 @@ Use independent detectors to evaluate fingerprints. [Botcheck](https://botcheck. ## Permissions & safety +When a field triggers payment confirmation during a fill, the reason can identify the field attribute and the kind of payment cue it matched. Include that reason when reporting a false positive. + On your own Chrome, chrome-use checks every agent action against the site it lands on before running it. By default it asks you first on banking, brokerage, crypto exchange and government ID sites (a [maintained list](cli/src/native/sensitive_sites.json)), and before typing into payment card fields and purchases. Asking before password fields and downloads is off by default, since agents sign in and download on their own; turn it on per category. You answer in the side panel, its notification or the options page: **Allow once**, **Always allow on this site**, or **Decline**. The options page keeps the approved and blocked sites and a permission history. The gated command exits with code 3 and the agent runs `chrome-use confirm ` to wait for your choice. Turn the defaults off on the options page, with `CHROME_USE_SENSITIVE_SITES=0`, or in the `sites` block of an `--action-policy` file. Organizations can pin allowed and blocked domains, the action policy and disabled agents through Chrome enterprise policy (`chrome.storage.managed`). The check runs in the CLI, so pages see nothing new. See [Permissions & Safety](https://chrome-use.leeguoo.com/en/permissions.html). ## More in the docs @@ -825,6 +829,8 @@ Apache-2.0 `debugger_access_denied` lists browser-wide candidate extension names and IDs when available. Verify which extension injects a frame into the blocked tab before disabling it; the list does not prove the cause. +If a snapshot stays blocked, `data.extensionFrameCleanup` reports this command’s cleanup status and reason. Leave the form open. Ask the user to close the visible extension menu or hide its autofill prompt on this site, then run `snapshot -i` in the same session. + A refused dynamic-form ref now reports `code: "stale_ref"` with `retryable: false`. Refresh `snapshot -i`, then use the current dialog's ref or a unique stable CSS/semantic locator; no input is sent by the refusal. Keep verification enabled and do not replace trusted input with a DOM click. For `debugger_access_denied`, close a visible autofill menu or save-login bar first; hiding a tab may not dismiss a save-login bar. Candidate-extension lookup is best effort and never replaces the original access denial. Video publisher sources and cover review: `wechat-channels/publish` still comes from bundled OpenCLI; it was not removed. OpenCLI 1.8.8 also provides Xiaohongshu image-note publishing, not a video publisher, and its TikTok manifest has no upload/publish command. Use `site info` to check the installed command and source. The bundled WeChat and Douyin video publishers now default to a chrome-use `--cover-mode review` preflight that refuses an implicit platform cover before invoking the adapter (`code: "cover_selection_required"`, `retryable: false`). WeChat `--manual true` or `--draft true` prepares the form without automatic publication; `--cover-mode keep` explicitly accepts the upstream platform-selected cover, without claiming to preserve a cover chosen in a previous form. Douyin's existing `--cover ` remains supported; `--cover-mode upload` requires it. Unsupported cover arguments and AI/frame modes are refused rather than silently ignored. Added OpenCLI sources keep their own schemas. Local frame extraction is available only on opted-in native adapters; existing-work cover updates remain unimplemented. diff --git a/README.zh.md b/README.zh.md index 969fda1cae..cc04d2c03a 100644 --- a/README.zh.md +++ b/README.zh.md @@ -252,7 +252,7 @@ chrome-use teach replay ~/.chrome-use/teach/checkout.json --arg-env password=SHO ```bash chrome-use extension install # 注册原生消息 host(一次性) chrome-use open https://x.com/home -chrome-use status # 中继、profile、扩展与会话健康总览 +chrome-use status # 查看 Chrome 进程、原生宿主、中继和会话状态 ``` 在 macOS/Linux 上,`chrome-use extension install` 还会为正在运行、以 `--user-data-dir=` 单独启动的 Chromium 系浏览器注册本地 host,扫描到的自定义目录必须已经存在。如果浏览器尚未运行或无法被扫描到,可执行 `chrome-use extension install --user-data-dir "/path/Chrome Data"`;也接受 `--user-data-dir=`,可重复指定多个目录。显式指定的目录不存在时会报错。命令会列出写入的清单,并回读校验 host 名称和启动器路径。这只确认注册完成;之后请在该 Chrome 里重新打开侧栏,或等扩展自动重连。Windows 使用 HKCU 注册表注册,不支持此选项。 自动扫描仅限当前用户的进程;发现目录写入或校验失败时警告并跳过,可用 `--user-data-dir` 重试,默认或显式目录失败仍报错。成功写入的自定义数据目录记录在 `~/.chrome-use/custom-host-dirs.json`,供状态查询和浏览器停止后的卸载清理使用;记录失败会警告卸载可能残留清单。 @@ -269,6 +269,8 @@ macOS 先使用 PATH 中的 `sqlite3`,只有工具缺失或可执行格式不 `/usr/bin/sqlite3`。执行权限拒绝,以及 SQLite 已启动后返回的查询错误,仍会明确报错; 数据库锁定或损坏不会通过换一个工具重试。 +中继离线时,先运行 `chrome-use status` 和 `chrome-use browsers`。如果 Chrome 未运行,打开目标 profile。如果原生宿主注册有误,或该 profile 的扩展弹窗显示 **Not paired**,运行 `chrome-use extension install --all-profiles`,完全退出 Chrome,再重新打开。如果扩展已配对但中继仍离线,重新打开扩展弹窗,或在 `chrome://extensions` 重新加载扩展。用 `chrome-use connect --browser ` 确认连接。 + `extension install` 是一次性的安装步骤。`chrome-use extension connect`(别名 `chrome-use reconnect`)在扩展已装好的前提下重新连上它的中继,不重装任何东西。被 attach 的 agent 标签页上 Chrome 仍会显示「chrome-use started debugging this browser」提示条;`chrome-use extension connect --silent` 会带 `--silent-debugger-extension-api` 把 Chrome 重启一次来去掉它(标签和登录自动恢复;同时开着多个 Chrome 实例时不会重启)。`--keep-banner` 完全不碰浏览器;两个 flag 都不带时,交互终端里会先问一句。详见[静音提示条](https://chrome-use.leeguoo.com/debugger-banner-silence.html)。 AI 标签默认开在你正在用的窗口里,以后台标签打开、不抢焦点;每个会话有自己的标签组,组名前面带 ✦,一眼能和你自己的标签分开。加 `--window dedicated` 则改为同一 Chrome profile 的所有 AI 会话共用一个后台专用窗口:已有窗口只要标签归属都能确认是 AI,就会复用,全屏也不另开窗口。归属不明或空白占位页清理失败时会报错,避免继续增加窗口。不会为回收窗口而搬走或删除用户页。你在 AI 窗口里开了或拖进了自己的页面,这个窗口就归你:里面已有的 AI 标签照常工作,新的 AI 标签开到一个新的 AI 窗口,之后的会话共用它。 @@ -437,7 +439,7 @@ Agent 在你的 Chrome 里操作:你能实时看到开标签、加载、点击 | `chrome-use auth login --bwu [--item ]` | 从 Bitwarden 填写当前登录页,处理 TOTP 和支持的 passkey 两步验证 | | `chrome-use auth login --bwu --passkey` | 在 `--launch` 浏览器中用 passkey 登录(bwu 0.9.0+) | | `chrome-use auth login --1password [--item ]` | 从 1Password 填写当前登录页(用户名、密码和 TOTP;不含 passkey) | -| `chrome-use status` | 中继传输、近期 debugger 超时、重复扩展、版本偏差与会话健康总览。ab-connect 0.5.50+ 的 host 断线后首次重试定时为 1 秒,连续失败逐步退避到 30 秒。旧 socket 的命令与事件等待会结束,旧回复不重放;发送失败或回复丢失报告 action_outcome_unknown 和 retryable: false;中断的写操作须先检查页面再决定是否重复 | +| `chrome-use status` | Chrome 进程状态、原生宿主注册、中继传输、近期 debugger 超时、重复扩展、版本偏差与会话健康总览。ab-connect 0.5.50+ 的 host 断线后首次重试定时为 1 秒,连续失败逐步退避到 30 秒。旧 socket 的命令与事件等待会结束,旧回复不重放;发送失败或回复丢失报告 action_outcome_unknown 和 retryable: false;中断的写操作须先检查页面再决定是否重复 | | `chrome-use close --forget-untracked` | 显式恢复:仅放弃没有标签身份、且两次有效 Chrome registry 查询都未列出的旧归属记录。返回 ownershipDropped,不声称原来的标签已关闭。不能与单个标签或 --all 合用 | `set device "iPhone 13"` 使用 390 × 844 CSS 视口、3× 缩放和 iOS 15 用户代理。 @@ -649,6 +651,8 @@ CDP 的 IME 路径会产生 composition 事件,但 Chrome 可能将 `compositi ## 权限与安全 +填写普通输入框却收到支付确认时,可以查看确认原因。若能定位触发来源,提示会写明字段属性和匹配到的支付特征,报告误判时可直接引用。 + 驱动你自己的 Chrome 时,chrome-use 在执行每个 agent 操作前会按它落在的站点检查一次。默认情况下,在银行、券商、加密货币交易所和政府证件站点上(见[维护中的列表](cli/src/native/sensitive_sites.json)),以及在支付卡字段里输入、购买之前,会先问你。密码字段和下载默认不问(agent 经常自己登录和下载),可按类别打开。你在侧栏、通知或选项页里选择**仅允许这一次**、**始终允许此站点**或**拒绝**;选项页保存已允许和已屏蔽的站点以及权限记录。被拦下的命令以退出码 3 结束,agent 运行 `chrome-use confirm ` 等你选择。可以在选项页、用 `CHROME_USE_SENSITIVE_SITES=0`,或在 `--action-policy` 文件的 `sites` 段里关闭这些默认规则。组织可以通过 Chrome 企业策略(`chrome.storage.managed`)锁定允许和屏蔽的域名、操作策略和停用的 agent。检查在 CLI 里完成,页面看不到任何新东西。详见[权限与安全](https://chrome-use.leeguoo.com/permissions.html)。 ## 文档里还有 @@ -734,6 +738,8 @@ Apache-2.0 `debugger_access_denied` 会尽可能列出浏览器范围内的候选扩展名称和 ID。先确认哪个扩展向被阻挡的标签页注入了框架,再禁用它;候选列表不能证明原因。 +快照仍被阻挡时,`data.extensionFrameCleanup` 会说明本次是否清理、结果如何。保留当前表单,请用户关闭可见的扩展菜单,或只在这个网站隐藏填充提示,再在原会话执行 `snapshot -i`。 + 动态表单的 ref 身份核验被拒绝时,返回 `code: "stale_ref"`、`retryable: false`,不会发送输入。重新执行 `snapshot -i`,使用当前弹窗中的 ref,或唯一且稳定的 CSS/语义定位器。保留身份核验,不要改用 DOM 点击绕过真实输入。遇到 `debugger_access_denied` 时,先关闭可见的自动填充菜单或保存登录信息提示条;隐藏标签页不一定能关闭提示条。候选扩展查询失败时仍保留原始访问拒绝错误。 发布器来源与封面核对:`wechat-channels/publish` 仍由内置 OpenCLI 提供,没有被移除。OpenCLI 1.8.8 还提供小红书图文发布,但不是视频发布;其 TikTok 清单没有上传/发布命令。用 `site info` 查看当前命令及来源。内置视频号、抖音视频发布器现在默认经过 chrome-use 的 `--cover-mode review` 检查,未明确选择封面时不会调用适配器,返回 `code: "cover_selection_required"`、`retryable: false`。视频号可以用 `--manual true` 或 `--draft true` 准备表单而不自动发布;`--cover-mode keep` 明确接受上游平台选出的封面,不承诺保留之前表单里手选的封面。抖音原有的 `--cover ` 继续可用,`--cover-mode upload` 必须同时提供图片。不支持的封面参数、AI/指定帧模式会明确拒绝,不再静默忽略。额外添加的 OpenCLI 来源保留自己的参数定义。已声明接入的原生适配器支持本地截帧;修改已发布作品封面仍未实现。 diff --git a/cli/src/connect.rs b/cli/src/connect.rs index bf174171c2..f8e13d6ed0 100644 --- a/cli/src/connect.rs +++ b/cli/src/connect.rs @@ -2739,7 +2739,8 @@ fn approved_config_profiles() -> (bool, Vec<&'static str>) { } /// What the process list says about Chrome. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] pub(crate) enum ChromeProcess { Running, NotRunning, @@ -2749,6 +2750,35 @@ pub(crate) enum ChromeProcess { Unknown, } +impl ChromeProcess { + pub(crate) fn label(self) -> &'static str { + match self { + Self::Running => "running", + Self::NotRunning => "not running", + Self::Unknown => "unknown", + } + } +} + +/// A live extension can confirm a running browser even if its process is +/// hidden. On platforms without the process probe, report that uncertainty. +pub(crate) fn observed_chrome_process(relay_up: bool) -> ChromeProcess { + if relay_up { + return ChromeProcess::Running; + } + #[cfg(unix)] + { + chrome_process() + } + #[cfg(not(unix))] + { + ChromeProcess::Unknown + } +} + +/// Only the extension popup can report why it has no native connection. +pub(crate) const RELAY_PAIRING_HELP: &str = "Open the chrome-use extension popup in the intended profile. If it says Not paired, run `chrome-use extension install --all-profiles`, fully quit Chrome, then relaunch that profile. If the relay stays down, reload the extension at chrome://extensions where available, then retry."; + /// Combine what pgrep said about Chrome with whether it can see a process /// that is always running. `None` is pgrep failing to run or erroring. pub(crate) fn classify_chrome_process( @@ -3162,7 +3192,14 @@ pub(crate) fn profile_listed_active(local_state: &serde_json::Value, dir: &str) /// whether its worker is loaded. Recovery waits before requesting a window. /// `None` means not running, no extension, active, or unreadable metadata. pub(crate) fn closed_relay_profile(selector: Option<&str>) -> Option { - if chrome_process() != ChromeProcess::Running { + unlisted_profile_when_running(chrome_process(), selector) +} + +pub(crate) fn unlisted_profile_when_running( + process: ChromeProcess, + selector: Option<&str>, +) -> Option { + if process != ChromeProcess::Running { return None; } let profiles = chrome_profiles(); diff --git a/cli/src/main.rs b/cli/src/main.rs index 3eaafc5e97..8042dea15f 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -1726,7 +1726,7 @@ fn status_selected_profile( fn run_status(session: &str, json_mode: bool, browser: Option<&str>) { let selected = match browser.map(str::trim).filter(|s| !s.is_empty()) { None => None, - Some(sel) => match status_selected_profile(&profiles::load_rows(), sel) { + Some(sel) => match status_selected_profile(&profiles::load_listening_rows(), sel) { Ok(row) => Some((sel.to_string(), row)), Err(msg) => { if json_mode { @@ -1752,6 +1752,8 @@ fn run_status(session: &str, json_mode: bool, browser: Option<&str>) { (_, ws) => connect::relay_health_and_profiles_at(ws), }; let relay_up = health.transport_responsive; + let process = connect::observed_chrome_process(relay_up); + let pairing = if relay_up { "connected" } else { "unverified" }; // The selected profile's relay, probed (#910): a recorded endpoint is not // a live one. let selected_accepts = selected_ws @@ -1769,7 +1771,7 @@ fn run_status(session: &str, json_mode: bool, browser: Option<&str>) { let closed_profile = if relay_up || selected.is_some() { None } else { - connect::closed_relay_profile(None) + connect::unlisted_profile_when_running(process, None) }; if let Some(profile) = &closed_profile { warnings.push(connect::closed_relay_profile_message(profile, false)); @@ -1778,13 +1780,22 @@ fn run_status(session: &str, json_mode: bool, browser: Option<&str>) { match (selected_ws.as_deref(), selected_accepts) { (None, _) => warnings.push(profiles::not_connected_message(sel, row)), (Some(ws), Some(false)) => warnings.push(format!( - "profile {}'s relay at {ws} is not accepting connections. {}", - row.label(), - connect::REFUSED_RELAY_FIX + "profile {}'s relay at {ws} is not accepting connections.", + row.label() )), _ => {} } } + if !relay_up { + let hint = if process == connect::ChromeProcess::NotRunning { + "Start Chrome in the intended profile, then check status again." + } else if !host_installed || !host_healthy { + "Run `chrome-use extension install --all-profiles`, fully quit Chrome, then reopen the intended profile." + } else { + connect::RELAY_PAIRING_HELP + }; + warnings.push(hint.into()); + } // Printed next to the driving profile below, so it must be that profile's // version, not the last `hello` writer's (#319). With --browser, the // selected profile's own (#910). @@ -1792,6 +1803,7 @@ fn run_status(session: &str, json_mode: bool, browser: Option<&str>) { Some((_, row)) => ( row.relay_id .as_deref() + .filter(|_| relay_up) .and_then(connect::relay_ext_version_for_profile), row.relay_id .clone() @@ -1879,6 +1891,8 @@ fn run_status(session: &str, json_mode: bool, browser: Option<&str>) { "hostInstalled": host_installed, "hostHealthy": host_healthy, "hostLauncherHealthy": host_healthy, + "browserProcess": process, + "pairing": pairing, "relayUp": relay_up, "profileClosed": closed_profile.as_ref().map(|p| p.dir.clone()), "health": health, @@ -1913,8 +1927,16 @@ fn run_status(session: &str, json_mode: bool, browser: Option<&str>) { } println!("chrome-use {}", env!("CARGO_PKG_VERSION")); + println!("Chrome process: {}", process.label()); + let host_setup = if !host_installed { + "no manifest found" + } else if !host_healthy { + "launcher unavailable" + } else { + "launcher configured" + }; println!( - "Native host: live {}, installed {}", + "Native host: {host_setup}; live {}, installed {}", health .native_host_version .as_deref() @@ -1925,15 +1947,8 @@ fn run_status(session: &str, json_mode: bool, browser: Option<&str>) { println!("Selected profile (--browser {sel}): {}", row.label()); } println!( - "Extension relay: {}{}", - if relay_up { "up" } else { "down" }, - if !host_installed { - " (native host not installed)" - } else if !host_healthy { - " (native host launcher broken)" - } else { - "" - } + "Extension relay: {} (pairing: {pairing})", + if relay_up { "up" } else { "down" } ); if !health.debugger_warns() { println!(" {}", health.debugger); diff --git a/cli/src/native/actions.rs b/cli/src/native/actions.rs index f4200f7e2c..1e02aae65d 100644 --- a/cli/src/native/actions.rs +++ b/cli/src/native/actions.rs @@ -18154,6 +18154,33 @@ pub async fn execute_command_recovering(cmd: &Value, state: &mut DaemonState) -> out } +/// Report only the cleanup this command actually performed. A browser-wide +/// extension candidate does not prove which frame blocked the current tab. +fn append_frame_cleanup_status(out: &mut Value, requested: bool, receipt: Option<(&str, String)>) { + let (status, detail) = receipt.unwrap_or_else(|| { + if requested { + ( + "not_attempted", + "frame cleanup was requested but did not run on this command".into(), + ) + } else { + ("not_requested", "frame cleanup was not requested".into()) + } + }); + if out["data"].is_null() { + out["data"] = json!({}); + } + if let Some(data) = out["data"].as_object_mut() { + data.insert( + "extensionFrameCleanup".into(), + json!({"status":status,"detail":detail}), + ); + } + if let Some(Value::String(error)) = out.get_mut("error") { + error.push_str(&format!("\nFrame cleanup [{status}]: {detail}. The command still reports debugger access denied. Keep this tab open. After the user closes the extension menu or hides its prompt for this site, resume with `snapshot -i` in the same session.")); + } +} + async fn execute_command_recovering_scrubbed(cmd: &Value, state: &mut DaemonState) -> Value { // `fill --from-env`: the whole command, `--observe` included, runs with // every field treated as sensitive, and the response is scrubbed of the @@ -18161,11 +18188,35 @@ async fn execute_command_recovering_scrubbed(cmd: &Value, state: &mut DaemonStat // `auth login --bwu` carries several (username, password, code, custom // fields) in `secrets`. let secrets = command_secrets(cmd); + let requested = cmd["_clearExtensionFrames"] + .as_bool() + .unwrap_or_else(super::browser::clear_extension_frames_enabled); + let run = async { + let (mut out, receipt) = super::browser::with_frame_cleanup_receipt( + requested, + Box::pin(execute_command_recovering_inner(cmd, state)), + ) + .await; + if is_denied(&out) { + let receipt = receipt.or_else(|| { + (requested && !state.browser.as_ref().is_some_and(BrowserManager::on_relay)).then( + || { + ( + "not_applicable", + "frame cleanup requires a tab on the extension relay".to_string(), + ) + }, + ) + }); + append_frame_cleanup_status(&mut out, requested, receipt); + } + out + }; if secrets.is_empty() { - return Box::pin(execute_command_recovering_inner(cmd, state)).await; + return Box::pin(run).await; } let mut out = super::sensitive::SECRET_COMMAND - .scope(true, Box::pin(execute_command_recovering_inner(cmd, state))) + .scope(true, Box::pin(run)) .await; for secret in &secrets { super::sensitive::scrub_value(&mut out, secret); @@ -18310,7 +18361,10 @@ async fn execute_command_recovering_inner(cmd: &Value, state: &mut DaemonState) } if is_denied(&second) { if let Some(Value::String(e)) = second.get_mut("error") { - let note = no_recovery_note("the menu opened again when the command was repeated", e); + let note = no_recovery_note( + "Chrome denied debugger access again when the command was repeated", + e, + ); e.push_str(¬e); } } @@ -18349,23 +18403,19 @@ fn no_recovery_note(reason: &str, error: &str) -> String { fn no_recovery_note_for(reason: &str, manager: Option<&str>) -> String { let next = match manager { Some(name) => format!( - "Next: run the command again; if it is still blocked, ask the user to deal with \ - the frame (most likely {name}'s), then repeat it. {}", + "Ask the user to check the extension UI in this tab (possibly {name}'s). {}", super::browser::inline_menu_fix(name) ), None => format!( - "Next: run the command again; if it is still blocked and a password manager's \ - menu or save bar is visible in that tab, ask the user to close it (Escape, or a \ - click on the page outside the field), then repeat it. If nothing is visible, an \ - extension keeps a hidden frame in the page: the user turns that extension off \ - for this site. For 1Password, which does this: {}", + "If a menu or save bar is visible in that tab, ask the user to close it (Escape, or a \ + click on the page outside the field). If nothing is visible, the user can hide the \ + extension's autofill prompt for this site. For 1Password: {}", super::browser::ONE_PASSWORD_HIDE ), }; format!( - "\n(No automatic recovery: {reason}.) The tab and what was typed into it are intact: \ - do not close tabs, stop the session or relaunch Chrome over this. {next} To ask the \ - user and wait in one step: `chrome-use session handoff --wait --note \"\"` \ + "\n(No automatic recovery: {reason}.) To preserve the current form, do not close tabs, stop the session or relaunch Chrome over this. {next} To ask the \ + user and wait in one step: `chrome-use session handoff --wait --note \"Close the extension menu in this tab, then press Done.\"` \ (shown in the side panel; it returns when they press Done)." ) } @@ -26865,10 +26915,10 @@ async fn site_gate_kind( category: &str, cmd: &Value, state: &DaemonState, -) -> Result, String> { - use super::site_policy::{field_kind, field_kind_from_text, is_purchase_name}; +) -> Result, String> { + use super::site_policy::{field_kind, field_kind_from_text, is_purchase_name, SiteActionKind}; if category == "download" { - return Ok(Some("download")); + return Ok(Some(SiteActionKind::new("download"))); } if !matches!(category, "typing" | "click") { return Ok(None); @@ -26907,7 +26957,7 @@ async fn site_gate_kind( "typing" => { if action == "form_fill" { let fields = cmd.get("map").map(|m| m.to_string()).unwrap_or_default(); - return Ok(field_kind_from_text(&fields)); + return Ok(field_kind_from_text(&fields).map(SiteActionKind::new)); } if selector.is_empty() { return Ok(None); @@ -26968,15 +27018,27 @@ async fn site_gate_kind( .ok_or_else(|| unreadable("field attributes are malformed")) }) .collect::>()?; - // The exact field's DOM, accessible name and the agent's selector + // The exact field's DOM, snapshot label and the agent's selector // are judged together: a card mark anywhere wins, and a // one-time-code mark anywhere keeps an ambiguous "security code" // from reading as a card field (#846). - let mut names = vec![selector]; - if let Some(e) = entry { - names.push(e.name.as_str()); - } - Ok(field_kind(&attrs, &names)) + let label = entry.map_or(("snapshot label", ""), |entry| { + use super::element::DerivedName; + let source = match entry + .ax_identity + .as_ref() + .filter(|ax| ax.name != entry.name) + { + Some(ax) => match ax.source { + DerivedName::Context => "snapshot label derived from context", + DerivedName::OwnText => "snapshot label derived from element text", + }, + None if entry.dom_sourced => "DOM snapshot label", + None => "snapshot label", + }; + (source, entry.name.as_str()) + }); + Ok(field_kind(&attrs, selector, label)) } "click" => { let name = entry.map(|e| e.name.as_str()).unwrap_or_else(|| { @@ -26986,7 +27048,7 @@ async fn site_gate_kind( .unwrap_or(selector) .trim_matches('"') }); - Ok(is_purchase_name(name).then_some("purchase")) + Ok(is_purchase_name(name).then_some(SiteActionKind::new("purchase"))) } _ => Ok(None), } @@ -27093,7 +27155,7 @@ async fn site_gate(cmd: &Value, action: &str, id: &str, state: &mut DaemonState) Err(error) => return Some(error_response(id, &error)), } }; - match policy.decide(&host, category, kind) { + match policy.decide(&host, category, kind.map(|k| k.name)) { SiteGate::Allow => return None, SiteGate::Deny(reason) => { return Some(error_response( @@ -27105,6 +27167,10 @@ async fn site_gate(cmd: &Value, action: &str, id: &str, state: &mut DaemonState) if site_approved(&host) { return None; } + let detail = match (reason, kind.and_then(|k| k.payment_match)) { + ("payment_input", Some(m)) => format!("{detail} ({} in {})", m.rule, m.source), + _ => detail, + }; ask = Some((host, reason, detail, category.to_string())); } } @@ -28320,7 +28386,7 @@ mod tests { the user's own tabs", &error, ); - assert!(note.contains("most likely 1Password's"), "{note}"); + assert!(note.contains("possibly 1Password's"), "{note}"); assert!(note.contains("Hide on this page"), "{note}"); assert!(!note.contains("press Escape"), "{note}"); assert!(!note.contains("closes it with"), "{note}"); diff --git a/cli/src/native/browser.rs b/cli/src/native/browser.rs index 27a6ccc6fb..3cd894b177 100644 --- a/cli/src/native/browser.rs +++ b/cli/src/native/browser.rs @@ -2132,8 +2132,7 @@ fn foreign_frame_hint_with(error: &str, name_of: impl Fn(&str) -> Option only after a protocol read succeeds. Some menus or save-login bars remain blocked, \ including under stealth mode; close that UI manually if needed. `press Escape` uses \ the same blocked debugger and may also fail. `get url` and `tab inspect` still read \ - browser metadata; an explicit `open ` can leave the blocked page. Fill fields with \ - `fill` (one write) rather than `type --key-events`. {fix}" + browser metadata. Keep the form in its current tab. {fix}" ) } @@ -2177,9 +2176,7 @@ fn blocking_inline_menu_manager_with( /// manager cannot be told apart. pub(crate) const ONE_PASSWORD_HIDE: &str = "The user can right-click the page, choose \ \"1Password - Password Manager\" → \"Hide on this page\" (undone in 1Password's Settings → \ - Autofill & save → Hidden pages), then run the command again. Without the user, on a tab \ - this session opened: run it again with --clear-extension-frames (ab-connect 0.5.108+), which \ - removes 1Password's frame from that page."; + Autofill & save → Hidden pages), then resume in the same tab."; /// What the user can do about `name`'s frame blocking a tab. Bitwarden's /// frame is its inline menu, which is visible and closes on Escape. @@ -2194,8 +2191,7 @@ pub(crate) fn inline_menu_fix(name: &str) -> String { "1Password" => format!( "If the frame is 1Password's: 1Password can keep its frame in the page after a \ field was focused with nothing shown, so there may be no menu to close and Escape \ - does not help. {ONE_PASSWORD_HIDE} Reloading the tab also drops the frame, but \ - loses what was typed into the form." + does not help. {ONE_PASSWORD_HIDE}" ), other => format!( "If {other}'s menu or save bar is visible in that tab, the user closes it; if \ @@ -3703,19 +3699,51 @@ pub fn is_valid_label(s: &str) -> bool { /// Off by default: that extension's widget is gone from the page until it /// adds it again. pub fn clear_extension_frames_enabled() -> bool { - std::env::var("AGENT_BROWSER_CLEAR_EXTENSION_FRAMES") - .is_ok_and(|v| matches!(v.trim(), "1" | "true" | "on" | "yes")) + FRAME_CLEANUP + .try_with(|(requested, _)| *requested) + .unwrap_or_else(|_| { + std::env::var("AGENT_BROWSER_CLEAR_EXTENSION_FRAMES") + .is_ok_and(|v| matches!(v.trim(), "1" | "true" | "on" | "yes")) + }) +} + +pub(super) type FrameCleanupReceipt = (&'static str, String); + +tokio::task_local! { + static FRAME_CLEANUP: (bool, std::cell::RefCell>); +} + +/// Run a command with its own opt-in and capture any cleanup result, including +/// cleanup inside an internal retry. Commands cannot inherit another's receipt. +pub(super) async fn with_frame_cleanup_receipt>( + requested: bool, + run: F, +) -> (Value, Option) { + FRAME_CLEANUP + .scope((requested, Default::default()), async { + let out = run.await; + (out, FRAME_CLEANUP.with(|(_, receipt)| receipt.take())) + }) + .await +} + +fn record_frame_cleanup(status: &'static str, detail: &str) { + let _ = FRAME_CLEANUP.try_with(|(_, receipt)| { + *receipt.borrow_mut() = Some((status, detail.to_string())); + }); } /// The note for what `ABExt.clearExtensionFrames` removed; an error when it /// removed nothing. fn extension_frames_note(out: &Value) -> Result { - let removed = out["removed"].as_array().cloned().unwrap_or_default(); + let removed = out["removed"] + .as_array() + .ok_or("the extension did not report which frames were removed")?; if removed.is_empty() { return Err("no other extension's frame was found in the tab".to_string()); } let mut what: Vec = Vec::new(); - for r in &removed { + for r in removed { let host = r["host"].as_str().unwrap_or(""); let ext = r["extension"].as_str().unwrap_or(""); let name = if host.starts_with("com-1password") { @@ -3730,8 +3758,7 @@ fn extension_frames_note(out: &Value) -> Result { } } Ok(format!( - "removed {} frame(s) another extension kept in this tab ({}); it shows its widget on \ - this page again after a reload or on the next page (--clear-extension-frames)", + "removed {} frame(s) another extension kept in this tab ({})", removed.len(), what.join(", ") )) @@ -7871,24 +7898,21 @@ impl BrowserManager { let mut cleared: Option = None; if clear_extension_frames_enabled() { match self.clear_extension_frames().await { - Ok(note) if !self.pinned_tab_blocked().await => return Ok(Some(note)), - Ok(note) => cleared = Some(format!("{note}, but the tab is still blocked")), - Err(e) => cleared = Some(format!("--clear-extension-frames: {e}")), + Ok(note) => match self.confirm_frame_cleanup(¬e).await { + Ok(()) => return Ok(Some(note)), + Err((true, detail)) => cleared = Some(detail), + Err((false, detail)) => return Err(detail), + }, + Err(e) => cleared = Some(e), } } let out = self.cycle_pinned_tab_visibility_menus(blur_focused).await; match (out, cleared) { (Err(e), Some(c)) => Err(format!("{e}; {c}")), - // Frames went and then a menu closed: say both. - (Ok(note), Some(c)) if !c.starts_with("--clear-extension-frames:") => { - let removed = c - .trim_end_matches(", but the tab is still blocked") - .to_string(); - Ok(Some(match note { - Some(n) => format!("{removed}; {n}"), - None => removed, - })) - } + (Ok(note), Some(detail)) => Ok(Some(match note { + Some(note) => format!("{detail}; {note}"), + None => detail, + })), (out, _) => out, } } @@ -7897,28 +7921,64 @@ impl BrowserManager { /// answers the debugger again. pub async fn clear_extension_frames_unblocking(&self) -> Result { let note = self.clear_extension_frames().await?; - if self.pinned_tab_blocked().await { - return Err(format!("{note}, but the tab is still blocked")); - } + self.confirm_frame_cleanup(¬e) + .await + .map_err(|(_, detail)| detail)?; Ok(note) } + /// Keep a missing or unreadable frame-tree reply distinct from an explicit + /// access denial. Neither confirms that cleanup restored debugger access. + async fn confirm_frame_cleanup(&self, note: &str) -> Result<(), (bool, String)> { + match self.pinned_tab_debugger_access().await { + Ok(()) => { + record_frame_cleanup( + "removed", + &format!("{note}; Chrome accepted a frame-tree read"), + ); + Ok(()) + } + Err(error) => { + let denied = is_debugger_access_denied(&error); + let detail = format!("{note}; frame-tree read failed: {error}"); + record_frame_cleanup( + if denied { + "still_blocked" + } else { + "unconfirmed" + }, + &detail, + ); + Err((denied, detail)) + } + } + } + /// Remove the frames other extensions keep in the pinned tab, through /// ab-connect (`ABExt.clearExtensionFrames`, 0.5.108+). Only a tab this /// session created. The note names what went. async fn clear_extension_frames(&self) -> Result { + let not_applicable = |detail: &str| { + record_frame_cleanup("not_applicable", detail); + detail.to_string() + }; if !self.on_relay() { - return Err("not on the extension relay".to_string()); + return Err(not_applicable("not on the extension relay")); } - let pinned = self.active_target_id.clone().ok_or("no pinned tab")?; - if !self.created_targets.contains(&pinned) { - return Err("only a tab this session created has its frames removed".to_string()); + let pinned = self + .active_target_id + .as_ref() + .ok_or_else(|| not_applicable("no pinned tab"))?; + if !self.created_targets.contains(pinned) { + return Err(not_applicable( + "the pinned tab was not created by this session", + )); } let page = self .pages .iter() - .find(|p| p.target_id == pinned) - .ok_or("pinned tab not tracked")?; + .find(|p| &p.target_id == pinned) + .ok_or_else(|| not_applicable("pinned tab not tracked"))?; let out = self .client .send_command( @@ -7927,16 +7987,28 @@ impl BrowserManager { None, ) .await - .map_err(|e| { - if e.contains("wasn't found") || e.contains("not found") { - "ab-connect is older than 0.5.108; Chrome updates it from the Web Store \ - (or update it from chrome://extensions)" - .to_string() + .map_err(|error| { + if extension_method_unsupported(&error, "ABExt.clearExtensionFrames") { + not_applicable("the installed extension does not support frame cleanup") + } else if error.contains("clearExtensionFrames: no site access") { + not_applicable("the extension lacks site access for this tab") + } else if error.contains("clearExtensionFrames: only a tab chrome-use created") { + not_applicable("the extension does not own this tab") + } else if error.contains("clearExtensionFrames: the tab has no web frame") { + not_applicable("the tab has no web frame eligible for cleanup") } else { - e + record_frame_cleanup("unconfirmed", &error); + error } })?; - extension_frames_note(&out) + extension_frames_note(&out).inspect_err(|detail| { + let status = if out["removed"].as_array().is_some_and(Vec::is_empty) { + "none_removed" + } else { + "unconfirmed" + }; + record_frame_cleanup(status, detail); + }) } pub async fn cycle_pinned_tab_visibility_menus( @@ -16474,6 +16546,7 @@ mod protected_url_tests { Accessible, MalformedAccessible, Blocked, + Snapshot { requested: bool, adopted: bool }, } fn committed(url: Option<&str>) -> (Value, Value) { @@ -16514,6 +16587,10 @@ mod protected_url_tests { assert_eq!(r["params"]["targetId"], "target-7"); records.0.clone() } + "ABExt.clearExtensionFrames" => records.1.clone(), + "ABExt.call" if matches!(query, Query::Snapshot { .. }) => { + json!({"result":null}) + } "ABExt.call" => { assert_eq!(r["params"]["namespace"], "tabs"); assert_eq!(r["params"]["method"], "get"); @@ -16523,7 +16600,8 @@ mod protected_url_tests { _ => json!({}), }; let inspect_error = records.0.get("inspectError").and_then(Value::as_str); - let failed = (method == "ABExt.inspectTab" && inspect_error.is_some()) + let failed = (matches!(query, Query::Snapshot { .. }) && method == "DOM.enable") + || (method == "ABExt.inspectTab" && inspect_error.is_some()) || (method == "Runtime.evaluate" && !error.is_empty()) || (!matches!(query, Query::Url) && !error.is_empty() @@ -16554,10 +16632,24 @@ mod protected_url_tests { }], ) .await; - browser.reown_target("target-7").unwrap(); + if matches!(query, Query::Snapshot { adopted: true, .. }) { + browser.adopted_targets.insert("target-7".into()); + } else { + browser.reown_target("target-7").unwrap(); + } let result = match query { Query::Url => browser.get_address_bar_url().await, Query::RendererUrl => browser.get_url().await, + Query::Snapshot { requested, .. } => { + let mut state = crate::native::actions::DaemonState::new(); + state.browser = Some(browser); + let cmd = json!({"id":"snapshot","action":"snapshot","interactive":true,"compact":true,"_clearExtensionFrames":requested}); + let response = Box::pin(crate::native::actions::execute_command_recovering( + &cmd, &mut state, + )) + .await; + Ok(response.to_string()) + } Query::Auth => { let mut state = crate::native::actions::DaemonState::new(); state.browser = Some(browser); @@ -16576,6 +16668,65 @@ mod protected_url_tests { (result, requests) } + #[tokio::test] + async fn blocked_snapshot_reports_frame_cleanup_without_recommending_it_again() { + let denied = "debugger_access_denied: Chrome denied access; Frames of other extensions open in this browser: aeblfdkhhhdcdjpifhhbdiojplfjncoa (chrome://extensions/?id=aeblfdkhhhdcdjpifhhbdiojplfjncoa)"; + for (requested, adopted, reply, status, calls) in [ + (false, false, json!({}), "not_requested", 0), + (true, true, json!({}), "not_applicable", 0), + (true, false, json!({"removed":[]}), "none_removed", 1), + (true, false, json!({}), "unconfirmed", 1), + ( + true, + false, + json!({"removed":[{"host":"fixture"}]}), + "still_blocked", + 1, + ), + ] { + let (out, seen) = query( + true, + denied, + ( + json!({"chromeTabId":7,"url":"https://fixture.invalid/form"}), + reply, + ), + Query::Snapshot { requested, adopted }, + ) + .await; + let out: Value = serde_json::from_str(&out.unwrap()).unwrap(); + assert_eq!(out["success"], false, "{out}"); + assert_eq!(out["code"], "debugger_access_denied", "{out}"); + assert_eq!( + out["data"]["extensionFrameCleanup"]["status"], status, + "{out}" + ); + let error = out["error"].as_str().unwrap(); + assert!( + error.contains("DOM.enable") && error.contains("same session"), + "{error}" + ); + assert!( + !error.contains("run it again with --clear-extension-frames"), + "{error}" + ); + assert_eq!( + seen.iter() + .filter(|r| r["method"] == "ABExt.clearExtensionFrames") + .count(), + calls + ); + assert!(!seen.iter().any(|r| r["method"] == "Page.reload" + || r["method"] == "Page.navigate" + || r["method"] == "Target.closeTarget")); + let wire: crate::connection::Response = serde_json::from_value(out).unwrap(); + assert_eq!( + wire.data.unwrap()["extensionFrameCleanup"]["status"], + status + ); + } + } + #[tokio::test] async fn old_relay_url_falls_back_only_for_an_unsupported_inspect_method() { for inspect_error in [ diff --git a/cli/src/native/clipboard_policy_tests.rs b/cli/src/native/clipboard_policy_tests.rs index 2aadb8f3ff..9617b10a21 100644 --- a/cli/src/native/clipboard_policy_tests.rs +++ b/cli/src/native/clipboard_policy_tests.rs @@ -615,6 +615,91 @@ async fn named_css_field_policy_reads_only_the_intended_renderer_in_both_directi } } +#[tokio::test] +async fn payment_approval_explains_the_rule_without_echoing_field_or_input_values() { + let attrs = json!([ + "id", + "docsConfig-private-field", + "value", + "private-old-value", + "aria-label", + "New prompt for private-account", + "private-attribute", + "private-marker" + ]); + let (mut state, server, commands, _mode) = fixture_with_fields( + field_policy(), + "fixture.test", + "once", + [("cb-tab-1".into(), attrs)].into_iter().collect(), + ) + .await; + let cmd = json!({"id":"explain","action":"fill","selector":"#private-selector","value":"private-new-value"}); + let gate = site_gate(&cmd, "fill", "explain", &mut state) + .await + .unwrap(); + let data = &gate["data"]; + assert_eq!(data["reason"], "payment_input"); + assert_eq!(data["description"], "chrome-use wants to type into a payment card field on fixture.test (card security-code marker in id)"); + let log = commands.lock().unwrap(); + let request = log + .iter() + .find(|r| r["method"] == "ABExt.siteApproval") + .unwrap(); + assert_eq!(request["params"]["description"], data["description"]); + for output in [data, &request["params"]] { + let text = output.to_string(); + for raw in ["private-", "docsConfig", "New prompt", "csc"] { + assert!(!text.contains(raw), "{text}"); + } + } + server.abort(); +} + +#[tokio::test] +async fn a_derived_snapshot_label_still_holds_payment_but_reports_its_provenance() { + use super::super::element::{AxIdentity, DerivedName}; + + for (derived, source) in [ + (DerivedName::Context, "snapshot label derived from context"), + ( + DerivedName::OwnText, + "snapshot label derived from element text", + ), + ] { + let (mut state, server, _commands, _mode) = fixture_with_fields( + field_policy(), + "fixture.test", + "once", + [("cb-tab-1".into(), json!(["name", "prompt"]))] + .into_iter() + .collect(), + ) + .await; + state.ref_map.add( + "e1".into(), + Some(41), + "textbox", + "Security code in private-context", + None, + ); + state.ref_map.set_ax_identity( + "e1", + AxIdentity { + role: "textbox".into(), + name: "".into(), + source: derived, + }, + ); + let cmd = json!({"id":"ref","action":"fill","selector":"@e1","value":"private-input"}); + let gate = site_gate(&cmd, "fill", "ref", &mut state).await.unwrap(); + assert_eq!(gate["data"]["reason"], "payment_input"); + assert_eq!(gate["data"]["description"], format!("chrome-use wants to type into a payment card field on fixture.test (card security-code marker in {source})")); + assert!(!gate.to_string().contains("private-")); + server.abort(); + } +} + #[tokio::test] async fn named_ref_field_policy_uses_saved_target_map_and_iframe_session() { for (a, b, expected) in [ diff --git a/cli/src/native/site_policy.rs b/cli/src/native/site_policy.rs index 6729c6b8a0..5d52f32bd0 100644 --- a/cli/src/native/site_policy.rs +++ b/cli/src/native/site_policy.rs @@ -44,36 +44,40 @@ pub const DEFAULT_ASK: &[&str] = &["payment_input", "purchase"]; /// Every kind (the extension's `KINDS`). pub const KINDS: &[&str] = &["payment_input", "purchase", "password_input", "download"]; -/// Lowercased `name` / `id` fragments of a payment field. -const PAYMENT_IDENTIFIERS: &[&str] = &[ - "cardnumber", - "card-number", - "card_number", - "ccnumber", - "cc-number", - "cc_number", - "cvc", - "cvv", - "exp-date", - "expdate", - "expiry", - "expiration", - "cc-exp", - "cc_exp", -]; -/// Lowercased accessible-name fragments of a payment field. -const PAYMENT_NAMES: &[&str] = &[ - "card number", - "credit card", - "debit card", - "card verification", - "cvc", - "cvv", - "expiration", - "expiry", - "卡号", - "信用卡", - "有效期", +/// Strong payment markers are grouped by the meaning we can safely report. +const PAYMENT_MARKERS: &[(&str, &[&str])] = &[ + ( + "card number marker", + &[ + "cardnumber", + "card-number", + "card_number", + "ccnumber", + "cc-number", + "cc_number", + "card number", + "credit card", + "debit card", + "卡号", + "信用卡", + ], + ), + ( + "card security-code marker", + &["cvc", "cvv", "card verification"], + ), + ( + "card expiration marker", + &[ + "exp-date", + "expdate", + "expiry", + "expiration", + "cc-exp", + "cc_exp", + "有效期", + ], + ), ]; /// Words a card's CVV field and a sign-in's one-time-code field share /// ("security code", 安全码): payment only when nothing marks the field as @@ -134,87 +138,122 @@ fn has_word(haystack: &str, word: &str) -> bool { .any(|w| w == word) } -/// `payment_input` or `password_input` for a selector, label or accessible -/// name, judged by its words. Payment wins when both match. -pub fn field_kind_from_text(text: &str) -> Option<&'static str> { - let t = text.to_lowercase(); - if t.trim().is_empty() { - return None; +/// Only fixed labels can reach an approval description. Field contents, selectors, +/// accessible names and the text being typed never appear in the explanation. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PaymentFieldMatch { + pub source: &'static str, + pub rule: &'static str, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SiteActionKind { + pub name: &'static str, + pub payment_match: Option, +} + +impl SiteActionKind { + pub fn new(name: &'static str) -> Self { + Self { + name, + payment_match: None, + } + } + + fn payment(source: &'static str, rule: &'static str) -> Self { + Self { + name: "payment_input", + payment_match: Some(PaymentFieldMatch { source, rule }), + } } - let one_time_code = ONE_TIME_CODE_MARKERS.iter().any(|p| t.contains(p)); - if PAYMENT_IDENTIFIERS +} + +fn classify_field_text(parts: &[(&'static str, String)]) -> Option { + let one_time_code = parts .iter() - .chain(PAYMENT_NAMES) - .any(|p| t.contains(p)) - || (!one_time_code && PAYMENT_AMBIGUOUS.iter().any(|p| t.contains(p))) + .any(|(_, t)| ONE_TIME_CODE_MARKERS.iter().any(|p| t.contains(p))); + for &(rule, markers) in PAYMENT_MARKERS + .iter() + .chain((!one_time_code).then_some(&("card security-code marker", PAYMENT_AMBIGUOUS))) { - return Some("payment_input"); - } - if one_time_code { - return Some("password_input"); - } - if t.contains("type=password") - || t.contains("type=\"password\"") - || PASSWORD_IDENTIFIERS + if let Some((source, _)) = parts .iter() - .chain(PASSWORD_NAMES) - .any(|p| t.contains(p)) - || has_word(&t, "pin") - { - return Some("password_input"); + .find(|(_, t)| markers.iter().any(|p| t.contains(p))) + { + return Some(SiteActionKind::payment(source, rule)); + } } - None + let password = one_time_code + || parts.iter().any(|(_, t)| { + t.contains("type=password") + || t.contains("type=\"password\"") + || PASSWORD_IDENTIFIERS + .iter() + .chain(PASSWORD_NAMES) + .any(|p| t.contains(p)) + || has_word(t, "pin") + }); + password.then_some(SiteActionKind::new("password_input")) +} + +/// A bulk form map has no single inspected field to attribute a rule to. +pub fn field_kind_from_text(text: &str) -> Option<&'static str> { + classify_field_text(&[("form map", text.to_lowercase())]).map(|m| m.name) } -/// `payment_input` or `password_input` from a field's DOM attributes (a flat -/// `[name, value, ...]` list, as CDP `DOM.describeNode` returns them). #[cfg(test)] -pub fn field_kind_from_attributes(attrs: &[String]) -> Option<&'static str> { - field_kind(attrs, &[]) +fn field_kind_from_attributes(attrs: &[String]) -> Option<&'static str> { + field_kind(attrs, "", ("snapshot label", "")).map(|m| m.name) } -/// The kind of a typed-into field from its DOM attributes plus what else -/// names it (the agent's selector, its accessible name), judged together: -/// a one-time-code mark anywhere (`autocomplete=one-time-code`, a 6-digit -/// `maxlength`, "验证码" in the placeholder) keeps an ambiguous "security -/// code" from reading as a card field (#846). A card's own marks -/// (`autocomplete=cc-*`, "card number", "cvv") still win. -pub fn field_kind(attrs: &[String], names: &[&str]) -> Option<&'static str> { +/// Classify the typed-into node using its DOM attributes, selector and snapshot +/// label. An OTP marker anywhere suppresses ambiguous card security-code terms +/// (#846); explicit card markers and card autocomplete still take precedence. +pub fn field_kind( + attrs: &[String], + selector: &str, + (label_source, label): (&'static str, &str), +) -> Option { let mut password = false; - let mut text: Vec = names.iter().map(|n| n.to_lowercase()).collect(); - for pair in attrs.chunks(2) { - let [key, value] = pair else { continue }; - let value = value.to_lowercase(); - match key.as_str() { + let mut parts = Vec::new(); + for pair in attrs.chunks_exact(2) { + let value = pair[1].to_lowercase(); + match pair[0].as_str() { "autocomplete" => { for token in value.split_whitespace() { if token.starts_with("cc-") { - return Some("payment_input"); + return Some(SiteActionKind::payment("autocomplete", "card autocomplete")); } if matches!(token, "current-password" | "new-password" | "one-time-code") { password = true; } if token == "one-time-code" { - text.push("one-time-code".into()); + parts.push(("autocomplete", "one-time-code".into())); } } } "type" if value == "password" => password = true, - "maxlength" if value.trim() == "6" => text.push("6-digit".into()), - "name" - | "id" - | "data-elements-stable-field-name" - | "aria-label" - | "placeholder" - | "title" => text.push(value), - _ => {} + "maxlength" if value.trim() == "6" => parts.push(("maxlength", "6-digit".into())), + key => { + const NAMING_ATTRIBUTES: &[&str] = &[ + "name", + "id", + "data-elements-stable-field-name", + "aria-label", + "placeholder", + "title", + ]; + if let Some(&source) = NAMING_ATTRIBUTES.iter().find(|&&attr| attr == key) { + parts.push((source, value)); + } + } } } - match field_kind_from_text(&text.join("\n")) { - Some("payment_input") => Some("payment_input"), - Some(_) => Some("password_input"), - None => password.then_some("password_input"), - } + // Prefer the node's own static attributes when more than one source matches. + parts.push((label_source, label.to_lowercase())); + parts.push(("selector", selector.to_lowercase())); + classify_field_text(&parts) + .or_else(|| password.then_some(SiteActionKind::new("password_input"))) } /// The category of a daemon action, or `None` for actions that only read @@ -846,6 +885,45 @@ mod tests { assert_eq!(field_kind_from_text("Search"), None); } + #[test] + fn payment_field_explanation_names_the_source_and_rule_with_existing_precedence() { + let classify = |attrs: &[&str], selector: &str, label: &str| { + let attrs: Vec<_> = attrs.iter().map(|s| (*s).into()).collect(); + field_kind(&attrs, selector, ("snapshot label", label)) + }; + assert_eq!(classify(&["name", "rule"], "@e1", "New prompt"), None); + assert_eq!( + classify(&["id", "docsConfig"], "@e1", "New prompt"), + Some(SiteActionKind::payment("id", "card security-code marker")) + ); + assert_eq!( + classify(&["id", "docsConfig", "maxlength", "6"], "@e1", "New prompt"), + Some(SiteActionKind::new("password_input")) + ); + assert_eq!( + classify( + &["id", "docsConfig", "autocomplete", "one-time-code"], + "@e1", + "Card number" + ), + Some(SiteActionKind::payment( + "snapshot label", + "card number marker" + )) + ); + assert_eq!( + classify(&["autocomplete", "billing CC-number"], "#cvv", "New prompt"), + Some(SiteActionKind::payment("autocomplete", "card autocomplete")) + ); + assert_eq!( + classify(&[], "#expiry", "New prompt"), + Some(SiteActionKind::payment( + "selector", + "card expiration marker" + )) + ); + } + #[test] fn non_relay_sessions_get_no_defaults() { let p = SitePolicy::default(); @@ -921,12 +999,19 @@ mod tests { assert_eq!( field_kind( &attrs(&[("autocomplete", "one-time-code")]), - &["Security code"] - ), + "", + ("snapshot label", "Security code") + ) + .map(|m| m.name), Some("password_input") ); assert_eq!( - field_kind(&attrs(&[("maxlength", "6")]), &["安全码"]), + field_kind( + &attrs(&[("maxlength", "6")]), + "", + ("snapshot label", "安全码") + ) + .map(|m| m.name), Some("password_input") ); assert_eq!( @@ -937,11 +1022,21 @@ mod tests { assert_eq!(field_kind_from_text("Security code"), Some("payment_input")); assert_eq!(field_kind_from_text("安全码"), Some("payment_input")); assert_eq!( - field_kind(&attrs(&[("autocomplete", "cc-csc")]), &["one-time code"]), + field_kind( + &attrs(&[("autocomplete", "cc-csc")]), + "", + ("snapshot label", "one-time code") + ) + .map(|m| m.name), Some("payment_input") ); assert_eq!( - field_kind(&attrs(&[("maxlength", "6"), ("name", "cvv")]), &[]), + field_kind( + &attrs(&[("maxlength", "6"), ("name", "cvv")]), + "", + ("snapshot label", "") + ) + .map(|m| m.name), Some("payment_input") ); assert_eq!(field_kind_from_text("Card number"), Some("payment_input")); diff --git a/cli/src/output.rs b/cli/src/output.rs index f02eaff1db..2b94320117 100644 --- a/cli/src/output.rs +++ b/cli/src/output.rs @@ -5247,6 +5247,8 @@ default; password fields and downloads when turned on; see "Permissions & safety" in the docs), the action returns a confirmation_required response with a confirmation ID instead of running. Use confirm/deny to approve or reject it. +When a field triggers payment confirmation, its reason can name the field +attribute and the kind of payment cue. Include the reason in a false-positive report. When the response says `approval: user`, the request is waiting in the chrome-use extension (side panel, notification, options page). Only the @@ -5899,7 +5901,9 @@ Usage: Lists every profile in Chrome's Local State: display name, directory, signed-in account, whether its extension relay is connected, which one is the default without --browser, and which one this --session uses. Unconnected rows show the -command that connects them. +command that connects them. A profile listed on disk can have no live relay. +Check Chrome's process state before opening a window or checking pairing +in that profile's extension popup. --who : for every profile, whether it looks signed in to , from cookie NAMES in the profile's on-disk cookie store (never values; no tab is @@ -5929,7 +5933,7 @@ Defaults (~/.chrome-use/config.json): ChooseBrowser rules are binding (macOS, when that app is installed): If the rule's profile is not connected, `open` fails naming the rule and - `chrome-use connect --browser ` (opens a window in that profile, so + `chrome-use connect --browser ` (can open a window in that profile, so ask the user first) instead of using another profile. If the session is already bound to a different profile, `open`/`goto`/ `navigate`/`tab new ` of the rule's site fails: use a new --session @@ -5957,12 +5961,17 @@ chrome-use connect - Connect to browser via CDP, or connect a Chrome profile Usage: chrome-use connect chrome-use connect --browser [--wait ] ---browser : connect that Chrome profile to chrome-use, lazily. If the -extension is missing there, opens its Chrome Web Store page IN THAT PROFILE — -the user clicks "Add to Chrome" once; if it is installed but the profile isn't -open, opens a window in it; if Chrome has it disabled, opens its extensions -page. Then waits (default 120s) for that profile's relay. It opens a window in -the user's Chrome, so agents ask the user first. +--browser : request a window in that Chrome profile and wait for its +relay (default 120s). If the extension is missing, request its Chrome Web Store +page so the user can click "Add to Chrome". If it is disabled, request the +extensions page. The command reports success once the profile's relay is live. +This can open a window in the user's Chrome, so agents ask the user first. + +On timeout, check chrome-use status and the extension popup in that profile. +If the host registration needs repair or the popup says "Not paired", run +chrome-use extension install --all-profiles, fully quit Chrome, then reopen +the profile. If the popup shows it is paired but the relay stays offline, +reopen the popup or reload the extension at chrome://extensions, then retry. Connects to a running browser instance via Chrome DevTools Protocol (CDP). This allows controlling browsers, Electron apps, or remote browser services. @@ -6052,7 +6061,11 @@ chrome-use status - Show browser automation health without contacting a session Usage: chrome-use status -Reports the installed CLI version, native host and extension relay state, +Reports whether Chrome is running (or unknown), native host registration, +and the live extension relay separately. Check pairing in the extension popup +for the selected profile. In --json, data.extension.browserProcess is running, +notRunning, or unknown. data.extension.pairing stays unverified until a live +extension answers the diagnostic. Status also reports the installed CLI version, live versus bundled extension version, driving Chrome profile, current session, and all running session daemons. Because this command is daemon-free, use it as the first check when browser commands are hanging. @@ -6810,7 +6823,7 @@ Core Commands: with --silent browsers [--who ] List every Chrome profile (name, dir, account, connected, default, this session); --who: which look signed in to a site - connect --browser Connect one more Chrome profile (opens a window there; + connect --browser Connect one more Chrome profile (requests a window; one "Add to Chrome" click if the extension is missing) keep Leave the active tab for the user — exempt it from auto-close/idle cleanup + remove it from the session @@ -7261,6 +7274,8 @@ Options: (debugger_access_denied, e.g. 1Password's hidden sign-in frame), remove other extensions' frames from that page and go on (or AGENT_BROWSER_CLEAR_EXTENSION_FRAMES=1; ab-connect 0.5.108+) + Still denied? See data.extensionFrameCleanup for the outcome. + Keep the tab open, close the extension menu, then resume with snapshot -i. --open-profile-window When the session's Chrome profile has no window (profile_not_open), open one in the background in that same profile and go on (or AGENT_BROWSER_OPEN_PROFILE_WINDOW=1). Default off. JSON reports diff --git a/cli/src/profiles.rs b/cli/src/profiles.rs index b6054d8acd..6c8f016883 100644 --- a/cli/src/profiles.rs +++ b/cli/src/profiles.rs @@ -35,6 +35,9 @@ pub struct ProfileRow { pub relay_email: Option, /// The profile's relay endpoint, when connected. pub ws: Option, + /// Result of the listener probe when the command requested live status. + /// Other callers can still use a recorded endpoint as a routing hint. + pub(crate) relay_accepts: Option, pub has_extension: bool, /// Chrome lists disable reasons for the extension in this profile. pub extension_disabled: bool, @@ -42,7 +45,21 @@ pub struct ProfileRow { impl ProfileRow { pub fn connected(&self) -> bool { - self.ws.is_some() + self.ws.is_some() && self.relay_accepts != Some(false) + } + + fn connection_label(&self, process: connect::ChromeProcess) -> &'static str { + if self.connected() { + "yes" + } else if self.extension_disabled { + "no (disabled)" + } else if process == connect::ChromeProcess::NotRunning { + "no (browser closed)" + } else if self.has_extension { + "no (no relay listener)" + } else { + "no (extension not found)" + } } fn account(&self) -> Option<&str> { @@ -225,6 +242,16 @@ pub fn load_rows() -> Vec { join_rows(&local, &relays, &|id| relay_id_dir(id, &local)) } +/// Sidecars survive a stopped native host. Inventory and profile selection +/// can check for a listener while retaining the recorded URL for diagnosis. +pub(crate) fn load_listening_rows() -> Vec { + let mut rows = load_rows(); + for row in &mut rows { + row.relay_accepts = row.ws.as_deref().map(connect::relay_endpoint_accepts); + } + rows +} + // --- Selector matching ------------------------------------------------------- #[derive(Debug, PartialEq)] @@ -347,7 +374,7 @@ fn list_lines(rows: &[ProfileRow], which: &[usize]) -> String { /// What to say about a profile that matched but has no live relay. pub fn not_connected_message(selector: &str, row: &ProfileRow) -> String { let cmd = connect_command(selector); - let ask = "It opens a window in the user's Chrome, so ask the user before running it."; + let ask = "It requests a window in the user's Chrome, so ask the user before running it."; if !row.has_extension { format!( "profile \"{selector}\" doesn't have the chrome-use extension yet — run `{cmd}` \ @@ -361,8 +388,8 @@ pub fn not_connected_message(selector: &str, row: &ProfileRow) -> String { ) } else { format!( - "profile \"{selector}\" ({}) has the chrome-use extension but isn't open in Chrome \ - right now — run `{cmd}` (opens a window in that profile), then repeat. {ask}", + "profile \"{selector}\" ({}) has the chrome-use extension but no connected relay \ + — run `{cmd}` (opens a window in that profile), then repeat. {ask}", row.dir.as_deref().unwrap_or("?") ) } @@ -1140,7 +1167,8 @@ pub fn run_browsers(args: &[String], session: &str, json_out: bool) { } return; } - let rows = load_rows(); + let rows = load_listening_rows(); + let process = connect::observed_chrome_process(false); let cfg = load_profiles_config(); let default = default_index(&rows, cfg.as_ref()); let session_id = crate::connection::daemon_ready(session) @@ -1161,6 +1189,7 @@ pub fn run_browsers(args: &[String], session: &str, json_out: bool) { .map(|(i, r)| { let mut v = r.to_json(); v["wsUrl"] = json!(r.ws); + v["relayAccepts"] = json!(r.relay_accepts); v["default"] = json!(default == Some(i)); v["session"] = json!(in_session(r)); if !r.connected() { @@ -1169,10 +1198,14 @@ pub fn run_browsers(args: &[String], session: &str, json_out: bool) { v }) .collect(); - println!("{}", json!({"success": true, "data": {"browsers": arr}})); + println!( + "{}", + json!({"success": true, "data": {"browserProcess": process, "browsers": arr}}) + ); return; } + println!("Chrome process: {}", process.label()); if rows.is_empty() { let host = connect::native_host_report(); if !host.manifests.is_empty() && !host.is_healthy() { @@ -1204,20 +1237,11 @@ pub fn run_browsers(args: &[String], session: &str, json_out: bool) { ]; let mut table: Vec<[String; 7]> = Vec::new(); for (i, r) in rows.iter().enumerate() { - let connected = if r.connected() { - "yes".to_string() - } else if r.extension_disabled { - "no (disabled)".to_string() - } else if r.has_extension { - "no (not open)".to_string() - } else { - "no".to_string() - }; table.push([ r.name.clone().unwrap_or_else(|| "-".into()), r.dir.clone().unwrap_or_else(|| "-".into()), r.account().unwrap_or("-").to_string(), - connected, + r.connection_label(process).into(), if default == Some(i) { "*" } else { "" }.to_string(), if in_session(r) { "*" } else { "" }.to_string(), if r.connected() { @@ -1271,7 +1295,7 @@ pub fn run_browsers(args: &[String], session: &str, json_out: bool) { ); if rows.iter().any(|r| !r.connected()) { println!( - "Not connected: the command on its row connects it — it opens a window in that \ + "Not connected: the command on its row requests a window in that \ profile (one click if the extension isn't there yet). Agents: ask the user first." ); } @@ -1477,7 +1501,7 @@ fn run_who(domain: &str, json_out: bool) { fail(json_out, &format!("--who: '{domain}' is not a domain")); return; } - let rows = load_rows(); + let rows = load_listening_rows(); let adapter = whoami_adapter(&domain); let mut out: Vec = Vec::new(); let mut lines: Vec<[String; 4]> = Vec::new(); @@ -1577,9 +1601,27 @@ fn run_who(domain: &str, json_out: bool) { // --- `chrome-use connect --browser ` --------------------------------- +/// A TCP listener is enough for the inventory, but connect waits for an +/// extension protocol reply before reporting that this profile can be used. +fn responsive_profile(row: &ProfileRow) -> bool { + row.connected() + && row + .ws + .as_deref() + .is_some_and(|url| connect::relay_health_at(url).transport_responsive) +} + +fn connect_timeout_hint(action: &str) -> &'static str { + match action { + "store" => "Check that Add to Chrome completed in that profile.", + "enable" => "Check that the extension is enabled at chrome://extensions in that profile.", + _ => connect::RELAY_PAIRING_HELP, + } +} + /// Connect one more profile, lazily: open the Web Store page in that profile /// (one click: "Add to Chrome"), or — if the extension is already there — -/// open a window so its worker starts, then wait for its relay. +/// request a window and wait for the extension to answer on its relay. pub fn run_connect_profile(selector: &str, args: &[String], json_out: bool) { let wait_secs: u64 = args .iter() @@ -1587,7 +1629,7 @@ pub fn run_connect_profile(selector: &str, args: &[String], json_out: bool) { .and_then(|i| args.get(i + 1)) .and_then(|v| v.parse().ok()) .unwrap_or(120); - let rows = load_rows(); + let rows = load_listening_rows(); let i = match resolve_in(&rows, selector) { Ok(i) => i, Err(e) => { @@ -1618,7 +1660,7 @@ pub fn run_connect_profile(selector: &str, args: &[String], json_out: bool) { ); } }; - if row.connected() { + if responsive_profile(&row) { done(&row, true); return; } @@ -1656,8 +1698,7 @@ pub fn run_connect_profile(selector: &str, args: &[String], json_out: bool) { "enable", format!( "The chrome-use extension is installed in {} but Chrome has it disabled \ - ({}). Turn it on (and accept any permission prompt) in the extensions \ - page that just opened in that profile.", + ({}). Turn it on (and accept any permission prompt) in chrome://extensions in that profile. Requested its extensions page in Chrome.", row.label(), ext.disable_reasons.join(", ") ), @@ -1667,8 +1708,7 @@ pub fn run_connect_profile(selector: &str, args: &[String], json_out: bool) { connect::open_in_profile(&local, None), "open-window", format!( - "The extension is installed in {} but that profile isn't open. Opened a window \ - in it so the extension can start.", + "Requested a Chrome window for {} so its installed extension can connect.", row.label() ), ), @@ -1676,8 +1716,7 @@ pub fn run_connect_profile(selector: &str, args: &[String], json_out: bool) { connect::open_in_profile(&local, Some(connect::STORE_URL)), "store", format!( - "Opened the chrome-use page of the Chrome Web Store in {}. Click \"Add to \ - Chrome\" there — that's the only step; Chrome keeps it updated after.", + "Requested the chrome-use Web Store page in {}. Click \"Add to Chrome\" there.", row.label() ), ), @@ -1690,7 +1729,7 @@ pub fn run_connect_profile(selector: &str, args: &[String], json_out: bool) { fail( json_out, &format!( - "couldn't open a Chrome window in {} automatically — {manual}, then re-run.", + "couldn't request a Chrome window in {} — {manual}, then re-run.", row.label() ), ); @@ -1698,13 +1737,13 @@ pub fn run_connect_profile(selector: &str, args: &[String], json_out: bool) { } if !json_out { eprintln!("{told}"); - eprint!("waiting up to {wait_secs}s for it to connect "); + eprint!("waiting up to {wait_secs}s for the extension relay to respond "); } let deadline = std::time::Instant::now() + std::time::Duration::from_secs(wait_secs); loop { if let Some(now) = load_rows() .into_iter() - .find(|r| r.same_profile(&row) && r.connected()) + .find(|r| r.same_profile(&row) && responsive_profile(r)) { if !json_out { eprintln!(); @@ -1724,20 +1763,22 @@ pub fn run_connect_profile(selector: &str, args: &[String], json_out: bool) { if !json_out { eprintln!(); } + let process = connect::observed_chrome_process(false); + let start = if process == connect::ChromeProcess::NotRunning { + " Start Chrome in that profile first." + } else { + "" + }; let msg = format!( - "{} isn't connected yet ({}). Re-run `{}` to keep waiting.", - row.label(), - match action { - "store" => "was \"Add to Chrome\" clicked?", - "enable" => "is the extension switched on?", - _ => "the extension's worker can take ~30s to wake", - }, - connect_command(selector.trim()) + "No extension relay responded for {} within {wait_secs}s. Chrome process: {}.{start} {} Re-run `{}`.", + row.label(), process.label(), connect_timeout_hint(action), connect_command(selector.trim()) ); if json_out { + let mut profile = row.to_json(); + profile["connected"] = false.into(); println!( "{}", - json!({"success": false, "error": msg, "data": {"connected": false, "action": action, "profile": row.to_json()}}) + json!({"success": false, "error": msg, "data": {"connected": false, "windowRequested": true, "browserProcess": process, "action": action, "profile": profile}}) ); } else { eprintln!("{} {msg}", color::error_indicator()); @@ -1878,7 +1919,7 @@ mod tests { let mut with_ext = r.clone(); with_ext[4].has_extension = true; let e = resolve_connected_in(&with_ext, "dora").unwrap_err(); - assert!(e.contains("isn't open in Chrome")); + assert!(e.contains("no connected relay")); let e = resolve_connected_in(&r, "Profile 12").unwrap_err(); assert!(e.contains("connect --browser \"Profile 12\"")); assert_eq!(resolve_connected_in(&r, "dav"), Ok(1)); diff --git a/cli/tests/relay_diagnostics.rs b/cli/tests/relay_diagnostics.rs new file mode 100644 index 0000000000..8d42f50923 --- /dev/null +++ b/cli/tests/relay_diagnostics.rs @@ -0,0 +1,101 @@ +//! Exercise offline CLI diagnostics without a real browser, user profile or daemon. +#![cfg(any(target_os = "macos", target_os = "linux"))] +use serde_json::{json, Value}; +use std::{fs, os::unix::fs::PermissionsExt, path::Path, process::Command}; + +fn shim(path: &Path, content: &str) { + fs::write(path, content).unwrap(); + fs::set_permissions(path, fs::Permissions::from_mode(0o755)).unwrap(); +} + +#[test] +fn offline_profiles_report_process_host_and_listener_separately() { + let temp = tempfile::tempdir().unwrap(); + let home = temp.path(); + let bin = home.join("bin"); + let relay = home.join("relay"); + fs::create_dir(&bin).unwrap(); + fs::create_dir(&relay).unwrap(); + // No system commands on PATH; even the window request is a local no-op. + shim(&bin.join("pgrep"), "#!/bin/sh\n[ \"$TEST_PROCESS\" = unknown ] && exit 2\ncase \"$2\" in launchd|chrome-use) echo 1;; 'Google Chrome'|chrome) [ \"$TEST_PROCESS\" = running ] || exit 1; echo 42;; *) exit 1;; esac\n"); + for name in ["open", "google-chrome"] { + shim(&bin.join(name), "#!/bin/sh\nexit 0\n"); + } + #[cfg(target_os = "macos")] + let root = home.join("Library/Application Support/Google/Chrome"); + #[cfg(target_os = "linux")] + let root = home.join(".config/google-chrome"); + fs::create_dir_all(root.join("Default")).unwrap(); + fs::write(root.join("Local State"), json!({"profile":{"info_cache":{"Default":{"name":"Work","user_name":"work@example.invalid"}}}}).to_string()).unwrap(); + fs::write(root.join("Default/Preferences"), json!({"extensions":{"settings":{"knfcmbamhjmaonkfnjhldjedeobeafmk":{"manifest":{"version":"0.0.1"}}}}}).to_string()).unwrap(); + let cli = |process: &str, args: &[&str]| { + let out = Command::new(env!("CARGO_BIN_EXE_chrome-use")) + .env_clear() + .env("HOME", home) + .env("PATH", &bin) + .env("TEST_PROCESS", process) + .env("CHROME_USE_RELAY_DIR", &relay) + .env("AGENT_BROWSER_SOCKET_DIR", home.join("sockets")) + .env("CHROME_USE_NO_UPDATE_CHECK", "1") + .env("CHROME_USE_NO_BROWSER_SCAN", "1") + .args(args) + .output() + .unwrap(); + let json: Value = serde_json::from_slice(&out.stdout) + .unwrap_or_else(|e| panic!("{e}: {}", String::from_utf8_lossy(&out.stderr))); + assert_eq!( + out.status.success(), + json["success"].as_bool().unwrap(), + "{json}" + ); + json + }; + for (process, expected) in [ + ("closed", "notRunning"), + ("running", "running"), + ("unknown", "unknown"), + ] { + let status = cli(process, &["status", "--browser", "Work", "--json"]); + let extension = &status["data"]["extension"]; + assert_eq!(extension["browserProcess"], expected); + assert_eq!(extension["hostInstalled"], false); + assert_eq!(extension["relayUp"], false); + assert_eq!(extension["pairing"], "unverified"); + let list = cli(process, &["browsers", "--json"]); + assert_eq!(list["data"]["browserProcess"], expected); + assert_eq!(list["data"]["browsers"][0]["hasExtension"], true); + } + // Port zero is not a listening TCP endpoint. A surviving sidecar alone + // must not make either browsers or connect return a successful connection. + fs::write( + relay.join("relay-ext-profile-fixture"), + r#"{"id":"fixture","email":"work@example.invalid"}"#, + ) + .unwrap(); + fs::write( + relay.join("relay-cdp-url-fixture"), + "ws://127.0.0.1:0/stale", + ) + .unwrap(); + let list = cli("running", &["browsers", "--json"]); + let row = &list["data"]["browsers"][0]; + assert_eq!(row["connected"], false); + assert_eq!(row["relayAccepts"], false); + let timeout = cli( + "running", + &["connect", "--browser", "Work", "--wait", "0", "--json"], + ); + assert_eq!(timeout["success"], false, "{timeout}"); + assert_eq!(timeout["data"]["windowRequested"], true, "{timeout}"); + assert_eq!(timeout["data"]["profile"]["connected"], false); + let reason = timeout["error"].as_str().unwrap(); + assert!( + reason.contains("extension install --all-profiles") && reason.contains("fully quit Chrome"), + "{reason}" + ); + let status = cli("running", &["status", "--browser", "Work", "--json"]); + let extension = &status["data"]["extension"]; + assert_eq!(extension["hostLauncherHealthy"], true); + assert_eq!(extension["selectedProfile"]["relayAccepts"], false); + assert_eq!(extension["pairing"], "unverified"); +} diff --git a/docs/en/permissions.html b/docs/en/permissions.html index dc071a5608..87888a9315 100644 --- a/docs/en/permissions.html +++ b/docs/en/permissions.html @@ -82,6 +82,7 @@

When chrome-use asks first

The detection is heuristic. Typing without a ref or selector (focus, then keyboard type) or a pay button with an unusual name can slip through. It is a gate for a person to look, not a sandbox.

--launch and --cdp sessions do not get these defaults (usually nobody is watching there). They follow your policy file only.

+

If an ordinary field triggers payment confirmation during a fill, the reason can identify the attribute or snapshot label that matched a payment cue. Include the reason in your report. Keep the entered text private.

Approving

A gated command does not run. It exits with code 3 and prints a confirmation id:

diff --git a/docs/en/real-chrome.html b/docs/en/real-chrome.html index 2157e35560..37e674ab4c 100644 --- a/docs/en/real-chrome.html +++ b/docs/en/real-chrome.html @@ -180,7 +180,7 @@

Multiple Chrome profiles: see which one, then pick it

bash
-
# List every connected profile (shows email if identity permission is granted, else a stable id, with the default flagged)
+
# List profiles on disk and connected relays; check the connection and default columns
 $ chrome-use browsers
 
 # Pin "this session" to a specific profile — sticky per session, so different agents don't interfere
@@ -226,7 +226,7 @@ 

Let your rules pick: ChooseBrowser

Read-only, and invisible if you do not use it: no rules file means no behaviour change and no message. A rule is binding: chrome-use never opens its site in a different profile. If the rule's profile is not connected, the command fails and names - chrome-use connect --browser <profile> (it opens a window in that profile, + chrome-use connect --browser <profile> (it can request a window in that profile, so ask the user first). If the session is already bound to another profile, the command also fails: use a new --session (it picks the rule's profile), or pass --no-choosebrowser to open it in the bound profile anyway. An explicit @@ -338,39 +338,28 @@

If "Allow remote debugging?" really does pop up

  1. - The extension / relay isn't up. Have the user install the store extension (the one-click link - above); once installed the relay stays online and this prompt never comes back. + The extension relay is offline. Check Chrome, the host registration and the target profile as described below.

-

Relay drops: the CLI self-heals

-

- If a command suddenly reports "couldn't reach your Chrome" / "relay … failed"—usually the MV3 service worker got - suspended, or two agents are sharing one relay—the CLI now self-heals: it waits for the worker's - keepalive to bring the relay back (about 25 seconds) and retries once, so most drops you never even notice. If a - command does surface the error: -

+

When the extension relay is offline

+

Run chrome-use status to check the Chrome process, native host registration and live relay. + Use chrome-use browsers to find the target profile. A profile on disk can remain listed after Chrome quits.

    -
  1. Just re-run the command—by then the relay has usually reconnected.
  2. -
  3. Still failing: chrome-use status (daemon-free CLI, extension, relay, profile, and session health) → chrome-use extension connect (re-attach) → retry. - The CLI registers the native host automatically, and opens the store page if the extension was never installed—you - don't have to run extension install by hand.
  4. -
  5. Never have the user quit/restart Chrome with --remote-debugging-port to recover a - dropped relay—that loses all their tabs and completely breaks the extension path.
  6. -
  7. chrome-use reconnect is a friendly alias for extension connect—it rebinds the session - to the running Chrome with no reinstall needed.
  8. -
  9. Browser totally unrecoverable? Don't sit waiting on a screenshot—fall back to - non-visual verification: get text / eval, or read the deployed page with - curl/WebFetch. Confirm a change is correct via DOM/HTML or the live URL, not a - failure. Save screenshots for the visual checks you actually need to report to the user.
  10. +
  11. If Chrome is stopped, open it in the target profile. If the process state is unknown, check whether Chrome is running.
  12. +
  13. If the native host needs repair or the profile’s extension popup says Not paired, run + chrome-use extension install --all-profiles, fully quit Chrome, then reopen the profile.
  14. +
  15. If the popup shows the extension is paired but the relay stays offline, open the popup again or reload + chrome-use at chrome://extensions. An offline relay alone cannot tell you whether its worker is asleep.
+

chrome-use connect --browser <profile> can request a window. It waits up to 120 seconds + by default for that profile’s relay. If an earlier write was interrupted, check the page before repeating it.

✅ Don't serialize agents to dodge "fragility"
- A relay drop is transient and self-heals; it is not a signal that a shared browser can't be - driven concurrently. Concurrent multi-agent is supported—each --session has its own + Concurrent multi-agent use is supported—each --session has its own tab group and drives only its own tabs. Give each agent a distinct --session and run them in parallel instead of one at a time.
diff --git a/docs/en/troubleshooting.html b/docs/en/troubleshooting.html index 5de1cfea9c..ecba36be60 100644 --- a/docs/en/troubleshooting.html +++ b/docs/en/troubleshooting.html @@ -91,6 +91,7 @@

Side panel: Specified native messaging host not found.

The extension popup shows Connected only after a native-host reply. Until then it shows Connecting; failures show their concrete error. An older host can be confirmed by the first real CLI command. A confirmed host link does not prove every page is drivable.

A protected extension iframe can cause debugger_access_denied on an ordinary web tab. Chrome checks the frame tree before dispatching parent-page commands; disabling auto-attach or filtering child events cannot remove this restriction. The error lists the extensions that have frames open in the browser, with a chrome://extensions/?id= link for each; these are browser-wide candidates, not confirmed blockers of this tab. The CLI names candidates from local Chrome profiles in its Possible blocking extensions: line, selecting manifests by numeric version. Save work, disable the conflicting extension on this site and reload, or use a profile without it. Do not turn denied commands into successful empty replies or loop on reattachment. 1Password can keep a frame in a sign-in page with nothing shown, so there is no menu to close: on a tab the session created, --clear-extension-frames (or AGENT_BROWSER_CLEAR_EXTENSION_FRAMES=1; ab-connect 0.5.108+ with site access) has the extension remove other extensions' frames from that page from an isolated world, then repeats the command when that is harmless; that extension's widget returns after a reload or on the next page. Otherwise hand the step to the user in one command: session handoff --wait --note "<what to do>". Use tab inspect <ref> for metadata or a separate test profile. Development checks can set the same absolute CHROME_USE_RELAY_DIR in the native host and CLI, with unique sessions and an explicit --browser, to keep candidate relays out of shared discovery.

+

If the page command still fails, read data.extensionFrameCleanup.status and detail. They describe this invocation. A refused cleanup or an unconfirmed reply does not establish which extension owns the frame. Keep the form open, ask the user to close the extension menu or hide its autofill prompt for this site, then run snapshot -i on the same tab.

Native agent-panel configuration journals are also scoped by this directory; their default is ~/.chrome-use/agent-panel. Agent configuration paths remain separate: use the agent's own config-root variable and synthetic settings for write tests. Saving settings does not switch an existing session's model. Inspect current values after an unconfirmed apply or restore; restore preserves external changes and reports field conflicts.

Relay navigation makes up to three bounded access checks and ends the lifecycle wait early on a confirmed debugger access denial. Successful checks or transient errors are not treated as page readiness.

See Local agent side panel for supported agents, permission controls, the current-page tag and deletion scope. An unconfirmed send can be retried explicitly with its original ID; clearing the warning does not cancel possible delivery. Claude permissions remain pending until the matching tool result arrives. Custom programs require absolute paths.

diff --git a/docs/permissions.html b/docs/permissions.html index 5223173e35..aab1aade5c 100644 --- a/docs/permissions.html +++ b/docs/permissions.html @@ -82,6 +82,7 @@

什么时候会先问你

这些判断是启发式的:没走 ref 或选择器的输入(例如先聚焦再 keyboard type)、名称不像购买的支付按钮,可能不会被识别。它是一道让人看一眼的闸,不是沙箱。

--launch 和 --cdp 会话不带这些默认规则(那里通常没有人在看),只按你的策略文件执行。

+

填写普通输入框却收到支付确认时,确认原因可能会指出触发判断的属性或快照标签,以及匹配到的支付特征。反馈误判时附上这段原因即可,无需提交输入内容。

怎么批准

被拦下的命令不会执行,退出码为 3,并给出确认 ID:

diff --git a/docs/real-chrome.html b/docs/real-chrome.html index 7163794092..2a3f43fef8 100644 --- a/docs/real-chrome.html +++ b/docs/real-chrome.html @@ -175,7 +175,7 @@

多个 Chrome profile:看清是哪一个,然后选它

bash
-
# 列出所有已连接的 profile(有 identity 权限则显示邮箱,否则显示稳定 id,标注默认项)
+
# 列出磁盘上的 profile 和已连接的中继,可查看连接状态及默认项
 $ chrome-use browsers
 
 # 把「本次 session」钉到指定 profile —— 按 session 粘滞,不同 agent 互不干扰
@@ -218,8 +218,7 @@ 

让规则替你选:ChooseBrowser

只读,没装的话完全无感——没有规则文件就不改变任何行为、也不打提示。 规则是硬约束,chrome-use 不会把站点开到别的 profile 里。规则指向的 profile 没连上时, - 命令直接失败,并给出 chrome-use connect --browser <profile>(会在那个 profile - 里开一个窗口,先问用户)。当前 session 已经绑定在另一个 profile 上时,命令同样失败: + 命令直接失败,并给出 chrome-use connect --browser <profile>(可能会请求在该 profile 里打开窗口,先问用户)。当前 session 已经绑定在另一个 profile 上时,命令同样失败: 换一个新的 --session(它会选规则指定的 profile),或者加 --no-choosebrowser 在已绑定的 profile 里打开。显式 --browser 和配置文件里的路由仍然优先。这条检查同样覆盖 batch 的每一步(一个 batch 需要两个 profile 时,任何一步都不会执行)、MCP 工具调用和 script 步骤。 @@ -323,36 +322,27 @@

万一真弹出「是否允许远程调试?」

  1. - 扩展 / relay 没起来。 让用户装商店版扩展(上面那个一键链接);装好后 relay 会持续在线, - 这个弹窗再也不会回来。 + 扩展中继离线。 按下方步骤检查 Chrome、原生宿主注册和目标 profile。

-

relay 掉线:CLI 会自愈

-

- 如果某条命令突然报「couldn't reach your Chrome」/「relay … failed」——通常是 MV3 service worker 被挂起, - 或两个 agent 在共用一个 relay——CLI 现在会自愈:它会等 worker 的 keepalive 把 relay 拉活 - (约 25 秒)并重试一次,所以大多数掉线你根本感知不到。如果某条命令确实把错误抛出来了: -

+

扩展中继离线时如何排查

+

运行 chrome-use status 查看 Chrome 进程、原生宿主注册和实时中继状态,再用 + chrome-use browsers 找到目标 profile。即使 Chrome 已退出,磁盘上的 profile 仍会列在这里。

    -
  1. 直接重跑这条命令——到那会儿 relay 通常已经重连好了。
  2. -
  3. 还不行:chrome-use status(无需 daemon 的 CLI、扩展、中继、profile 与会话总览)→ chrome-use extension connect(重新 attach)→ 再重试。 - CLI 会自动注册原生宿主,如果扩展从没装过还会自己打开商店页面——你不用手动跑 extension install。
  4. -
  5. 绝不要让用户用 --remote-debugging-port 退出/重启 Chrome 来恢复掉线的 relay—— - 那会丢掉他们的所有标签页,也彻底破坏了扩展路径。
  6. -
  7. chrome-use reconnect 是 extension connect 的友好别名——无需任何重装, - 就把 session 重新绑定到运行中的 Chrome。
  8. -
  9. 浏览器完全恢复不了? 不要干等一张截图——退回到非视觉的验证方式: - get text / eval,或用 curl/WebFetch 读已部署的页面。 - 通过 DOM/HTML 或 live URL 确认一个改动是正确的结果,不是失败。截图留给你真正要报告给用户的视觉检查。
  10. +
  11. 如果 Chrome 未运行,打开目标 profile。如果命令无法判断进程状态,先确认 Chrome 是否在运行。
  12. +
  13. 如果原生宿主注册有误,或该 profile 的扩展弹窗显示 Not paired,运行 + chrome-use extension install --all-profiles,完全退出 Chrome,再打开目标 profile。
  14. +
  15. 如果扩展弹窗显示已配对,中继仍离线,重新打开弹窗,或在 chrome://extensions 重新加载 chrome-use。仅凭中继离线无法判断扩展 worker 是否休眠。
+

chrome-use connect --browser <profile> 可以请求打开窗口,默认最多等 120 秒,直到该 profile 的中继连上。 + 如果之前的写操作中断,先查看页面,确认是否需要重试。

✅ 不要为了躲「脆弱」而把 agent 串行化
- relay 掉线是短暂的、会自愈的,它不是共享浏览器无法并发驱动的信号。并发多 agent - 是被支持的——每个 --session 有自己的标签组、只驱动自己的标签页。 + 同一个浏览器支持多个 agent 并发工作——每个 --session 有自己的标签组、只驱动自己的标签页。 给每个 agent 一个不同的 --session 让它们并行跑,不用一个个来。
diff --git a/docs/troubleshooting.html b/docs/troubleshooting.html index 33263d030a..74f40bc3a8 100644 --- a/docs/troubleshooting.html +++ b/docs/troubleshooting.html @@ -89,6 +89,7 @@

侧栏报 Specified native messaging host not found.

扩展弹窗只在收到原生主机回应后显示 Connected。确认前为 Connecting,连接失败时显示具体错误。旧主机可由首次实际 CLI 命令确认连接;主机接通不代表所有页面都可驱动。

网页中的其他扩展 iframe 也可能导致 debugger_access_denied。Chrome 会在执行主页面命令前检查整个框架树;关闭 auto-attach 或过滤子框架事件无法解除这个限制。报错会列出当前浏览器里开着框架的其他扩展,每个都附 chrome://extensions/?id= 链接;这只是浏览器范围的候选列表,不能确认哪个属于被阻挡的标签页。CLI 会在 Possible blocking extensions: 行里按本机 Chrome profile 写出候选扩展的名字,按数字版本选择最新 manifest。先保存工作,再禁用该站点上注入框架的扩展并重新加载,或使用不含该扩展的独立 profile。不要把权限错误当作成功,也不要循环重连。1Password 会在登录页里放一个什么都不显示的隐藏框架,没有菜单可关;会话自己打开的标签页可以加 --clear-extension-frames(或 AGENT_BROWSER_CLEAR_EXTENSION_FRAMES=1,需要 ab-connect 0.5.108 及以上并开启站点访问),由扩展在隔离环境里把其他扩展的框架从这个页面移除,再在安全时重跑命令;该扩展的控件在重新加载或下一页时才会回来。不想这样做时,用一条命令交给用户并等待:session handoff --wait --note "<要用户做什么>"。使用 tab inspect <ref> 查看浏览器级状态,或选择独立测试 profile。开发验收可在原生主机和 CLI 中设置相同的绝对路径 CHROME_USE_RELAY_DIR,配合唯一 session 与明确的 --browser,避免把候选中继登记到共享目录。

+

页面命令仍被阻挡时,data.extensionFrameCleanup.status 和 detail 会说明本次调用是否执行清理,以及结果如何。无法清理或没有收到确认时,仍不能据此认定是哪款扩展。保留表单,请用户关闭扩展菜单或只在这个网站隐藏填充提示,再在原标签页运行 snapshot -i。

原生 agent 面板的配置记录也按该目录隔离,默认保存在 ~/.chrome-use/agent-panel。这不会改变 agent 自己的配置路径;测试写入需另设该 agent 的配置目录变量,并使用合成数据。已有会话不会因保存配置而切换模型。应用或恢复没有收到确认时,先读当前值;恢复会保留外部修改并报告字段冲突。

中继导航最多执行三次有时限的访问检查,确认 debugger 访问被拒绝时提前结束等待;成功检查或临时错误不会被当作页面已经就绪。

侧栏支持的 agent、权限开关、当前页面标签和删除范围见 本机 agent 侧栏。发送未获确认时,可明确选择用原消息 ID 重试;清除提示不会取消可能已送达的任务。Claude 授权需收到对应工具结果才算处理完成。自定义程序需填绝对路径。

diff --git a/skill-data/core/SKILL.md b/skill-data/core/SKILL.md index b34cbe4941..3675c2e937 100644 --- a/skill-data/core/SKILL.md +++ b/skill-data/core/SKILL.md @@ -122,7 +122,7 @@ waits for that choice, and your own `confirm` never approves it. | Reads, frames, shadow roots, screenshot crops | `core/reading` | | Waiting, scroll animations, observation limits | `core/waiting` | | Ref identity, snapshot detail | `core/snapshot-refs` | -| Diagnostics, profiles, launch, stealth | `core/connection` | +| Diagnose an offline Chrome profile (`status`, `browsers`), launch, stealth | `core/connection` | | Repeats, output and verification | `core/behaviour` | | Site adapters | `core/site-adapters` | | Teach a flow, replay without a model | `core/teach` | diff --git a/skill-data/core/references/commands.md b/skill-data/core/references/commands.md index cddba4b40a..d8c1d70f5f 100644 --- a/skill-data/core/references/commands.md +++ b/skill-data/core/references/commands.md @@ -969,9 +969,13 @@ chrome-use extension status # is the host installed? chrome-use extension uninstall # remove the host manifest ``` -`chrome-use status --json` reports native-host launcher health as -`data.extension.hostHealthy`, so a stale launcher is distinguishable from a -missing manifest or a disconnected relay. +In `chrome-use status --json`, `data.extension.browserProcess` is +`running`, `notRunning` or `unknown`. `data.extension.pairing` is +`connected` after an extension replies to diagnostics and `unverified` +otherwise. `hostInstalled` and `hostLauncherHealthy` (also exposed as +`hostHealthy`) describe the host configuration on disk. `chrome-use browsers --json` reports the process state +as `data.browserProcess`; a profile is connected when its relay endpoint +accepts a connection. Security: the extension↔host link is authenticated by Chrome (extension id); the host↔chrome-use CDP link uses an unguessable URL in a 0600 file. Use this when diff --git a/skill-data/core/references/connection.md b/skill-data/core/references/connection.md index d49264cfe3..36b2c98a1c 100644 --- a/skill-data/core/references/connection.md +++ b/skill-data/core/references/connection.md @@ -81,6 +81,15 @@ and tab cleanup on two local fixtures. Stop the Moli process when finished. `chrome-use status` reads extension state without a session daemon or debugger command. Stale relay files do not count as online. A healthy relay does not prove that an individual page renderer responds; verify the intended page separately. +For a disconnected profile, read the Chrome process state, native host +registration and live relay separately. If the process state is unknown, check +whether Chrome is open. If Chrome is stopped, open the target profile. +If the registration needs repair or its extension popup says **Not paired**, +run `chrome-use extension install --all-profiles`, fully quit Chrome, then +reopen the profile. A paired extension with no live relay may have an idle +worker. Open its popup or reload it at `chrome://extensions`, then check +`chrome-use browsers` again. + `status`, `extension status`, and doctor's relay check read `ABExt.state` over one diagnostic connection with a total 10-second budget. An error reply falls back to `ABExt.inspectTab` on that same connection. They send no debugger commands. The debugger summary passively counts answered commands (including non-timeout errors) and timeouts with “in the last 10 min” for a full reporting window, otherwise “since the extension worker started ago” (whole seconds below 120 seconds, such as “45s”; whole minutes otherwise, such as “3 min”). No samples means “not exercised”; an older extension without health data reports that explicitly. Counts use bounded one-second buckets and reset when the service worker restarts. If commands keep failing, reload the chrome-use extension at `chrome://extensions` or restart Chrome. New native hosts acknowledge diagnostic connections and skip `attachAll`. A still-running older host performs its usual `attachAll` once; the diagnostic notice recommends reloading the extension after upgrading to start the new host. Possible duplicate extensions are identified from sidecar identities and concurrent TCP liveness checks with a one-second limit and no WebSocket handshake. Matching account/browser with distinct extension ids does not prove a shared Chrome profile: disable one only if both are installed in the same profile. @@ -138,13 +147,12 @@ another the personal one. Pick the profile before the task, not after a login wa `auth login --bwu`). Do not switch to another profile. **Connecting another profile.** Only profiles running the extension are -connected; most people install it in one. `chrome-use connect --browser ` -connects one when it's needed. It opens the extension's Web Store page in that -profile, and the user clicks "Add to Chrome" once. If the extension is already -installed, it opens a window in that profile instead (the extension runs only -while the profile is open). If Chrome has it disabled, it opens its extensions -page. Then it waits for the relay. **It opens a window in the user's Chrome, so -ask the user before running it.** `--browser` naming an unconnected profile +connected. `chrome-use connect --browser ` requests a window in the +selected profile. If the extension is missing, the request opens its Web Store +page for the user to click "Add to Chrome". If it is disabled, the request +opens the extensions page. The CLI waits for that profile's relay before it +reports success. **This can open a window in the user's Chrome, so ask the +user before running it.** `--browser` naming an unconnected profile fails with exactly this command. **Defaults.** In `~/.chrome-use/config.json`: @@ -169,7 +177,7 @@ The profile line names the rule that chose. a different profile: - If the rule's profile is not connected, the command fails, naming the rule - and `chrome-use connect --browser ` (opens a window in that + and `chrome-use connect --browser ` (can open a window in that profile, so ask the user first). It does not fall through to `default` or the focused profile. - A running session never switches profiles. If it is bound to profile X and @@ -231,6 +239,15 @@ Reattaching does not help. To avoid it, fill those fields with `fill` rather tha `type --key-events`, turn the extension's inline menu off for the site, or use a `--launch` profile. +If a page command still reports `debugger_access_denied`, read +`data.extensionFrameCleanup.status` and `detail`. The status distinguishes +`not_requested`, `not_attempted`, and `not_applicable` from `none_removed`, +`still_blocked`, and `unconfirmed`. The `removed` status means Chrome accepted +a frame-tree read after removal; a later snapshot can still be denied. +Keep the form in its current tab. Ask the user to close the visible menu or +hide the extension's autofill prompt on that site, then resume with +`snapshot -i` in the same session. + Relay navigation makes up to three bounded access checks while waiting for a lifecycle event. A confirmed debugger access denial ends the wait early; a successful check or a transient failure does not substitute for page readiness. diff --git a/skill-data/core/references/trust-boundaries.md b/skill-data/core/references/trust-boundaries.md index ff7405f49f..99f3a242b6 100644 --- a/skill-data/core/references/trust-boundaries.md +++ b/skill-data/core/references/trust-boundaries.md @@ -126,6 +126,10 @@ default, so `auth login` and `fill --from-env` into a password field run). The c run; it prints `Confirmation required:` with a `Site:` line and a confirmation id, and exits with code 3 (`--json`: `confirmation_required`, `site`, `reason`, `approval`). +For a payment-field prompt on a resolved field, the reason can identify the +attribute or snapshot label and the kind of payment cue. In JSON this is in +`description`; the policy `reason` remains `payment_input`. That description +is sufficient to report a suspected misclassification. - `approval: user`: only the user can approve, in the chrome-use side panel, notification or options page (Allow once / Always allow on this site / diff --git a/skill-data/real-chrome/SKILL.md b/skill-data/real-chrome/SKILL.md index 078b20d926..06f049d80e 100644 --- a/skill-data/real-chrome/SKILL.md +++ b/skill-data/real-chrome/SKILL.md @@ -37,7 +37,7 @@ To write one back, add `--remember` alongside an explicit `--browser`: after the A matching rule is binding; chrome-use never substitutes another profile for the one it names. `open` / `goto` / `navigate` / `tab new ` fail with the fix when: -- the rule's profile is not connected — the error names the rule and `chrome-use connect --browser `. That opens a window in the user's Chrome, so **ask the user first**. +- the rule's profile is not connected — the error names the rule and `chrome-use connect --browser `. That can open a window in the user's Chrome, so **ask the user first**. - the session is already bound to a different profile — sessions never switch profiles. Use a new `--session ` (it picks the rule's profile), or pass `--no-choosebrowser` if the user wants the site in the bound profile anyway. An explicit `--browser` or a config route still wins over the rule. A rule whose profile no longer exists on this machine is ignored with a warning (`warning` in `--json`); tell the user the rule is stale rather than assuming the account is right. A rule whose key fits several profiles is refused. The check applies to `batch` steps (a batch needing two profiles is refused before anything runs), MCP tool calls and script steps too. `chrome-use doctor` lists each rule and whether its profile is connected. `click` and `snapshot` do not consult routing rules. @@ -53,8 +53,8 @@ isolated browser is fine. > whichever profile's extension worker is talking to the native host. If a site > comes back logged out, confirm it's the right profile before assuming the login > is gone: -> - `chrome-use browsers` — lists every connected profile (email if the ext has -> the optional `identity` permission, else a stable id; marks the default). +> - `chrome-use browsers` — lists profiles found on disk and connected relays. +> Check the connected and default columns for the profile you intend to use. > - `chrome-use --browser ` — pins THIS session to that profile. > It's **sticky per session** (the session's daemon binds on first connect), and > each session can pick a different profile, so concurrent agents don't fight. @@ -98,23 +98,27 @@ attempt re-pops it). One of two things is true: may be shadowing the upgraded one; remove the stale copy (`npm rm -g chrome-use` / `pnpm rm -g chrome-use`) so the `install.sh` build wins. A tool that bundles its *own* pinned copy needs that copy upgraded too. -2. **The extension/relay isn't live.** Tell the user to install the Store - extension (one click, above); after that the relay stays up and the dialog - never returns. - -**If the relay drops mid-session** (a command suddenly errors with "couldn't -reach your Chrome" / "relay … failed" — usually the MV3 service worker got -suspended, or two agents are sharing one relay): **the CLI self-heals** — it -waits for the worker's keepalive to revive the relay (~25s) and retries once, so -most drops you never even see. If a command *does* surface the error: - -1. **Just retry the command** — the relay has usually reconnected by then. -2. If it persists: `chrome-use status` (check), then `chrome-use extension connect` - (re-attach), then retry. The CLI auto-registers the native host and opens the - Web Store page itself if the extension was never set up — you don't run - `extension install` by hand. - `status` is daemon-free and reports CLI, live/expected extension, driving - profile, and current session state even when that session worker is stuck. +2. **The extension relay is offline.** Check the selected profile as follows. + +**Diagnose an offline relay.** Run `chrome-use status` for the Chrome process, +native host registration and live relay. Run `chrome-use browsers` to find +the target profile. A listed profile exists on disk or has a connected relay; +a missing selector is a separate error. A window request from +`chrome-use connect --browser ` can bring up the user's Chrome. +The command waits up to 120 seconds by default for the selected relay to connect. + +1. **Chrome stopped.** Open Chrome in the target profile. If the process state + is unknown, check whether Chrome is open. +2. **Host registration or pairing needs repair.** Check the extension popup + in that profile. If it says **Not paired**, or the host registration is + missing or unhealthy, run `chrome-use extension install --all-profiles`. + Fully quit Chrome, reopen that profile, then check `chrome-use browsers`. +3. **Paired, still offline.** Open the popup to wake the extension, or reload + it at `chrome://extensions`. Verify that the profile is connected before + resuming the session. An offline relay alone cannot identify a sleeping + worker. Check the page before repeating an action whose outcome is unknown. + +4. **Automatic recovery.** Browser commands normally require an open window in the selected Chrome profile. If its relay is down while Chrome is running and Local State does not list that profile as active, recovery first waits for the same profile to remain unlisted for 20 seconds. @@ -131,19 +135,20 @@ most drops you never even see. If a command *does* surface the error: instance on another data root is excluded. If recovery still cannot connect, follow the reported profile or relay error; do not restart Chrome merely because its relay is down. -3. **Never** tell the user to quit/restart Chrome with `--remote-debugging-port` - to recover a dropped relay — that throws away their tabs and defeats the - extension path. -4. `chrome-use reconnect` is a friendly alias for `extension connect` — re-binds - the session to the running Chrome without any reinstall. - -> **Don't serialize agents to dodge fragility.** Relay drops are transient and -> self-heal; they are *not* a sign that the shared browser can't be driven -> concurrently. Concurrent multi-agent **is** supported — each `--session` + +**Never** tell the user to quit/restart Chrome with `--remote-debugging-port` +to recover a dropped relay — that throws away their tabs and defeats the +extension path. + +`chrome-use reconnect` is a friendly alias for `extension connect` — re-binds +the session to the running Chrome without any reinstall. + +> Concurrent multi-agent use is supported — each `--session` > drives only its own tabs (sessions of one project share its tab group) (see *Strict multi-agent > isolation* below). Give each agent a distinct `--session` and let them run in > parallel; you don't need to run them one at a time. -5. **Can't restore the browser at all?** Don't stall waiting for a screenshot — + +**Can't restore the browser at all?** Don't stall waiting for a screenshot — **fall back to non-visual verification**: `get text` / `eval` / read the deployed page over `curl`/`WebFetch`. Confirming a change via the DOM/HTML or the live URL is a *correct* result, not a failure. Reserve screenshots for a From a3b7be11e66e33cb13de409494bbf3756c4d212a Mon Sep 17 00:00:00 2001 From: leo Date: Wed, 2 Dec 2026 16:52:51 +0900 Subject: [PATCH 2/5] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E5=AE=A1=E6=9F=A5?= =?UTF-8?q?=E8=A7=84=E5=88=99=E8=BE=93=E5=85=A5=E8=AF=AF=E6=8A=A5=E5=B9=B6?= =?UTF-8?q?=E5=A4=8D=E6=A0=B8=E5=BB=B6=E8=BF=9F=E5=87=BA=E7=8E=B0=E7=9A=84?= =?UTF-8?q?=E5=BC=B9=E7=AA=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- README.zh.md | 2 +- cli/src/native/actions.rs | 8 +- cli/src/native/browser.rs | 4 +- cli/src/native/clipboard_policy_tests.rs | 109 ++++++- cli/src/native/focus_restore.rs | 291 ++++++++++++++++-- cli/src/native/site_policy.rs | 56 +++- cli/src/output.rs | 2 +- docs/en/permissions.html | 2 +- docs/permissions.html | 2 +- .../core/references/trust-boundaries.md | 3 +- 11 files changed, 438 insertions(+), 43 deletions(-) diff --git a/README.md b/README.md index 899881a680..bd1624f0bd 100644 --- a/README.md +++ b/README.md @@ -738,7 +738,7 @@ Use independent detectors to evaluate fingerprints. [Botcheck](https://botcheck. ## Permissions & safety -When a field triggers payment confirmation during a fill, the reason can identify the field attribute and the kind of payment cue it matched. Include that reason when reporting a false positive. +The Smart Effort review prompt in Cursor accepts rules about security-related code changes. When a field triggers payment confirmation during a fill, the description can identify the field attribute and the kind of payment cue it matched. Include that reason when reporting a false positive. On your own Chrome, chrome-use checks every agent action against the site it lands on before running it. By default it asks you first on banking, brokerage, crypto exchange and government ID sites (a [maintained list](cli/src/native/sensitive_sites.json)), and before typing into payment card fields and purchases. Asking before password fields and downloads is off by default, since agents sign in and download on their own; turn it on per category. You answer in the side panel, its notification or the options page: **Allow once**, **Always allow on this site**, or **Decline**. The options page keeps the approved and blocked sites and a permission history. The gated command exits with code 3 and the agent runs `chrome-use confirm ` to wait for your choice. Turn the defaults off on the options page, with `CHROME_USE_SENSITIVE_SITES=0`, or in the `sites` block of an `--action-policy` file. Organizations can pin allowed and blocked domains, the action policy and disabled agents through Chrome enterprise policy (`chrome.storage.managed`). The check runs in the CLI, so pages see nothing new. See [Permissions & Safety](https://chrome-use.leeguoo.com/en/permissions.html). diff --git a/README.zh.md b/README.zh.md index cc04d2c03a..7c6209adc7 100644 --- a/README.zh.md +++ b/README.zh.md @@ -651,7 +651,7 @@ CDP 的 IME 路径会产生 composition 事件,但 Chrome 可能将 `compositi ## 权限与安全 -填写普通输入框却收到支付确认时,可以查看确认原因。若能定位触发来源,提示会写明字段属性和匹配到的支付特征,报告误判时可直接引用。 +Cursor 的 Smart Effort 可填写涉及安全代码变更的审查规则。填写普通输入框却收到支付确认时,可以查看确认说明。若能定位触发来源,提示会写明字段属性和匹配到的支付特征,报告误判时可直接引用。 驱动你自己的 Chrome 时,chrome-use 在执行每个 agent 操作前会按它落在的站点检查一次。默认情况下,在银行、券商、加密货币交易所和政府证件站点上(见[维护中的列表](cli/src/native/sensitive_sites.json)),以及在支付卡字段里输入、购买之前,会先问你。密码字段和下载默认不问(agent 经常自己登录和下载),可按类别打开。你在侧栏、通知或选项页里选择**仅允许这一次**、**始终允许此站点**或**拒绝**;选项页保存已允许和已屏蔽的站点以及权限记录。被拦下的命令以退出码 3 结束,agent 运行 `chrome-use confirm ` 等你选择。可以在选项页、用 `CHROME_USE_SENSITIVE_SITES=0`,或在 `--action-policy` 文件的 `sites` 段里关闭这些默认规则。组织可以通过 Chrome 企业策略(`chrome.storage.managed`)锁定允许和屏蔽的域名、操作策略和停用的 agent。检查在 CLI 里完成,页面看不到任何新东西。详见[权限与安全](https://chrome-use.leeguoo.com/permissions.html)。 diff --git a/cli/src/native/actions.rs b/cli/src/native/actions.rs index 1e02aae65d..2758a4ea2a 100644 --- a/cli/src/native/actions.rs +++ b/cli/src/native/actions.rs @@ -10142,7 +10142,7 @@ pub(crate) struct DeferredClickTabCheck { /// How long after a click a tab it opened is given to register before we /// look for it. -const CLICK_NEW_TAB_GRACE_MS: u64 = 150; +pub(super) const CLICK_NEW_TAB_GRACE_MS: u64 = 150; /// Where a click's pop-up guard goes (#468): the frame of the `@ref` being /// clicked (its own session for an out-of-process iframe), else the top frame @@ -27038,7 +27038,11 @@ async fn site_gate_kind( }; (source, entry.name.as_str()) }); - Ok(field_kind(&attrs, selector, label)) + let local_name = described + .pointer("/node/localName") + .and_then(Value::as_str) + .unwrap_or(""); + Ok(field_kind(local_name, &attrs, selector, label)) } "click" => { let name = entry.map(|e| e.name.as_str()).unwrap_or_else(|| { diff --git a/cli/src/native/browser.rs b/cli/src/native/browser.rs index 3cd894b177..5a5df5de2e 100644 --- a/cli/src/native/browser.rs +++ b/cli/src/native/browser.rs @@ -5950,12 +5950,14 @@ impl BrowserManager { // a user tab taken with `tab adopt`: its pop-up still raises // Chrome over the user's app. let mut ours = self.relay_own_chrome_tabs(); - ours.extend(self.active_session_id().ok().and_then(relay_chrome_tab_id)); + let clicked = self.active_session_id().ok().and_then(relay_chrome_tab_id); + ours.extend(clicked); relay_before.map(|b| { ( NewTabProbe::RelayTabs { before: b.tab_ids().clone(), ours, + clicked, }, None, ) diff --git a/cli/src/native/clipboard_policy_tests.rs b/cli/src/native/clipboard_policy_tests.rs index 9617b10a21..211cf9f1bd 100644 --- a/cli/src/native/clipboard_policy_tests.rs +++ b/cli/src/native/clipboard_policy_tests.rs @@ -106,7 +106,12 @@ async fn fixture_with_origin( "DOM.describeNode" if fields.contains_key(request["sessionId"].as_str().unwrap_or("")) => { - json!({"node":{"attributes":fields[request["sessionId"].as_str().unwrap()]}}) + let descriptor = &fields[request["sessionId"].as_str().unwrap()]; + if descriptor.is_object() { + json!({"node": descriptor}) + } else { + json!({"node":{"attributes": descriptor}}) + } } "Browser.getVersion" => json!({"product":"Chrome/156.0.0.0"}), _ => { @@ -615,6 +620,108 @@ async fn named_css_field_policy_reads_only_the_intended_renderer_in_both_directi } } +#[tokio::test] +async fn smart_effort_prompt_source_code_example_does_not_describe_a_payment_field() { + // #915: the deployed Bugbot component labels this textarea "New prompt"; + // its example talks about changing source code, not entering a card code. + let example = "Use high effort on PRs that touch billing and security code."; + let attrs = json!(["id", "bugbot-smart-mode-new-prompt", "placeholder", example]); + for (node, label, expected) in [ + ( + json!({"localName":"textarea","attributes":attrs}), + "New prompt", + None, + ), + ( + json!({"localName":"input","attributes":attrs}), + "New prompt", + Some("placeholder"), + ), + ( + json!({"attributes":attrs}), + "New prompt", + Some("placeholder"), + ), + ( + json!({"localName":"textarea","attributes":attrs}), + "Security code", + Some("snapshot label"), + ), + ( + json!({"localName":"textarea","attributes":["name","review-prompt","placeholder",example,"autocomplete","cc-csc"]}), + "New prompt", + Some("autocomplete"), + ), + ( + json!({"localName":"textarea","attributes":["name","review-prompt","placeholder","Enter the security code for your transaction."]}), + "New prompt", + Some("placeholder"), + ), + ( + json!({"localName":"textarea","attributes":["name","review-prompt","placeholder","PRs that modify security code: enter your security code here."]}), + "New prompt", + Some("placeholder"), + ), + ( + json!({"localName":"textarea","attributes":["name","review-prompt","placeholder","PRs that change CVV and security code."]}), + "New prompt", + Some("placeholder"), + ), + ( + json!({"localName":"textarea","attributes":["id","review-field","placeholder",example]}), + "New prompt", + Some("placeholder"), + ), + ( + json!({"localName":"textarea","attributes":["id","docsConfig","name","review-prompt","placeholder",example]}), + "New prompt", + Some("id"), + ), + ( + json!({"localName":"textarea","attributes":["aria-label","Review prompt","placeholder","Use high effort for pull requests which modify security code."]}), + "Review prompt", + None, + ), + ] { + let (mut state, server, commands, _mode) = fixture_with_fields( + field_policy(), + "fixture.test", + "once", + [("cb-tab-1".into(), node)].into_iter().collect(), + ) + .await; + state + .ref_map + .add("e1".into(), Some(41), "textbox", label, None); + let cmd = json!({"id":"prompt","action":"fill","selector":"@e1","value":"Review the payment code."}); + let gate = site_gate(&cmd, "fill", "prompt", &mut state).await; + match expected { + Some(source) => { + let data = &gate.unwrap()["data"]; + assert_eq!(data["reason"], "payment_input"); + assert!( + data["description"] + .as_str() + .unwrap() + .ends_with(&format!(" in {source})")), + "{data}" + ); + } + None => assert!(gate.is_none(), "{gate:?}"), + } + assert_eq!( + commands + .lock() + .unwrap() + .iter() + .filter(|r| r["method"] == "DOM.describeNode") + .count(), + 1 + ); + server.abort(); + } +} + #[tokio::test] async fn payment_approval_explains_the_rule_without_echoing_field_or_input_values() { let attrs = json!([ diff --git a/cli/src/native/focus_restore.rs b/cli/src/native/focus_restore.rs index 5ca8d402fb..81be9b47eb 100644 --- a/cli/src/native/focus_restore.rs +++ b/cli/src/native/focus_restore.rs @@ -43,6 +43,7 @@ //! Linux it depends on the window manager; the click says so. use std::collections::HashSet; +use std::future::Future; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; @@ -227,13 +228,14 @@ pub enum NewTabProbe { RelayTabs { before: HashSet, ours: HashSet, + clicked: Option, }, /// A browser the daemon launched: page target ids before the click. Targets(HashSet), } impl NewTabProbe { - async fn confirm_new_tab(&self, client: &CdpClient) -> Result<(), Reason> { + async fn confirm_new_tab(&self, client: &CdpClient, late: bool) -> Result<(), Reason> { let (method, params) = match self { Self::RelayTabs { .. } => ( "ABExt.call", @@ -249,15 +251,35 @@ impl NewTabProbe { .ok() .and_then(Result::ok) .ok_or(Reason::TabQueryUnavailable)?; - self.confirm_reply(&reply) + self.confirm_reply(&reply, late) } - fn confirm_reply(&self, reply: &Value) -> Result<(), Reason> { + fn confirm_reply(&self, reply: &Value, late: bool) -> Result<(), Reason> { let found = match self { - Self::RelayTabs { before, ours } => { + Self::RelayTabs { + before, + ours, + clicked, + } => { let tabs = reply["result"] .as_array() .ok_or(Reason::TabQueryUnavailable)?; + // A second look widens the time in which an unrelated tab can + // appear. Accept only the clicked tab's own child, still + // subject to the normal baseline and group ownership checks. + let mut excluded; + let before = if late { + let opener = clicked.ok_or(Reason::NoNewTab)?; + excluded = before.clone(); + excluded.extend( + tabs.iter() + .filter(|t| t["openerTabId"].as_i64() != Some(opener)) + .filter_map(|t| t["id"].as_i64()), + ); + &excluded + } else { + before + }; super::browser::relay_popup_candidate(tabs, before, ours).is_some() } Self::Targets(before) => { @@ -289,7 +311,7 @@ pub const TRACE_ENV: &str = "AGENT_BROWSER_FOCUS_TRACE"; impl Drop for FocusWatch { fn drop(&mut self) { - self.stop.store(true, std::sync::atomic::Ordering::Relaxed); + self.stop.store(true, std::sync::atomic::Ordering::Release); } } @@ -337,7 +359,23 @@ impl FocusWatch { if !platform::SUPPORTED { return Self::done(Status::Skipped(Reason::UnsupportedPlatform)); } - let Some(before) = platform::frontmost() else { + Self::arm_with( + client, + probe, + browser_pid, + platform::frontmost, + platform::activate, + ) + } + + fn arm_with> + Send + 'static>( + client: Arc, + probe: NewTabProbe, + browser_pid: Option, + frontmost: impl Fn() -> Option + Send + Sync + 'static, + activate: impl Fn(i32) -> F + Send + 'static, + ) -> Self { + let Some(before) = frontmost() else { return Self::done(Status::Skipped(Reason::FrontUnknown)); }; if is_browser(&before, browser_pid) { @@ -369,10 +407,11 @@ impl FocusWatch { } }; let mut seen_at: Option = None; + let mut observed_browser = None; let mut confirmed = false; let mut restored = false; loop { - if armed_at.elapsed() > WINDOW || stop.load(std::sync::atomic::Ordering::Relaxed) { + if armed_at.elapsed() >= WINDOW || stop.load(std::sync::atomic::Ordering::Relaxed) { if !restored { let reason = if seen_at.is_some() { Reason::WindowElapsed @@ -384,7 +423,7 @@ impl FocusWatch { note("watch ended".into()); return; } - let Some(front) = platform::frontmost() else { + let Some(front) = frontmost() else { tokio::time::sleep(POLL).await; continue; }; @@ -392,7 +431,9 @@ impl FocusWatch { tokio::time::sleep(POLL).await; continue; } - if !is_browser(&front, browser_pid) { + if !is_browser(&front, browser_pid) + || observed_browser.is_some_and(|pid| pid != front.pid) + { note(format!( "front is pid {} {}: not the browser", front.pid, @@ -405,6 +446,7 @@ impl FocusWatch { } return; } + observed_browser = Some(front.pid); let seen = *seen_at.get_or_insert_with(|| { note(format!( "browser in front: pid {} {}", @@ -413,8 +455,52 @@ impl FocusWatch { )); Instant::now() }); + let still_in_front = || { + if stop.load(std::sync::atomic::Ordering::Acquire) + || armed_at.elapsed() >= WINDOW + { + return Err(Reason::WindowElapsed); + } + let now = frontmost().ok_or(Reason::FrontUnknown)?; + (now.pid == front.pid) + .then_some(()) + .ok_or(Reason::UserMoved) + }; + let verify = async { + let first = probe.confirm_new_tab(&client, false).await; + if first != Err(Reason::NoNewTab) + || !matches!( + &probe, + NewTabProbe::RelayTabs { + clicked: Some(_), + .. + } + ) + { + return first; + } + note("new tab not listed yet; waiting for the clicked tab's opener".into()); + tokio::time::sleep(Duration::from_millis( + super::actions::CLICK_NEW_TAB_GRACE_MS, + )) + .await; + still_in_front()?; + probe.confirm_new_tab(&client, true).await + }; if !confirmed { - if let Err(reason) = probe.confirm_new_tab(&client).await { + tokio::pin!(verify); + let verdict = loop { + if let Err(reason) = still_in_front() { + break Err(reason); + } + tokio::select! { + biased; + _ = tokio::time::sleep_until((armed_at + WINDOW).into()) => break Err(Reason::WindowElapsed), + result = &mut verify => break result, + _ = tokio::time::sleep(POLL) => {} + } + }; + if let Err(reason) = verdict { note(reason.note()); set(Status::Skipped(reason)); return; @@ -422,14 +508,15 @@ impl FocusWatch { confirmed = true; note("new tab: true".into()); } - // Still the browser, still inside the window: put the app - // the user was in back in front. - if armed_at.elapsed() > WINDOW - || platform::frontmost().map(|f| f.pid) != Some(front.pid) - { - continue; + // The query could have completed just as the user moved or + // the click ended. Never admit an activation on stale evidence. + if let Err(reason) = still_in_front() { + if !restored { + set(Status::Skipped(reason)); + } + return; } - match platform::activate(before.pid).await { + match activate(before.pid).await { Ok(()) => { note("previous app in front again".into()); restored = true; @@ -709,11 +796,14 @@ mod tests { let new_page = json!({ "targetInfos": [ { "type": "page", "targetId": "A" }, { "type": "page", "targetId": "B" }] }); let probe = NewTabProbe::Targets(before); - assert_eq!(probe.confirm_reply(&only_old), Err(Reason::NoNewTab)); - assert_eq!(probe.confirm_reply(&new_worker), Err(Reason::NoNewTab)); - assert_eq!(probe.confirm_reply(&new_page), Ok(())); + assert_eq!(probe.confirm_reply(&only_old, false), Err(Reason::NoNewTab)); assert_eq!( - probe.confirm_reply(&json!({})), + probe.confirm_reply(&new_worker, false), + Err(Reason::NoNewTab) + ); + assert_eq!(probe.confirm_reply(&new_page, false), Ok(())); + assert_eq!( + probe.confirm_reply(&json!({}), false), Err(Reason::TabQueryUnavailable) ); } @@ -723,21 +813,174 @@ mod tests { let probe = NewTabProbe::RelayTabs { before: [1].into_iter().collect(), ours: [1].into_iter().collect(), + clicked: Some(1), }; assert_eq!( - probe.confirm_reply(&json!({})), + probe.confirm_reply(&json!({}), false), Err(Reason::TabQueryUnavailable) ); assert_eq!( - probe.confirm_reply(&json!({"result": [{"id": 1}]})), + probe.confirm_reply(&json!({"result": [{"id": 1}]}), false), Err(Reason::NoNewTab) ); assert_eq!( - probe.confirm_reply(&json!({"result": [{"id": 2, "openerTabId": 1}]})), + probe.confirm_reply(&json!({"result": [{"id": 2, "openerTabId": 1}]}), false), Ok(()) ); } + struct RelayWatchFixture { + watch: FocusWatch, + front: Arc, + reads: Arc, + activations: Arc>>, + } + + // Run the actual watch and read Chrome tab records over a loopback CDP + // socket. Only the macOS window-server calls are replaced. + async fn watch_before_popup(first: Value, second: Value) -> RelayWatchFixture { + use std::sync::atomic::{AtomicI32, AtomicUsize, Ordering::SeqCst}; + let reads = Arc::new(AtomicUsize::new(0)); + let queried = Arc::new(tokio::sync::Notify::new()); + let count = reads.clone(); + let first_read = queried.clone(); + let (endpoint, _) = super::super::browser::fake_cdp::start_with(move |req| { + assert_eq!(req["method"], "ABExt.call"); + assert_eq!(req["params"]["namespace"], "tabs"); + assert_eq!(req["params"]["method"], "query"); + if count.fetch_add(1, SeqCst) == 0 { + first_read.notify_one(); + first.clone() + } else { + second.clone() + } + }) + .await; + let client = Arc::new(CdpClient::connect(&endpoint).await.unwrap()); + let front = Arc::new(AtomicI32::new(1)); + let pid = front.clone(); + let read_app = move || { + let pid = pid.load(SeqCst); + let bundle = match pid { + 1 => "com.apple.Terminal", + 2 | 4 => "com.google.Chrome", + _ => "com.apple.finder", + }; + Some(App { + pid, + bundle_id: Some(bundle.to_string()), + }) + }; + let activations = Arc::new(Mutex::new(Vec::new())); + let activated = activations.clone(); + let current = front.clone(); + let watch = FocusWatch::arm_with( + client, + NewTabProbe::RelayTabs { + before: [10, 11, 20].into_iter().collect(), + ours: [10, 11].into_iter().collect(), + clicked: Some(10), + }, + None, + read_app, + move |pid| { + activated.lock().unwrap().push(pid); + current.store(pid, SeqCst); + std::future::ready(Ok(())) + }, + ); + front.store(2, SeqCst); + tokio::time::timeout(WINDOW, queried.notified()) + .await + .expect("Chrome came forward before the first tab query"); + RelayWatchFixture { + watch, + front, + reads, + activations, + } + } + + fn relay_tabs(new: &[Value]) -> Value { + let mut tabs = vec![ + json!({"id":10,"groupId":4}), + json!({"id":11,"groupId":4}), + json!({"id":20,"groupId":7}), + ]; + tabs.extend_from_slice(new); + json!({"result":tabs}) + } + + #[tokio::test] + async fn late_relay_popup_restores_only_for_the_clicked_opener() { + use std::sync::atomic::Ordering::SeqCst; + for (extra, restore) in [ + (vec![json!({"id":30,"openerTabId":10,"groupId":4})], true), + ( + vec![ + json!({"id":30,"groupId":4}), + json!({"id":31,"openerTabId":10}), + ], + true, + ), + (vec![json!({"id":30,"openerTabId":11,"groupId":4})], false), + (vec![json!({"id":30,"openerTabId":10,"groupId":7})], false), + (vec![json!({"id":30,"groupId":4})], false), + (vec![], false), + ] { + let f = watch_before_popup(relay_tabs(&[]), relay_tabs(&extra)).await; + let status = f.watch.settled(WINDOW).await; + assert_eq!(f.reads.load(SeqCst), 2); + if restore { + assert!(matches!(status, Status::Restored { .. }), "{status:?}"); + assert_eq!(*f.activations.lock().unwrap(), [1]); + } else { + assert_eq!(status, Status::Skipped(Reason::NoNewTab)); + assert!(f.activations.lock().unwrap().is_empty()); + } + } + } + + #[tokio::test] + async fn late_relay_popup_leaves_a_changed_foreground_and_cancellation_alone() { + use std::sync::atomic::Ordering::SeqCst; + let popup = relay_tabs(&[json!({"id":30,"openerTabId":10})]); + for next_pid in [1, 3, 4] { + let f = watch_before_popup(relay_tabs(&[]), popup.clone()).await; + f.front.store(next_pid, SeqCst); + assert_eq!( + f.watch.settled(WINDOW).await, + Status::Skipped(Reason::UserMoved) + ); + assert!(f.activations.lock().unwrap().is_empty()); + assert_eq!(f.reads.load(SeqCst), 1); + } + let f = watch_before_popup(relay_tabs(&[]), popup).await; + let status = f.watch.status.clone(); + drop(f.watch); + tokio::time::timeout(WINDOW, async { + while *status.lock().unwrap() == Status::Watching { + tokio::time::sleep(POLL).await; + } + }) + .await + .unwrap(); + assert!(f.activations.lock().unwrap().is_empty()); + assert_eq!(f.reads.load(SeqCst), 1); + } + + #[tokio::test] + async fn unreadable_relay_popup_list_is_not_retried() { + let f = + watch_before_popup(json!({}), relay_tabs(&[json!({"id":30,"openerTabId":10})])).await; + assert_eq!( + f.watch.settled(WINDOW).await, + Status::Skipped(Reason::TabQueryUnavailable) + ); + assert_eq!(f.reads.load(std::sync::atomic::Ordering::SeqCst), 1); + assert!(f.activations.lock().unwrap().is_empty()); + } + #[test] fn the_click_reports_what_happened() { let restored = Status::Restored { diff --git a/cli/src/native/site_policy.rs b/cli/src/native/site_policy.rs index 5d52f32bd0..502db9a062 100644 --- a/cli/src/native/site_policy.rs +++ b/cli/src/native/site_policy.rs @@ -168,7 +168,29 @@ impl SiteActionKind { } } -fn classify_field_text(parts: &[(&'static str, String)]) -> Option { +/// In a code-review prompt's example, "PRs that touch ... security code" +/// describes the source being changed. Remove only that grammatical phrase +/// when looking for this ambiguous marker. A second request to enter a +/// security code in the same placeholder still matches. +fn placeholder_requests_security_code(text: &str) -> bool { + static REVIEWED_CODE: OnceLock = OnceLock::new(); + let reviewed_code = REVIEWED_CODE.get_or_init(|| { + regex_lite::Regex::new(concat!( + r"\b(?:prs?|pull requests?)\s+(?:that|which)\s+", + r"(?:touch(?:es)?|changes?|modif(?:y|ies)|edits?|updates?)\s+", + r"(?:[a-z0-9_-]+\s+(?:and|or)\s+)*security code\b" + )) + .unwrap() + }); + reviewed_code + .replace_all(text, "\n") + .contains("security code") +} + +fn classify_field_text( + parts: &[(&'static str, String)], + prompt_textarea: bool, +) -> Option { let one_time_code = parts .iter() .any(|(_, t)| ONE_TIME_CODE_MARKERS.iter().any(|p| t.contains(p))); @@ -176,10 +198,15 @@ fn classify_field_text(parts: &[(&'static str, String)]) -> Option Option Option<&'static str> { - classify_field_text(&[("form map", text.to_lowercase())]).map(|m| m.name) + classify_field_text(&[("form map", text.to_lowercase())], false).map(|m| m.name) } #[cfg(test)] fn field_kind_from_attributes(attrs: &[String]) -> Option<&'static str> { - field_kind(attrs, "", ("snapshot label", "")).map(|m| m.name) + field_kind("", attrs, "", ("snapshot label", "")).map(|m| m.name) } /// Classify the typed-into node using its DOM attributes, selector and snapshot /// label. An OTP marker anywhere suppresses ambiguous card security-code terms /// (#846); explicit card markers and card autocomplete still take precedence. pub fn field_kind( + local_name: &str, attrs: &[String], selector: &str, (label_source, label): (&'static str, &str), @@ -252,7 +280,13 @@ pub fn field_kind( // Prefer the node's own static attributes when more than one source matches. parts.push((label_source, label.to_lowercase())); parts.push(("selector", selector.to_lowercase())); - classify_field_text(&parts) + // The control must independently identify itself as a multiline prompt. + // A placeholder, selector or inferred snapshot label alone is insufficient. + let prompt_textarea = local_name == "textarea" + && parts.iter().any(|(source, text)| { + matches!(*source, "id" | "name" | "aria-label") && has_word(text, "prompt") + }); + classify_field_text(&parts, prompt_textarea) .or_else(|| password.then_some(SiteActionKind::new("password_input"))) } @@ -889,7 +923,7 @@ mod tests { fn payment_field_explanation_names_the_source_and_rule_with_existing_precedence() { let classify = |attrs: &[&str], selector: &str, label: &str| { let attrs: Vec<_> = attrs.iter().map(|s| (*s).into()).collect(); - field_kind(&attrs, selector, ("snapshot label", label)) + field_kind("", &attrs, selector, ("snapshot label", label)) }; assert_eq!(classify(&["name", "rule"], "@e1", "New prompt"), None); assert_eq!( @@ -998,6 +1032,7 @@ mod tests { ); assert_eq!( field_kind( + "", &attrs(&[("autocomplete", "one-time-code")]), "", ("snapshot label", "Security code") @@ -1007,6 +1042,7 @@ mod tests { ); assert_eq!( field_kind( + "", &attrs(&[("maxlength", "6")]), "", ("snapshot label", "安全码") @@ -1023,6 +1059,7 @@ mod tests { assert_eq!(field_kind_from_text("安全码"), Some("payment_input")); assert_eq!( field_kind( + "", &attrs(&[("autocomplete", "cc-csc")]), "", ("snapshot label", "one-time code") @@ -1032,6 +1069,7 @@ mod tests { ); assert_eq!( field_kind( + "", &attrs(&[("maxlength", "6"), ("name", "cvv")]), "", ("snapshot label", "") diff --git a/cli/src/output.rs b/cli/src/output.rs index 2b94320117..4f0d549dc7 100644 --- a/cli/src/output.rs +++ b/cli/src/output.rs @@ -5247,7 +5247,7 @@ default; password fields and downloads when turned on; see "Permissions & safety" in the docs), the action returns a confirmation_required response with a confirmation ID instead of running. Use confirm/deny to approve or reject it. -When a field triggers payment confirmation, its reason can name the field +When a field triggers payment confirmation, its description can name the field attribute and the kind of payment cue. Include the reason in a false-positive report. When the response says `approval: user`, the request is waiting in the diff --git a/docs/en/permissions.html b/docs/en/permissions.html index 87888a9315..ae13889352 100644 --- a/docs/en/permissions.html +++ b/docs/en/permissions.html @@ -82,7 +82,7 @@

When chrome-use asks first

The detection is heuristic. Typing without a ref or selector (focus, then keyboard type) or a pay button with an unusual name can slip through. It is a gate for a person to look, not a sandbox.

--launch and --cdp sessions do not get these defaults (usually nobody is watching there). They follow your policy file only.

-

If an ordinary field triggers payment confirmation during a fill, the reason can identify the attribute or snapshot label that matched a payment cue. Include the reason in your report. Keep the entered text private.

+

Cursor’s Smart Effort rule editor accepts review instructions about changes to security code. If an ordinary field triggers payment confirmation during a fill, the description can identify the attribute or snapshot label that matched a payment cue. Include the reason in your report. Keep the entered text private.

Approving

A gated command does not run. It exits with code 3 and prints a confirmation id:

diff --git a/docs/permissions.html b/docs/permissions.html index aab1aade5c..e9c296119f 100644 --- a/docs/permissions.html +++ b/docs/permissions.html @@ -82,7 +82,7 @@

什么时候会先问你

这些判断是启发式的:没走 ref 或选择器的输入(例如先聚焦再 keyboard type)、名称不像购买的支付按钮,可能不会被识别。它是一道让人看一眼的闸,不是沙箱。

--launch 和 --cdp 会话不带这些默认规则(那里通常没有人在看),只按你的策略文件执行。

-

填写普通输入框却收到支付确认时,确认原因可能会指出触发判断的属性或快照标签,以及匹配到的支付特征。反馈误判时附上这段原因即可,无需提交输入内容。

+

Cursor 的 Smart Effort 支持填写与安全代码变更有关的审查规则。填写普通输入框却收到支付确认时,确认说明可能会指出触发判断的属性或快照标签,以及匹配到的支付特征。反馈误判时附上这段原因即可,无需提交输入内容。

怎么批准

被拦下的命令不会执行,退出码为 3,并给出确认 ID:

diff --git a/skill-data/core/references/trust-boundaries.md b/skill-data/core/references/trust-boundaries.md index 99f3a242b6..0af93aaaae 100644 --- a/skill-data/core/references/trust-boundaries.md +++ b/skill-data/core/references/trust-boundaries.md @@ -126,7 +126,8 @@ default, so `auth login` and `fill --from-env` into a password field run). The c run; it prints `Confirmation required:` with a `Site:` line and a confirmation id, and exits with code 3 (`--json`: `confirmation_required`, `site`, `reason`, `approval`). -For a payment-field prompt on a resolved field, the reason can identify the +Cursor’s Smart Effort rule editor can describe a PR touching security code in +its example text. For a payment-field prompt on a resolved field, the description can identify the attribute or snapshot label and the kind of payment cue. In JSON this is in `description`; the policy `reason` remains `payment_input`. That description is sufficient to report a suspected misclassification. From a80704c9903184975663beb79cda3290e94f1799 Mon Sep 17 00:00:00 2001 From: leo Date: Wed, 2 Dec 2026 17:18:58 +0900 Subject: [PATCH 3/5] =?UTF-8?q?fix(connect):=20=E9=99=90=E5=88=B6=E8=AF=8A?= =?UTF-8?q?=E6=96=AD=E7=AD=89=E5=BE=85=E5=B9=B6=E5=A4=8D=E7=94=A8=E5=B7=B2?= =?UTF-8?q?=E6=9C=89=E7=9B=91=E5=90=AC=E7=AB=AF=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 6 + README.zh.md | 5 +- cli/src/connect.rs | 14 +- cli/src/native/focus_restore.rs | 2 +- cli/src/output.rs | 16 +- cli/src/profiles.rs | 248 +++++++++++++---------- cli/tests/relay_diagnostics.rs | 82 +++++++- docs/commands.html | 2 +- docs/en/commands.html | 2 +- docs/en/real-chrome.html | 1 + docs/real-chrome.html | 1 + skill-data/core/references/commands.md | 10 +- skill-data/core/references/connection.md | 2 + skill-data/real-chrome/SKILL.md | 4 +- 14 files changed, 278 insertions(+), 117 deletions(-) diff --git a/README.md b/README.md index bd1624f0bd..dd1affc855 100644 --- a/README.md +++ b/README.md @@ -500,6 +500,12 @@ Chrome keeps the discarded tabs. Older relays without `ABExt.inspectTab` rely on Tab creation, selection, and adoption stay in the background by default. On macOS, a page that opens a tab itself can briefly bring Chrome to the front. The click reports `focusRestored` and, when restoration is unconfirmed, a `focusNote`. +If Chrome appears before the relay lists the popup, chrome-use checks once more +after 150 ms. On that check, the popup must name the clicked tab as its opener. +For a read-only link with an ordinary `href`, `click @ref --new-tab` opens the +destination in a background tab and skips the page’s click handler. In a +same-origin loopback test on Chrome 155, the first request carried the +`SameSite=Strict` session cookie and the source tab stayed selected. `--activate` (alias `--front`) and `bringToFront` are the explicit exceptions: they change the visible tab, focus that Chrome window and leave the tab in the foreground, so agents are told to use them only when you ask. If new-tab initialization diff --git a/README.zh.md b/README.zh.md index 7c6209adc7..9a122c1a00 100644 --- a/README.zh.md +++ b/README.zh.md @@ -471,7 +471,10 @@ JSON 健康摘要只包含 `transportResponsive`、`hostDiagnostic`、`nativeHos 并从新标签读取页面地址确认加载结果。原标签会保留。缺少 `ABExt.inspectTab` 的旧扩展依赖缓存,仍可能复用已回收的标签。 新建、选择与接管标签默认在后台进行。在 macOS 上,网页自行打开标签时,Chrome 可能短暂切到前台。 -点击结果的 `focusRestored` 表示是否已确认恢复焦点;未确认时可查看 `focusNote`。 +点击结果的 `focusRestored` 表示是否已确认恢复焦点,未确认时可查看 `focusNote`。 +如果 Chrome 已到前台、扩展还没列出弹窗,chrome-use 会等 150 毫秒再查一次。新弹窗明确来自刚点击的标签页时,才会切回原应用。 +只想读取普通 `href` 链接时,`click @ref --new-tab` 会在后台打开目标地址,跳过页面的点击处理函数。 +在 Chrome 155 的回环同源测试里,首次请求带上了 `SameSite=Strict` 会话 cookie,原标签页仍被选中。 `--activate`(别名 `--front`)和 `bringToFront` 是显式的例外:它们会切换可见标签、 聚焦那个 Chrome 窗口并让目标保持在前台,所以 agent 只在你要求时才用。新标签初始化失败后, chrome-use 会保留该标签并报告目标 ID。保持相同 session 和连接端点,执行 diff --git a/cli/src/connect.rs b/cli/src/connect.rs index f8e13d6ed0..366846b67a 100644 --- a/cli/src/connect.rs +++ b/cli/src/connect.rs @@ -4179,13 +4179,17 @@ pub fn relay_health() -> RelayHealth { /// The same snapshot for one relay endpoint: a profile picked with /// `--browser` (#910), not whichever host wrote the generic sidecar last. pub fn relay_health_at(url: &str) -> RelayHealth { + relay_health_within(url, std::time::Duration::from_secs(10)) +} + +pub(crate) fn relay_health_within(url: &str, budget: std::time::Duration) -> RelayHealth { let Ok(runtime) = tokio::runtime::Builder::new_current_thread() .enable_all() .build() else { return RelayHealth::default(); }; - runtime.block_on(probe_relay_health(url, std::time::Duration::from_secs(10))) + runtime.block_on(probe_relay_health(url, budget)) } /// What to do about a profile relay that refuses connections (#910): its @@ -4204,7 +4208,12 @@ pub const REFUSED_RELAY_FIX: &str = "Its native host has stopped and ab-connect /// died, so its existence alone is not "connected" (#910). Blocking and /// runtime-free, so sync callers inside or outside tokio can use it. pub fn relay_endpoint_accepts(url: &str) -> bool { + relay_endpoint_accepts_within(url, std::time::Duration::from_secs(1)) +} + +pub(crate) fn relay_endpoint_accepts_within(url: &str, budget: std::time::Duration) -> bool { use std::net::ToSocketAddrs; + let start = std::time::Instant::now(); let Ok(uri) = url.parse::() else { return false; }; @@ -4220,7 +4229,8 @@ pub fn relay_endpoint_accepts(url: &str) -> bool { return false; }; addrs.into_iter().any(|addr| { - std::net::TcpStream::connect_timeout(&addr, std::time::Duration::from_secs(1)).is_ok() + let left = budget.saturating_sub(start.elapsed()); + !left.is_zero() && std::net::TcpStream::connect_timeout(&addr, left).is_ok() }) } diff --git a/cli/src/native/focus_restore.rs b/cli/src/native/focus_restore.rs index 81be9b47eb..8b349aa09b 100644 --- a/cli/src/native/focus_restore.rs +++ b/cli/src/native/focus_restore.rs @@ -479,7 +479,7 @@ impl FocusWatch { { return first; } - note("new tab not listed yet; waiting for the clicked tab's opener".into()); + note("new tab not listed yet; waiting for a popup from the clicked tab".into()); tokio::time::sleep(Duration::from_millis( super::actions::CLICK_NEW_TAB_GRACE_MS, )) diff --git a/cli/src/output.rs b/cli/src/output.rs index 4f0d549dc7..b7d135593e 100644 --- a/cli/src/output.rs +++ b/cli/src/output.rs @@ -3121,8 +3121,13 @@ before, never when Chrome was already the frontmost app or another app came to the front. The click reports focusRestored (true with focusRestoredApp and focusRestoredAfterMs, or false with focusNote saying why, also printed as "focus not restored: ..." without --json). The note distinguishes an unreadable -tab list from a completed check that found no new tab. Windows and Linux: -not done. AGENT_BROWSER_RESTORE_FOCUS=0 turns it off (read when the daemon +tab list from a completed check that found no new tab. If the relay's first +list has no attributable tab, a second check after 150 ms requires the clicked +tab as opener, within the same 1.5 s window. For a plain href, click @ref +--new-tab opens the URL directly and skips the page's click handler. In a +Chrome 155 same-origin loopback test its first request sent a SameSite=Strict +session cookie and the source tab stayed selected. Focus restoration is macOS +only. AGENT_BROWSER_RESTORE_FOCUS=0 turns it off (read when the daemon starts). AGENT_BROWSER_BACKGROUND_LINKS=cross-site (also `1`/`on`; the default while @@ -5892,16 +5897,17 @@ Examples: // === Browsers (Chrome profiles) === "browsers" => { r##" -chrome-use browsers - Chrome profiles on this machine and which are connected +chrome-use browsers - Chrome profiles on this machine and their relay listeners Usage: chrome-use browsers [--json] chrome-use browsers --who [--json] Lists every profile in Chrome's Local State: display name, directory, signed-in -account, whether its extension relay is connected, which one is the default +account, whether its relay port accepts connections, which one is the default without --browser, and which one this --session uses. Unconnected rows show the -command that connects them. A profile listed on disk can have no live relay. +command that connects them. Use status to confirm an extension reply. connect +waits on an existing listener without requesting an additional window. Check Chrome's process state before opening a window or checking pairing in that profile's extension popup. diff --git a/cli/src/profiles.rs b/cli/src/profiles.rs index 6c8f016883..a2780f74bb 100644 --- a/cli/src/profiles.rs +++ b/cli/src/profiles.rs @@ -13,6 +13,7 @@ use crate::color; use crate::connect::{self, ChromeProfileInfo}; use serde_json::{json, Value}; use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant}; /// One Chrome profile, as `Local State` and the relay together describe it. /// A relay with no matching `Local State` entry (e.g. Chrome's data root is in @@ -50,7 +51,7 @@ impl ProfileRow { fn connection_label(&self, process: connect::ChromeProcess) -> &'static str { if self.connected() { - "yes" + "yes (pairing unverified)" } else if self.extension_disabled { "no (disabled)" } else if process == connect::ChromeProcess::NotRunning { @@ -272,6 +273,14 @@ pub enum Match { /// is exactly one — the same email signed in to three profiles, one of which /// runs the extension, kept working before this matcher knew the other two. pub fn match_selector(rows: &[ProfileRow], selector: &str) -> Match { + match_selector_with_relay_preference(rows, selector, true) +} + +fn match_selector_with_relay_preference( + rows: &[ProfileRow], + selector: &str, + prefer_live: bool, +) -> Match { let sel = selector.trim(); if sel.is_empty() { return Match::None; @@ -290,7 +299,7 @@ pub fn match_selector(rows: &[ProfileRow], selector: &str) -> Match { 0 => None, 1 => Some(Match::One(c[0])), _ => { - if prefer_connected { + if prefer_connected && prefer_live { let live: Vec = c.iter().copied().filter(|&i| rows[i].connected()).collect(); if live.len() == 1 { @@ -1190,6 +1199,7 @@ pub fn run_browsers(args: &[String], session: &str, json_out: bool) { let mut v = r.to_json(); v["wsUrl"] = json!(r.ws); v["relayAccepts"] = json!(r.relay_accepts); + v["pairing"] = json!("unverified"); v["default"] = json!(default == Some(i)); v["session"] = json!(in_session(r)); if !r.connected() { @@ -1230,7 +1240,7 @@ pub fn run_browsers(args: &[String], session: &str, json_out: bool) { "PROFILE", "DIR", "ACCOUNT", - "CONNECTED", + "RELAY LISTENER", "DEFAULT", "SESSION", "", @@ -1526,6 +1536,8 @@ fn run_who(domain: &str, json_out: bool) { }; out.push(json!({ "profile": r.to_json(), + "relayAccepts": r.relay_accepts, + "pairing": "unverified", "state": state, "cookieNames": cookies, "error": error, @@ -1546,7 +1558,12 @@ fn run_who(domain: &str, json_out: bool) { } lines.push([ r.label(), - if r.connected() { "yes" } else { "no" }.to_string(), + if r.connected() { + "yes (pairing unverified)" + } else { + "no" + } + .to_string(), state.to_string(), detail, ]); @@ -1562,7 +1579,7 @@ fn run_who(domain: &str, json_out: bool) { println!("no Chrome profiles found on this machine."); return; } - let header = ["PROFILE", "CONNECTED", domain.as_str(), "COOKIE NAMES"]; + let header = ["PROFILE", "RELAY LISTENER", domain.as_str(), "COOKIE NAMES"]; let mut w = [0usize; 3]; for (c, wc) in w.iter_mut().enumerate() { *wc = lines @@ -1601,16 +1618,6 @@ fn run_who(domain: &str, json_out: bool) { // --- `chrome-use connect --browser ` --------------------------------- -/// A TCP listener is enough for the inventory, but connect waits for an -/// extension protocol reply before reporting that this profile can be used. -fn responsive_profile(row: &ProfileRow) -> bool { - row.connected() - && row - .ws - .as_deref() - .is_some_and(|url| connect::relay_health_at(url).transport_responsive) -} - fn connect_timeout_hint(action: &str) -> &'static str { match action { "store" => "Check that Add to Chrome completed in that profile.", @@ -1619,75 +1626,26 @@ fn connect_timeout_hint(action: &str) -> &'static str { } } -/// Connect one more profile, lazily: open the Web Store page in that profile -/// (one click: "Add to Chrome"), or — if the extension is already there — -/// request a window and wait for the extension to answer on its relay. -pub fn run_connect_profile(selector: &str, args: &[String], json_out: bool) { - let wait_secs: u64 = args - .iter() - .position(|a| a == "--wait") - .and_then(|i| args.get(i + 1)) - .and_then(|v| v.parse().ok()) - .unwrap_or(120); - let rows = load_listening_rows(); - let i = match resolve_in(&rows, selector) { - Ok(i) => i, - Err(e) => { - fail(json_out, &e); - return; - } - }; - let row = rows[i].clone(); - let done = |row: &ProfileRow, already: bool| { - if json_out { - println!( - "{}", - json!({"success": true, "data": {"connected": true, "alreadyConnected": already, "profile": row.to_json()}}) - ); - } else if already { - println!( - "{} {} is already connected — use --browser {}", - color::success_indicator(), - row.label(), - shell_quote(selector.trim()) - ); - } else { - println!( - "{} connected {} — use --browser {}", - color::success_indicator(), - row.label(), - shell_quote(selector.trim()) - ); - } - }; - if responsive_profile(&row) { - done(&row, true); - return; - } +fn request_connect_window(row: &ProfileRow) -> Result<(&'static str, String), String> { let local = connect::chrome_profiles() .into_iter() .find(|p| Some(&p.dir) == row.dir.as_ref() && Some(&p.root) == row.root.as_ref()); let Some(local) = local else { - fail( - json_out, - &format!( - "can't find {} on disk — open it in Chrome yourself, then re-run.", - row.label() - ), - ); - return; + return Err(format!( + "can't find {} on disk — open it in Chrome yourself, then re-run.", + row.label() + )); }; // The relay needs the native-messaging host; registering it is idempotent // and touches no browser state, so do it rather than describe it. connect::ensure_host_installed(); let host = connect::native_host_report(); if host.manifests.is_empty() || !host.is_healthy() { - fail( - json_out, + return Err( "the native-messaging host isn't registered correctly, so no profile can connect — \ - run `chrome-use extension connect` (or `chrome-use doctor`) first.", + run `chrome-use extension connect` (or `chrome-use doctor`) first." + .into(), ); - return; } let (opened, action, told) = match &local.extension { @@ -1726,42 +1684,123 @@ pub fn run_connect_profile(selector: &str, args: &[String], json_out: bool) { "store" => format!("open {} in that profile", connect::STORE_URL), _ => "open that profile from Chrome's profile menu".to_string(), }; - fail( - json_out, - &format!( - "couldn't request a Chrome window in {} — {manual}, then re-run.", - row.label() - ), - ); - return; + return Err(format!( + "couldn't request a Chrome window in {} — {manual}, then re-run.", + row.label() + )); } - if !json_out { - eprintln!("{told}"); - eprint!("waiting up to {wait_secs}s for the extension relay to respond "); + Ok((action, told)) +} + +/// Connect one more profile, lazily: open the Web Store page in that profile +/// (one click: "Add to Chrome"), or — if the extension is already there — +/// request a window and wait for the extension to answer on its relay. +pub fn run_connect_profile(selector: &str, args: &[String], json_out: bool) { + let wait_secs: u64 = args + .iter() + .position(|a| a == "--wait") + .and_then(|i| args.get(i + 1)) + .and_then(|v| v.parse().ok()) + .unwrap_or(120); + // Even --wait 0 makes one quick protocol check on an existing listener. + // Positive waits share one deadline across selection, probes and poll sleeps. + let mut rows = load_rows(); + let started = Instant::now(); + let budget = if wait_secs == 0 { + Duration::from_millis(250) + } else { + Duration::from_secs(wait_secs) + }; + let remaining = || budget.saturating_sub(started.elapsed()); + // Only matching candidates need TCP liveness for the existing tie-break. + let candidates = match match_selector_with_relay_preference(&rows, selector, false) { + Match::One(i) => vec![i], + Match::Ambiguous(indices) => indices, + Match::None => vec![], + }; + for i in candidates { + rows[i].relay_accepts = rows[i].ws.as_deref().map(|url| { + connect::relay_endpoint_accepts_within(url, remaining().min(Duration::from_secs(1))) + }); } - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(wait_secs); + let i = match resolve_in(&rows, selector) { + Ok(i) => i, + Err(e) => { + fail(json_out, &e); + return; + } + }; + let row = rows[i].clone(); + let listener = row.relay_accepts == Some(true); + let done = |row: &ProfileRow, already: bool| { + if json_out { + println!( + "{}", + json!({"success": true, "data": {"connected": true, "alreadyConnected": already, "windowRequested": !listener, "profile": row.to_json()}}) + ); + } else if already { + println!( + "{} {} is already connected — use --browser {}", + color::success_indicator(), + row.label(), + shell_quote(selector.trim()) + ); + } else { + println!( + "{} connected {} — use --browser {}", + color::success_indicator(), + row.label(), + shell_quote(selector.trim()) + ); + } + }; + let action = if listener { + "wait-relay" + } else { + match request_connect_window(&row) { + Ok((action, told)) => { + if !json_out { + eprintln!("{told}"); + } + action + } + Err(error) => { + fail(json_out, &error); + return; + } + } + }; + let mut first = true; loop { - if let Some(now) = load_rows() - .into_iter() - .find(|r| r.same_profile(&row) && responsive_profile(r)) - { - if !json_out { - eprintln!(); + let current = if first && listener { + Some(row.clone()) + } else { + load_rows().into_iter().find(|r| r.same_profile(&row)) + }; + if let Some(now) = current { + let left = remaining().min(Duration::from_secs(10)); + if !left.is_zero() + && now + .ws + .as_deref() + .is_some_and(|url| connect::relay_health_within(url, left).transport_responsive) + { + done(&now, listener && first); + return; } - done(&now, false); - return; } - if std::time::Instant::now() >= deadline { + let left = remaining(); + if wait_secs == 0 || left.is_zero() { break; } - if !json_out { - eprint!("."); - let _ = std::io::Write::flush(&mut std::io::stderr()); + if first && !json_out { + eprintln!("Waiting up to {wait_secs}s for the extension relay to respond."); + } + first = false; + std::thread::sleep(left.min(budget / 4).min(Duration::from_millis(1500))); + if remaining().is_zero() { + break; } - std::thread::sleep(std::time::Duration::from_millis(1500)); - } - if !json_out { - eprintln!(); } let process = connect::observed_chrome_process(false); let start = if process == connect::ChromeProcess::NotRunning { @@ -1769,8 +1808,13 @@ pub fn run_connect_profile(selector: &str, args: &[String], json_out: bool) { } else { "" }; + let listener_note = if listener { + " The relay port accepted a connection; no additional window was requested." + } else { + "" + }; let msg = format!( - "No extension relay responded for {} within {wait_secs}s. Chrome process: {}.{start} {} Re-run `{}`.", + "No extension relay responded for {} within {wait_secs}s.{listener_note} Chrome process: {}.{start} {} Re-run `{}`.", row.label(), process.label(), connect_timeout_hint(action), connect_command(selector.trim()) ); if json_out { @@ -1778,7 +1822,7 @@ pub fn run_connect_profile(selector: &str, args: &[String], json_out: bool) { profile["connected"] = false.into(); println!( "{}", - json!({"success": false, "error": msg, "data": {"connected": false, "windowRequested": true, "browserProcess": process, "action": action, "profile": profile}}) + json!({"success": false, "error": msg, "data": {"connected": false, "windowRequested": !listener, "relayAccepts": row.relay_accepts, "pairing": "unverified", "browserProcess": process, "action": action, "profile": profile}}) ); } else { eprintln!("{} {msg}", color::error_indicator()); diff --git a/cli/tests/relay_diagnostics.rs b/cli/tests/relay_diagnostics.rs index 8d42f50923..c940e06b7f 100644 --- a/cli/tests/relay_diagnostics.rs +++ b/cli/tests/relay_diagnostics.rs @@ -1,7 +1,14 @@ //! Exercise offline CLI diagnostics without a real browser, user profile or daemon. #![cfg(any(target_os = "macos", target_os = "linux"))] use serde_json::{json, Value}; -use std::{fs, os::unix::fs::PermissionsExt, path::Path, process::Command}; +use std::{ + fs, + net::TcpListener, + os::unix::fs::PermissionsExt, + path::Path, + process::Command, + time::{Duration, Instant}, +}; fn shim(path: &Path, content: &str) { fs::write(path, content).unwrap(); @@ -19,7 +26,10 @@ fn offline_profiles_report_process_host_and_listener_separately() { // No system commands on PATH; even the window request is a local no-op. shim(&bin.join("pgrep"), "#!/bin/sh\n[ \"$TEST_PROCESS\" = unknown ] && exit 2\ncase \"$2\" in launchd|chrome-use) echo 1;; 'Google Chrome'|chrome) [ \"$TEST_PROCESS\" = running ] || exit 1; echo 42;; *) exit 1;; esac\n"); for name in ["open", "google-chrome"] { - shim(&bin.join(name), "#!/bin/sh\nexit 0\n"); + shim( + &bin.join(name), + "#!/bin/sh\necho request >> \"$HOME/window-requests\"\n", + ); } #[cfg(target_os = "macos")] let root = home.join("Library/Application Support/Google/Chrome"); @@ -98,4 +108,72 @@ fn offline_profiles_report_process_host_and_listener_separately() { assert_eq!(extension["hostLauncherHealthy"], true); assert_eq!(extension["selectedProfile"]["relayAccepts"], false); assert_eq!(extension["pairing"], "unverified"); + + // This socket accepts TCP but never completes a WebSocket handshake. + let silent = TcpListener::bind("127.0.0.1:0").unwrap(); + let endpoint = relay.join("relay-cdp-url-fixture"); + fs::write( + &endpoint, + format!("ws://{}/relay", silent.local_addr().unwrap()), + ) + .unwrap(); + let before = fs::read_to_string(home.join("window-requests")).unwrap(); + let inventory = cli("closed", &["browsers", "--json"]); + assert_eq!(inventory["data"]["browserProcess"], "notRunning"); + let row = &inventory["data"]["browsers"][0]; + assert_eq!(row["relayAccepts"], true); + assert_eq!(row["connected"], true); // compatibility field for TCP inventory + assert_eq!(row["pairing"], "unverified"); + for wait in ["0", "1"] { + let started = Instant::now(); + let result = cli( + "running", + &["connect", "--browser", "Work", "--wait", wait, "--json"], + ); + // Allow subprocess startup overhead while catching a full 10 s health probe. + let limit = Duration::from_secs(wait.parse::().unwrap()) + Duration::from_millis(1500); + assert!( + started.elapsed() < limit, + "wait {wait}: {:?}", + started.elapsed() + ); + assert_eq!(result["success"], false); + assert_eq!(result["data"]["windowRequested"], false); + assert_eq!(result["data"]["action"], "wait-relay"); + } + + let healthy = TcpListener::bind("127.0.0.1:0").unwrap(); + fs::write( + &endpoint, + format!("ws://{}/relay", healthy.local_addr().unwrap()), + ) + .unwrap(); + let server = std::thread::spawn(move || { + // One passive connection precedes the diagnostic request. + for stream in healthy.incoming().take(2) { + if let Ok(mut ws) = tokio_tungstenite::tungstenite::accept(stream.unwrap()) { + let request: Value = + serde_json::from_str(ws.read().unwrap().to_text().unwrap()).unwrap(); + assert_eq!(request["method"], "ABExt.state"); + ws.send(tokio_tungstenite::tungstenite::Message::Text( + json!({"id":request["id"],"result":{"connected":true}}).to_string(), + )) + .unwrap(); + return; + } + } + panic!("no WebSocket diagnostic"); + }); + let live = cli( + "unknown", + &["connect", "--browser", "Work", "--wait", "0", "--json"], + ); + assert_eq!(live["success"], true, "{live}"); + assert_eq!(live["data"]["alreadyConnected"], true); + assert_eq!(live["data"]["windowRequested"], false); + server.join().unwrap(); + assert_eq!( + fs::read_to_string(home.join("window-requests")).unwrap(), + before + ); } diff --git a/docs/commands.html b/docs/commands.html index 6db7ce63de..992710f6d0 100644 --- a/docs/commands.html +++ b/docs/commands.html @@ -589,7 +589,7 @@

页面诊断:diag pages

网页自己打开的标签(target=_blank、window.open)会让 Chrome 跑到你正在用的应用前面(#468)。默认情况下 - chrome-use 让 Chrome 自己打开,和用户点击完全一样;在你自己的 Chrome 里,click 会在 openedTabWarning 里说明。在 macOS 上 chrome-use 默认会把点击前在前台的应用切回前台:只在点击后 1.5 秒内 Chrome 带着一个点击前不存在的新标签跑到前面时才做;点击前 Chrome 本来就在前台、或你切到了别的应用时都不动(结果里的 focusRestored / focusNote 说明;没恢复时不带 --json 也会打印一行 focus not restored: …)。提示会区分标签列表读取失败、未发现本次点击打开的新标签,以及返回时仍在等待确认。Windows 和 Linux 不做。AGENT_BROWSER_RESTORE_FOCUS=0 关闭。 + chrome-use 让 Chrome 自己打开,和用户点击完全一样;在你自己的 Chrome 里,click 会在 openedTabWarning 里说明。在 macOS 上 chrome-use 默认会把点击前在前台的应用切回前台:只在点击后 1.5 秒内 Chrome 带着一个点击前不存在的新标签跑到前面时才做;点击前 Chrome 本来就在前台、或你切到了别的应用时都不动(结果里的 focusRestored / focusNote 说明;没恢复时不带 --json 也会打印一行 focus not restored: …)。提示会区分标签列表读取失败、未发现本次点击打开的新标签,以及返回时仍在等待确认。如果 Chrome 已到前台而扩展还没列出新标签,会等 150 毫秒再查一次。只有新标签的打开者是刚点击的标签才恢复原应用。在等待期间切出 Chrome 会取消恢复。只想读取普通 href 链接时,可以用 click @ref --new-tab,它直接在后台打开目标地址,跳过页面的点击处理函数。两轮独立的无头 Chrome 155.0.8059.39 测试(CLI 1.5.297、扩展 0.5.109)中,原生点击和显式 --new-tab 的首次请求都向回环同源服务器发送了 SameSite=Strict 会话 cookie,原标签页都保持选中。只有原生点击触发了页面的点击处理函数。测试记录的是浏览器选中的标签页,未测量桌面前台焦点。焦点恢复仅适用于 macOS。AGENT_BROWSER_RESTORE_FOCUS=0 关闭。 需主动开启:AGENT_BROWSER_BACKGROUND_LINKS=cross-site(也可写 1/on)后,在本会话创建的标签上, 跨站的 target=_blank 链接(左键、无修饰键、http(s) 地址,页面和链接两端按公共后缀列表都属于不同的可注册域名, 没有 rel=opener、download 或 ping)由 chrome-use 自己打开:网页的点击处理函数照常全部执行, diff --git a/docs/en/commands.html b/docs/en/commands.html index 09bef0da3a..f9386a8958 100644 --- a/docs/en/commands.html +++ b/docs/en/commands.html @@ -622,7 +622,7 @@

Page diagnostics: diag pages

A tab a page opens itself (target=_blank, window.open) brings Chrome to the front over whatever app you are in (#468). By default chrome-use leaves it to Chrome, exactly like a user's click, and in - your own Chrome the click says so in openedTabWarning. On macOS chrome-use then puts the app that was in front back in front (on by default): only when Chrome comes to the front within 1.5 s of the click with a tab that was not there before, never when Chrome was already in front or you moved to another app (focusRestored / focusNote on the click). The note distinguishes a failed tab query, no attributable new tab, and a watch that was still running when the click returned. Not done on Windows and Linux. AGENT_BROWSER_RESTORE_FOCUS=0 turns it off. Opt-in: + your own Chrome the click says so in openedTabWarning. On macOS chrome-use then puts the app that was in front back in front (on by default): only when Chrome comes to the front within 1.5 s of the click with a tab that was not there before, never when Chrome was already in front or you moved to another app (focusRestored / focusNote on the click). The note distinguishes a failed tab query, no attributable new tab, and a watch that was still running when the click returned. If Chrome appears before the relay lists the popup, a second check after 150 ms requires the clicked tab as opener. Leaving Chrome during the wait cancels restoration. For a read-only link with a plain href, click @ref --new-tab opens the URL directly and skips the page’s click handler. In two private headless Chrome 155.0.8059.39 runs (CLI 1.5.297, extension 0.5.109), both the native same-origin link and explicit --new-tab sent the loopback server’s SameSite=Strict session cookie on the first request. In both cases the source tab stayed selected. Only the native click ran the page’s handler. This test measured browser tab selection; desktop foreground focus was outside its scope. Focus restoration is macOS only. AGENT_BROWSER_RESTORE_FOCUS=0 turns it off. Opt-in: AGENT_BROWSER_BACKGROUND_LINKS=cross-site (also 1/on) makes chrome-use open cross-site target=_blank links itself, in a tab the session created (left click, no modifiers, http(s) href to another registrable domain by the Public Suffix List on both ends, no diff --git a/docs/en/real-chrome.html b/docs/en/real-chrome.html index 37e674ab4c..ed2f3e30d1 100644 --- a/docs/en/real-chrome.html +++ b/docs/en/real-chrome.html @@ -354,6 +354,7 @@

When the extension relay is offline

  • If the popup shows the extension is paired but the relay stays offline, open the popup again or reload chrome-use at chrome://extensions. An offline relay alone cannot tell you whether its worker is asleep.
  • +

    The RELAY LISTENER column in browsers reports a TCP check. Use status on the profile to confirm an extension reply. When the port is already listening, connect waits without requesting another window.

    chrome-use connect --browser <profile> can request a window. It waits up to 120 seconds by default for that profile’s relay. If an earlier write was interrupted, check the page before repeating it.

    diff --git a/docs/real-chrome.html b/docs/real-chrome.html index 2a3f43fef8..132b88b50f 100644 --- a/docs/real-chrome.html +++ b/docs/real-chrome.html @@ -337,6 +337,7 @@

    扩展中继离线时如何排查

    chrome-use extension install --all-profiles,完全退出 Chrome,再打开目标 profile。
  • 如果扩展弹窗显示已配对,中继仍离线,重新打开弹窗,或在 chrome://extensions 重新加载 chrome-use。仅凭中继离线无法判断扩展 worker 是否休眠。
  • +

    browsers 的 RELAY LISTENER 列只检查端口;用指定 profile 的 status 核实扩展回复。当端口已在监听时,connect 会等待回复,无需再开窗口。

    chrome-use connect --browser <profile> 可以请求打开窗口,默认最多等 120 秒,直到该 profile 的中继连上。 如果之前的写操作中断,先查看页面,确认是否需要重试。

    diff --git a/skill-data/core/references/commands.md b/skill-data/core/references/commands.md index d8c1d70f5f..4b9dc5a823 100644 --- a/skill-data/core/references/commands.md +++ b/skill-data/core/references/commands.md @@ -709,7 +709,15 @@ back in front (measured: Chrome in front for about 45–60 ms). The click report `focusRestored: true` with `focusRestoredApp` and `focusRestoredAfterMs`, or `focusRestored: false` with `focusNote` describing what the watch observed. The note distinguishes a failed tab query, a query that found no attributable -new tab, and a result collected before the watch finished. It never switches apps +new tab, and a result collected before the watch finished. If the relay has yet +to list the popup, a single check after 150 ms requires the clicked tab as opener +and the same browser process to remain in front, within the original 1.5 s. +For read-only navigation using a plain `href`, explicit `click @ref --new-tab` +opens the URL without dispatching the page’s click handler. A private headless +Chrome 155 test with a loopback origin and a `SameSite=Strict` session cookie +observed an authenticated first request while the source tab stayed selected. +Use the native click when the link depends on its handler. +It never switches apps when Chrome was already the frontmost app before the click (you are in Chrome; the agent's window may then become Chrome's focused window), when another app came to the front (you moved), or when Chrome came to the front without a new diff --git a/skill-data/core/references/connection.md b/skill-data/core/references/connection.md index 36b2c98a1c..9a2dd0e3d0 100644 --- a/skill-data/core/references/connection.md +++ b/skill-data/core/references/connection.md @@ -81,6 +81,8 @@ and tab cleanup on two local fixtures. Stop the Moli process when finished. `chrome-use status` reads extension state without a session daemon or debugger command. Stale relay files do not count as online. A healthy relay does not prove that an individual page renderer responds; verify the intended page separately. +The `RELAY LISTENER` column in `browsers` reports a TCP check. Use `status --browser ` to confirm an extension reply. When the selected port is already listening, `connect --browser` waits there without requesting another window. + For a disconnected profile, read the Chrome process state, native host registration and live relay separately. If the process state is unknown, check whether Chrome is open. If Chrome is stopped, open the target profile. diff --git a/skill-data/real-chrome/SKILL.md b/skill-data/real-chrome/SKILL.md index 06f049d80e..acbf6dcc8f 100644 --- a/skill-data/real-chrome/SKILL.md +++ b/skill-data/real-chrome/SKILL.md @@ -105,7 +105,9 @@ native host registration and live relay. Run `chrome-use browsers` to find the target profile. A listed profile exists on disk or has a connected relay; a missing selector is a separate error. A window request from `chrome-use connect --browser ` can bring up the user's Chrome. -The command waits up to 120 seconds by default for the selected relay to connect. +The command waits up to 120 seconds by default for the selected relay to answer. +If its port already accepts connections, it waits without opening another window. +`browsers` reports the listener; `status` checks for an extension reply. 1. **Chrome stopped.** Open Chrome in the target profile. If the process state is unknown, check whether Chrome is open. From ad6d866c4cc0c9f5c416572ff4eca8957c9651a1 Mon Sep 17 00:00:00 2001 From: leo Date: Wed, 2 Dec 2026 17:51:42 +0900 Subject: [PATCH 4/5] =?UTF-8?q?fix(connect):=20=E6=9C=AA=E7=A1=AE=E8=AE=A4?= =?UTF-8?q?=E7=AB=AF=E5=8F=A3=E6=8B=92=E7=BB=9D=E6=97=B6=E4=BF=9D=E7=95=99?= =?UTF-8?q?=E7=8E=B0=E6=9C=89=E7=AA=97=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cli/src/connect.rs | 46 ++++++++++++++++++++++++++++------ cli/src/profiles.rs | 40 ++++++++++++++++------------- cli/tests/relay_diagnostics.rs | 22 ++++++++++++++-- docs/commands.html | 2 +- docs/en/commands.html | 2 +- 5 files changed, 83 insertions(+), 29 deletions(-) diff --git a/cli/src/connect.rs b/cli/src/connect.rs index 366846b67a..e6e01e42d9 100644 --- a/cli/src/connect.rs +++ b/cli/src/connect.rs @@ -4208,16 +4208,23 @@ pub const REFUSED_RELAY_FIX: &str = "Its native host has stopped and ab-connect /// died, so its existence alone is not "connected" (#910). Blocking and /// runtime-free, so sync callers inside or outside tokio can use it. pub fn relay_endpoint_accepts(url: &str) -> bool { - relay_endpoint_accepts_within(url, std::time::Duration::from_secs(1)) + relay_endpoint_accepts_within(url, std::time::Duration::from_secs(1)) == Some(true) } -pub(crate) fn relay_endpoint_accepts_within(url: &str, budget: std::time::Duration) -> bool { +/// Some(false) means every resolved address explicitly refused the connection. +pub(crate) fn relay_endpoint_accepts_within( + url: &str, + budget: std::time::Duration, +) -> Option { use std::net::ToSocketAddrs; + if budget.is_zero() { + return None; + } let start = std::time::Instant::now(); let Ok(uri) = url.parse::() else { - return false; + return None; }; - let Some(host) = uri.host() else { return false }; + let Some(host) = uri.host() else { return None }; let port = uri .port_u16() .unwrap_or(if uri.scheme_str() == Some("wss") { @@ -4226,12 +4233,22 @@ pub(crate) fn relay_endpoint_accepts_within(url: &str, budget: std::time::Durati 80 }); let Ok(addrs) = (host.trim_matches(['[', ']']), port).to_socket_addrs() else { - return false; + return None; }; - addrs.into_iter().any(|addr| { + let mut refused = false; + let mut uncertain = false; + for addr in addrs { let left = budget.saturating_sub(start.elapsed()); - !left.is_zero() && std::net::TcpStream::connect_timeout(&addr, left).is_ok() - }) + if left.is_zero() { + return None; + } + match std::net::TcpStream::connect_timeout(&addr, left) { + Ok(_) => return Some(true), + Err(e) if e.kind() == std::io::ErrorKind::ConnectionRefused => refused = true, + Err(_) => uncertain = true, + } + } + (refused && !uncertain).then_some(false) } /// The extension version one profile's extension reported, from its own @@ -7675,7 +7692,20 @@ printf '%s\000' "$HOME" "${CHROME_USE_RELAY_DIR-__unset__}" "$@" assert!(relay_endpoint_accepts(&format!( "ws://127.0.0.1:{port}/devtools/browser/x" ))); + let url = format!("ws://127.0.0.1:{port}/devtools/browser/x"); + assert_eq!( + relay_endpoint_accepts_within(&url, std::time::Duration::ZERO), + None + ); + assert_eq!( + relay_endpoint_accepts_within("not a url", std::time::Duration::from_secs(1)), + None + ); drop(listener); + assert_eq!( + relay_endpoint_accepts_within(&url, std::time::Duration::from_secs(1)), + Some(false) + ); // Port 1 (outside the ephemeral range, so no self-connect): refused. assert!(!relay_endpoint_accepts( "ws://127.0.0.1:1/devtools/browser/x" diff --git a/cli/src/profiles.rs b/cli/src/profiles.rs index a2780f74bb..b5a496b103 100644 --- a/cli/src/profiles.rs +++ b/cli/src/profiles.rs @@ -273,13 +273,13 @@ pub enum Match { /// is exactly one — the same email signed in to three profiles, one of which /// runs the extension, kept working before this matcher knew the other two. pub fn match_selector(rows: &[ProfileRow], selector: &str) -> Match { - match_selector_with_relay_preference(rows, selector, true) + match_selector_with_relay_preference(rows, selector, ProfileRow::connected) } fn match_selector_with_relay_preference( rows: &[ProfileRow], selector: &str, - prefer_live: bool, + live: impl Fn(&ProfileRow) -> bool, ) -> Match { let sel = selector.trim(); if sel.is_empty() { @@ -299,9 +299,8 @@ fn match_selector_with_relay_preference( 0 => None, 1 => Some(Match::One(c[0])), _ => { - if prefer_connected && prefer_live { - let live: Vec = - c.iter().copied().filter(|&i| rows[i].connected()).collect(); + if prefer_connected { + let live: Vec = c.iter().copied().filter(|&i| live(&rows[i])).collect(); if live.len() == 1 { return Some(Match::One(live[0])); } @@ -407,8 +406,11 @@ pub fn not_connected_message(selector: &str, row: &ProfileRow) -> String { /// Pure resolution to any profile (connected or not), with the user-facing /// error for no match / several matches. pub fn resolve_in(rows: &[ProfileRow], selector: &str) -> Result { - let sel = selector.trim(); - match match_selector(rows, sel) { + resolved_match(rows, selector.trim(), match_selector(rows, selector)) +} + +fn resolved_match(rows: &[ProfileRow], sel: &str, result: Match) -> Result { + match result { Match::One(i) => Ok(i), Match::Ambiguous(c) => Err(format!( "'{sel}' matches {} Chrome profiles — use the directory name or email:{}", @@ -1713,17 +1715,19 @@ pub fn run_connect_profile(selector: &str, args: &[String], json_out: bool) { }; let remaining = || budget.saturating_sub(started.elapsed()); // Only matching candidates need TCP liveness for the existing tie-break. - let candidates = match match_selector_with_relay_preference(&rows, selector, false) { + let candidates = match match_selector_with_relay_preference(&rows, selector, |_| false) { Match::One(i) => vec![i], Match::Ambiguous(indices) => indices, Match::None => vec![], }; for i in candidates { - rows[i].relay_accepts = rows[i].ws.as_deref().map(|url| { + rows[i].relay_accepts = rows[i].ws.as_deref().and_then(|url| { connect::relay_endpoint_accepts_within(url, remaining().min(Duration::from_secs(1))) }); } - let i = match resolve_in(&rows, selector) { + let matched = + match_selector_with_relay_preference(&rows, selector, |r| r.relay_accepts == Some(true)); + let i = match resolved_match(&rows, selector.trim(), matched) { Ok(i) => i, Err(e) => { fail(json_out, &e); @@ -1731,12 +1735,12 @@ pub fn run_connect_profile(selector: &str, args: &[String], json_out: bool) { } }; let row = rows[i].clone(); - let listener = row.relay_accepts == Some(true); + let window_requested = row.ws.is_none() || row.relay_accepts == Some(false); let done = |row: &ProfileRow, already: bool| { if json_out { println!( "{}", - json!({"success": true, "data": {"connected": true, "alreadyConnected": already, "windowRequested": !listener, "profile": row.to_json()}}) + json!({"success": true, "data": {"connected": true, "alreadyConnected": already, "windowRequested": window_requested, "profile": row.to_json()}}) ); } else if already { println!( @@ -1754,7 +1758,7 @@ pub fn run_connect_profile(selector: &str, args: &[String], json_out: bool) { ); } }; - let action = if listener { + let action = if !window_requested { "wait-relay" } else { match request_connect_window(&row) { @@ -1772,7 +1776,7 @@ pub fn run_connect_profile(selector: &str, args: &[String], json_out: bool) { }; let mut first = true; loop { - let current = if first && listener { + let current = if first && !window_requested { Some(row.clone()) } else { load_rows().into_iter().find(|r| r.same_profile(&row)) @@ -1785,7 +1789,7 @@ pub fn run_connect_profile(selector: &str, args: &[String], json_out: bool) { .as_deref() .is_some_and(|url| connect::relay_health_within(url, left).transport_responsive) { - done(&now, listener && first); + done(&now, !window_requested && first); return; } } @@ -1808,8 +1812,10 @@ pub fn run_connect_profile(selector: &str, args: &[String], json_out: bool) { } else { "" }; - let listener_note = if listener { + let listener_note = if row.relay_accepts == Some(true) { " The relay port accepted a connection; no additional window was requested." + } else if !window_requested { + " The recorded relay endpoint could not be verified; no additional window was requested." } else { "" }; @@ -1822,7 +1828,7 @@ pub fn run_connect_profile(selector: &str, args: &[String], json_out: bool) { profile["connected"] = false.into(); println!( "{}", - json!({"success": false, "error": msg, "data": {"connected": false, "windowRequested": !listener, "relayAccepts": row.relay_accepts, "pairing": "unverified", "browserProcess": process, "action": action, "profile": profile}}) + json!({"success": false, "error": msg, "data": {"connected": false, "windowRequested": window_requested, "relayAccepts": row.relay_accepts, "pairing": "unverified", "browserProcess": process, "action": action, "profile": profile}}) ); } else { eprintln!("{} {msg}", color::error_indicator()); diff --git a/cli/tests/relay_diagnostics.rs b/cli/tests/relay_diagnostics.rs index c940e06b7f..8a16330e62 100644 --- a/cli/tests/relay_diagnostics.rs +++ b/cli/tests/relay_diagnostics.rs @@ -75,16 +75,19 @@ fn offline_profiles_report_process_host_and_listener_separately() { assert_eq!(list["data"]["browserProcess"], expected); assert_eq!(list["data"]["browsers"][0]["hasExtension"], true); } - // Port zero is not a listening TCP endpoint. A surviving sidecar alone + // A closed local port explicitly refuses the connection. A surviving sidecar alone // must not make either browsers or connect return a successful connection. fs::write( relay.join("relay-ext-profile-fixture"), r#"{"id":"fixture","email":"work@example.invalid"}"#, ) .unwrap(); + let closed = TcpListener::bind("127.0.0.1:0").unwrap(); + let closed_addr = closed.local_addr().unwrap(); + drop(closed); fs::write( relay.join("relay-cdp-url-fixture"), - "ws://127.0.0.1:0/stale", + format!("ws://{closed_addr}/stale"), ) .unwrap(); let list = cli("running", &["browsers", "--json"]); @@ -142,6 +145,21 @@ fn offline_profiles_report_process_host_and_listener_separately() { assert_eq!(result["data"]["action"], "wait-relay"); } + // A recorded address that cannot be probed is not an observed refusal. + fs::write(&endpoint, "ws://[").unwrap(); + let unknown = cli( + "running", + &["connect", "--browser", "Work", "--wait", "0", "--json"], + ); + assert_eq!(unknown["success"], false); + assert_eq!(unknown["data"]["relayAccepts"], Value::Null); + assert_eq!(unknown["data"]["windowRequested"], false); + assert_eq!(unknown["data"]["action"], "wait-relay"); + assert_eq!( + fs::read_to_string(home.join("window-requests")).unwrap(), + before + ); + let healthy = TcpListener::bind("127.0.0.1:0").unwrap(); fs::write( &endpoint, diff --git a/docs/commands.html b/docs/commands.html index 992710f6d0..04f0e8f97b 100644 --- a/docs/commands.html +++ b/docs/commands.html @@ -589,7 +589,7 @@

    页面诊断:diag pages

    网页自己打开的标签(target=_blank、window.open)会让 Chrome 跑到你正在用的应用前面(#468)。默认情况下 - chrome-use 让 Chrome 自己打开,和用户点击完全一样;在你自己的 Chrome 里,click 会在 openedTabWarning 里说明。在 macOS 上 chrome-use 默认会把点击前在前台的应用切回前台:只在点击后 1.5 秒内 Chrome 带着一个点击前不存在的新标签跑到前面时才做;点击前 Chrome 本来就在前台、或你切到了别的应用时都不动(结果里的 focusRestored / focusNote 说明;没恢复时不带 --json 也会打印一行 focus not restored: …)。提示会区分标签列表读取失败、未发现本次点击打开的新标签,以及返回时仍在等待确认。如果 Chrome 已到前台而扩展还没列出新标签,会等 150 毫秒再查一次。只有新标签的打开者是刚点击的标签才恢复原应用。在等待期间切出 Chrome 会取消恢复。只想读取普通 href 链接时,可以用 click @ref --new-tab,它直接在后台打开目标地址,跳过页面的点击处理函数。两轮独立的无头 Chrome 155.0.8059.39 测试(CLI 1.5.297、扩展 0.5.109)中,原生点击和显式 --new-tab 的首次请求都向回环同源服务器发送了 SameSite=Strict 会话 cookie,原标签页都保持选中。只有原生点击触发了页面的点击处理函数。测试记录的是浏览器选中的标签页,未测量桌面前台焦点。焦点恢复仅适用于 macOS。AGENT_BROWSER_RESTORE_FOCUS=0 关闭。 + chrome-use 让 Chrome 自己打开,和用户点击完全一样;在你自己的 Chrome 里,click 会在 openedTabWarning 里说明。在 macOS 上 chrome-use 默认会把点击前在前台的应用切回前台:只在点击后 1.5 秒内 Chrome 带着一个点击前不存在的新标签跑到前面时才做;点击前 Chrome 本来就在前台、或你切到了别的应用时都不动(结果里的 focusRestored / focusNote 说明;没恢复时不带 --json 也会打印一行 focus not restored: …)。提示会区分标签列表读取失败、未发现本次点击打开的新标签,以及返回时仍在等待确认。首次检查接受会话标签组里的新标签,也接受由会话标签打开的未分组新标签。如果 Chrome 已到前台而首次检查没有找到这样的标签,会等 150 毫秒再查一次。这次复查还要求新标签的打开者就是刚点击的标签。在等待期间切出 Chrome 会取消恢复。只想读取普通 href 链接时,可以用 click @ref --new-tab,它直接在后台打开目标地址,跳过页面的点击处理函数。两轮独立的无头 Chrome 155.0.8059.39 测试(CLI 1.5.297、扩展 0.5.109)中,原生点击和显式 --new-tab 的首次请求都向回环同源服务器发送了 SameSite=Strict 会话 cookie,原标签页都保持选中。只有原生点击触发了页面的点击处理函数。测试记录的是浏览器选中的标签页,未测量桌面前台焦点。焦点恢复仅适用于 macOS。AGENT_BROWSER_RESTORE_FOCUS=0 关闭。 需主动开启:AGENT_BROWSER_BACKGROUND_LINKS=cross-site(也可写 1/on)后,在本会话创建的标签上, 跨站的 target=_blank 链接(左键、无修饰键、http(s) 地址,页面和链接两端按公共后缀列表都属于不同的可注册域名, 没有 rel=opener、download 或 ping)由 chrome-use 自己打开:网页的点击处理函数照常全部执行, diff --git a/docs/en/commands.html b/docs/en/commands.html index f9386a8958..3cdaaf59e8 100644 --- a/docs/en/commands.html +++ b/docs/en/commands.html @@ -622,7 +622,7 @@

    Page diagnostics: diag pages

    A tab a page opens itself (target=_blank, window.open) brings Chrome to the front over whatever app you are in (#468). By default chrome-use leaves it to Chrome, exactly like a user's click, and in - your own Chrome the click says so in openedTabWarning. On macOS chrome-use then puts the app that was in front back in front (on by default): only when Chrome comes to the front within 1.5 s of the click with a tab that was not there before, never when Chrome was already in front or you moved to another app (focusRestored / focusNote on the click). The note distinguishes a failed tab query, no attributable new tab, and a watch that was still running when the click returned. If Chrome appears before the relay lists the popup, a second check after 150 ms requires the clicked tab as opener. Leaving Chrome during the wait cancels restoration. For a read-only link with a plain href, click @ref --new-tab opens the URL directly and skips the page’s click handler. In two private headless Chrome 155.0.8059.39 runs (CLI 1.5.297, extension 0.5.109), both the native same-origin link and explicit --new-tab sent the loopback server’s SameSite=Strict session cookie on the first request. In both cases the source tab stayed selected. Only the native click ran the page’s handler. This test measured browser tab selection; desktop foreground focus was outside its scope. Focus restoration is macOS only. AGENT_BROWSER_RESTORE_FOCUS=0 turns it off. Opt-in: + your own Chrome the click says so in openedTabWarning. On macOS chrome-use then puts the app that was in front back in front (on by default): only when Chrome comes to the front within 1.5 s of the click with a tab that was not there before, never when Chrome was already in front or you moved to another app (focusRestored / focusNote on the click). The note distinguishes a failed tab query, no attributable new tab, and a watch that was still running when the click returned. The first check accepts a new tab in a session tab group or an ungrouped tab opened by a session tab. If it finds neither when Chrome comes forward, a second check after 150 ms also requires the clicked tab as opener. Leaving Chrome during the wait cancels restoration. For a read-only link with a plain href, click @ref --new-tab opens the URL directly and skips the page’s click handler. In two private headless Chrome 155.0.8059.39 runs (CLI 1.5.297, extension 0.5.109), both the native same-origin link and explicit --new-tab sent the loopback server’s SameSite=Strict session cookie on the first request. In both cases the source tab stayed selected. Only the native click ran the page’s handler. This test measured browser tab selection; desktop foreground focus was outside its scope. Focus restoration is macOS only. AGENT_BROWSER_RESTORE_FOCUS=0 turns it off. Opt-in: AGENT_BROWSER_BACKGROUND_LINKS=cross-site (also 1/on) makes chrome-use open cross-site target=_blank links itself, in a tab the session created (left click, no modifiers, http(s) href to another registrable domain by the Public Suffix List on both ends, no From 929846aeeadea94c63d17347c93ac11548d2b524 Mon Sep 17 00:00:00 2001 From: leo Date: Wed, 2 Dec 2026 17:54:44 +0900 Subject: [PATCH 5/5] =?UTF-8?q?chore(ci):=20=E7=AE=80=E5=8C=96=E7=AB=AF?= =?UTF-8?q?=E7=82=B9=E4=B8=BB=E6=9C=BA=E5=90=8D=E7=BC=BA=E5=A4=B1=E5=88=86?= =?UTF-8?q?=E6=94=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cli/src/connect.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cli/src/connect.rs b/cli/src/connect.rs index e6e01e42d9..b64bcfee92 100644 --- a/cli/src/connect.rs +++ b/cli/src/connect.rs @@ -4224,7 +4224,7 @@ pub(crate) fn relay_endpoint_accepts_within( let Ok(uri) = url.parse::() else { return None; }; - let Some(host) = uri.host() else { return None }; + let host = uri.host()?; let port = uri .port_u16() .unwrap_or(if uri.scheme_str() == Some("wss") {