@glittering0717/ai-browser 2.4.5 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -15,7 +15,7 @@
15
15
  <img alt="MIT" src="https://img.shields.io/badge/license-MIT-blue.svg">
16
16
  <img alt="Electron" src="https://img.shields.io/badge/built%20with-Electron%2033-9cf">
17
17
  <img alt="Platforms" src="https://img.shields.io/badge/platforms-macOS%20%E2%80%A2%20Linux-blueviolet">
18
- <img alt="Tests" src="https://img.shields.io/badge/tests-658%20unit%20%2B%20447%20e2e-2ea043">
18
+ <img alt="Tests" src="https://img.shields.io/badge/tests-1309%20unit%20%2B%20831%20e2e-2ea043">
19
19
  <img alt="MCP" src="https://img.shields.io/badge/spec-MCP%20(stdio)-f5b23b">
20
20
  </p>
21
21
 
@@ -32,17 +32,22 @@
32
32
  </p>
33
33
 
34
34
  **What it is.** An Electron app that exposes its tabs over two equivalent interfaces — an MCP server
35
- (20 `browse_*` tools) and a raw WebSocket JSON-RPC API (`ws://localhost:9223`, methods `ui.*`). Your
35
+ (17 `browse_*` tools) and a raw WebSocket JSON-RPC API (`ws://localhost:9223`, methods `ui.*`). Your
36
36
  agent navigates, reads a structured semantic tree (`role` / `label` / `value` / `states` / `actions`),
37
- and clicks or types by `data-ai-id`. There is no screenshot step and no OCR: `src/` contains no
38
- capture call at all.
37
+ and clicks or types by `data-ai-id`. **Reading never goes through a screenshot and there is no OCR** —
38
+ that's the point of the tree. `browse_screenshot` exists, but as a *diagnostic* for the cases the tree
39
+ can't see (overlays, canvas, mis-rendered layout), not as the read path.
39
40
 
40
41
  **What it is not.** It is not headless. The window really opens, really renders, and stays interactive —
41
42
  see [Letting a human step in](#letting-a-human-step-in). Nor does it "co-drive" with you: the hand-off
42
43
  is a conversation between the agent and the user, not a browser API.
43
44
 
44
- > **Security note.** The WebSocket server has no authentication — it listens on localhost and trusts
45
- > whoever connects. Do not expose port 9223 beyond loopback, and avoid untrusted networks.
45
+ > **Security note.** The WebSocket server binds loopback only and **refuses any handshake that carries
46
+ > an `Origin` header** — that's what a browser always sends, so a page running inside AI Browser (or
47
+ > any other browser) cannot drive the control plane, while Node/CLI/MCP clients (which send no
48
+ > `Origin`) work normally. There is still no token: a local process running as you can connect.
49
+ > Do not expose port 9223 beyond loopback.
50
+ > (`AI_BROWSER_WS_ALLOW_ORIGIN=1` disables the check — debug only, it re-opens the page → browser path.)
46
51
 
47
52
  ---
48
53
 
@@ -207,6 +212,9 @@ small surface, since every tool schema is injected into your agent's context on
207
212
  | `browse_wait` | Poll until `button_enabled` / `modal_appeared` / `text_contains` / `url_contains`. |
208
213
  | `browse_tabs` | Tabs: `list` / `new` / `close` / `switch` / `window`. `switch` = default; add `show:true`. `new` never steals the view unless `show:true`. |
209
214
  | `browse_network` | Chrome-DevTools-style network inspection: `list` (filter by method / URL / status / type), `get` (request + response headers and bodies), `clear`, `configure`. |
215
+ | `browse_auth_state` | Login-state self-check for a tab: are we logged in, or bounced to a login wall. Cheap — no tree is built. |
216
+ | `browse_screenshot` | Diagnostic viewport/element capture (`png`/`jpeg`/`webp`, `clip`, `fullPage`). Not the read path — use it when the tree and the screen disagree. |
217
+ | `browse_errors` | Recent errors the browser recorded (crashes, failed navigations, RPC failures) with hints. Ask here when behaviour doesn't match the docs. |
210
218
  | `browse_quit` | Shut the whole browser down and release the process. |
211
219
 
212
220
  ### What every act result already tells you: `effect_state`
@@ -461,7 +469,9 @@ covers the things an agent genuinely cannot do:
461
469
  side, and nothing needs to. It is a conversation between the agent and its user:
462
470
 
463
471
  1. The agent hits something it cannot do.
464
- 2. It says so in chat, plainly: *"Please scan the QR code in the browser window, then reply 'done'."*
472
+ 2. It says so in its own reply, as plain text — *"Please scan the QR code in the browser window, then
473
+ reply 'done'."* No tool call is involved: there is no `chat` / `message` / `ask_user` tool in this
474
+ project, and no "spawn a side conversation" feature. Talking to the user is the agent's own job.
465
475
  3. It stops and waits for the reply — no retry loops on clicks that cannot work.
466
476
  4. After "done" it re-reads with `browse_get_tree` to confirm the new state, then continues.
467
477
 
@@ -483,6 +493,14 @@ MCP is a thin stdio adapter. Anything MCP can do is reachable directly over JSON
483
493
  `ws://localhost:9223` from any language. Source of truth: the method switch in
484
494
  [`src/main/ws_server.js`](src/main/ws_server.js).
485
495
 
496
+ Two things to know before you write a client:
497
+
498
+ - **Connections carrying an `Origin` header are closed with code 1008.** Browsers always send it;
499
+ Node's `WebSocket` and the `ws` package do not, so a normal script is unaffected. This is a
500
+ security boundary, not a bug — see the security note above.
501
+ - Method parameters are camelCase (`focusedOnly`, `timeout_ms`). MCP maps the snake_case tool
502
+ arguments onto them.
503
+
486
504
  You do not have to write a client to do this. The CLI speaks the same protocol:
487
505
 
488
506
  ```bash
@@ -38,8 +38,10 @@ success:true 只代表动作发出去了,不代表页面变了。要证明生
38
38
  canvas / 富文本),换动作不是换选择器;点了没反应 → browse_screenshot 看视觉 或
39
39
  browse_network 看请求;怀疑掉登录 → browse_auth_state;都不是 → browse_errors。
40
40
 
41
- 需要人(登录/扫码/滑块/支付):在对话里直接请用户在窗口里操作,收到"好了"再 browse_get_tree
42
- 确认。不要编造凭据,不要重试注定失败的点击。窗口是真的,人随时能抢鼠标。
41
+ 需要人(登录/扫码/滑块/支付):**在你这轮回复里直接说一句**,请用户在窗口里操作,然后结束这轮等
42
+ 回话;收到"好了"再 browse_get_tree 确认。这一步不需要任何工具——本项目没有 chat / message /
43
+ ask_user 这类工具,也没有"发起一次性会话",别去调宿主的临时对话能力。不要编造凭据,不要重试
44
+ 注定失败的点击。窗口是真的,人随时能抢鼠标。
43
45
 
44
46
  收尾:browse_quit 关掉窗口和进程(人正在操作时不要调)。
45
47
  ```
package/llms-install.md CHANGED
@@ -201,11 +201,14 @@ notifications. Use `browse_network` for pull-based inspection.
201
201
  ## Human hand-off
202
202
 
203
203
  When blocked by login, SSO, QR code, slider/image CAPTCHA, SMS/email code, or
204
- payment confirmation: stop, ask the user in chat to do it in the visible browser
205
- window and reply "done", wait for that reply, then re-read with
206
- `browse_get_tree` and continue. Never fabricate credentials or retry clicks that
207
- cannot succeed. Logins persist in the `persist:ai-browser` session partition
208
- (on disk under `~/.ai-browser`), so intervention is usually needed once per site.
204
+ payment confirmation: stop and ask the user **in your own reply** (plain text —
205
+ there is no `chat`/`message` tool here, and no side-conversation feature) to do
206
+ it in the visible browser window and reply "done", wait for that reply, then
207
+ re-read with `browse_get_tree` and continue. Never fabricate credentials or retry
208
+ clicks that cannot succeed. Logins persist in the `persist:ai-browser` session
209
+ partition (on disk under `~/.ai-browser`), so intervention is usually needed once
210
+ per site. While the user is typing or scanning, do **not** call `browse_quit` —
211
+ it closes the window and takes any half-finished work with it.
209
212
 
210
213
  ## Troubleshooting (common cases)
211
214
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@glittering0717/ai-browser",
3
- "version": "2.4.5",
3
+ "version": "2.5.0",
4
4
  "description": "AI-native browser — renders pixels for humans, structured semantic-tree API for agents. No screenshots, no OCR, no coordinate guessing.",
5
5
  "main": "src/main/index.js",
6
6
  "bin": {
@@ -96,7 +96,9 @@
96
96
  "background": "node e2e/background_ws.cjs",
97
97
  "icon:check": "node scripts/check_icon.cjs",
98
98
  "icons": "env -u ELECTRON_RUN_AS_NODE node_modules/electron/dist/Electron.app/Contents/MacOS/Electron --no-sandbox --disable-gpu scripts/render_icon.cjs",
99
- "icon": "node e2e/icon_ws.cjs"
99
+ "icon": "node e2e/icon_ws.cjs",
100
+ "security": "node e2e/security_ws.cjs",
101
+ "contract": "node e2e/contract_ws.cjs"
100
102
  },
101
103
  "dependencies": {
102
104
  "@modelcontextprotocol/sdk": "^1.29.0",
@@ -46,7 +46,7 @@ ai-browser call ui.act '{"action":"click","target":"e:a-3"}' # 点它
46
46
 
47
47
  ## 需要人帮忙
48
48
 
49
- 登录、扫码、滑块、支付:请用户在窗口里操作,说"好了"再重读树;不要编造密码。
49
+ 登录扫码滑块支付:回复请人操作,好了再读树;无 chat/一次性会话工具,勿编密码。
50
50
 
51
51
  ## 按需深挖
52
52
 
@@ -55,6 +55,22 @@ browse_tabs {"op":"switch","tab":7,"show":true}
55
55
  用户点开你那一页只是"看",**不会**抢走你的目标;你继续在上面操作,他看到的是
56
56
  实时画面。要避免"我正要输入他却盯着看"的尴尬,就提前说一句。
57
57
 
58
+ ### 怎么"说一句"——不需要任何工具
59
+
60
+ **就在你这轮回复里写一句人话,然后结束这一轮、停下等回话。** 例如:
61
+
62
+ > 请在浏览器窗口里扫这个码,好了回我一句"好了"。
63
+
64
+ 收到"好了"之后再用 `browse_get_tree` 确认状态变了,才继续 —— 别把"用户说好了"
65
+ 当成"页面真的变了"。
66
+
67
+ - 本项目**没有** `chat` / `message` / `ask_user` 这类工具,也**没有**"发起一次性会话"
68
+ 的功能。去调宿主的临时对话/子对话不会让人去扫码,只会白绕一轮 —— 它是不是用完
69
+ 自动关闭,跟你这一轮任务没有任何关系,不用管。
70
+ - 交接发生在 agent 的对话里,**浏览器侧零改动**:窗口一直开着,人随时能抢鼠标。
71
+ - **人正在操作时不要 `browse_quit`**:它连窗口一起带走,做到一半的全没了。
72
+ - 别编造密码/验证码,也别重试注定失败的点击(滑块、风控拦截页)。
73
+
58
74
  ## 关于"后台"
59
75
 
60
76
  ```json
@@ -19,6 +19,26 @@ import { config } from '../shared/config.js';
19
19
 
20
20
  const MAX_RECORDS_PER_TAB = 200;
21
21
 
22
+
23
+ /**
24
+ * 同名文件唯一化(`report.csv` → `report (1).csv`)。
25
+ *
26
+ * 此前 savePath 直接拼 `dir/basename`,而 Electron 的 `setSavePath` 会**覆盖**
27
+ * 目标文件。同一站点连点两次导出,第一次的文件就没了 —— 回执里两条记录的
28
+ * path 一模一样,用户拿到的却是后一份内容(2026-10-31 复核)。
29
+ */
30
+ function uniquePath(dir, name) {
31
+ const ext = path.extname(name);
32
+ const stem = ext ? name.slice(0, -ext.length) : name;
33
+ let candidate = path.join(dir, name);
34
+ let n = 1;
35
+ while (fs.existsSync(candidate) && n < 1000) {
36
+ candidate = path.join(dir, `${stem} (${n})${ext}`);
37
+ n += 1;
38
+ }
39
+ return candidate;
40
+ }
41
+
22
42
  export class DownloadMonitor {
23
43
  constructor(session, opts = {}) {
24
44
  this.session = session;
@@ -50,7 +70,7 @@ export class DownloadMonitor {
50
70
  const raw = String(item.getFilename() || 'download');
51
71
  const safe = path.basename(raw).replace(/[\u0000-\u001f"*/:<>?\\|]/g, '_') || 'download';
52
72
  const dir = path.join(this.baseDir, String(tabId));
53
- const savePath = path.join(dir, safe);
73
+ const savePath = uniquePath(dir, safe);
54
74
 
55
75
  try { fs.mkdirSync(dir, { recursive: true }); } catch (_) { /* 落盘失败在下面体现 */ }
56
76
  item.setSavePath(savePath);
@@ -142,3 +162,5 @@ export class DownloadMonitor {
142
162
  this._byTab.clear();
143
163
  }
144
164
  }
165
+
166
+ export { uniquePath };
@@ -17,6 +17,7 @@ import ensureMod from '../../scripts/ensure_running.cjs';
17
17
  import { MCP_TOOLS } from './mcp_tools.js';
18
18
  import { actParams, networkParams } from './mcp_args.js';
19
19
  import { evaluateGuardError } from '../shared/guards.js';
20
+ import { timeoutForTool } from '../shared/tool_timeout.js';
20
21
  // 截图体积上限(与 WS 侧共用同一把尺):超过就不把图塞进上下文。
21
22
  import screenshotOpts from '../shared/screenshot_opts.cjs';
22
23
  import { config, wsUrl } from '../shared/config.js';
@@ -102,7 +103,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
102
103
  url: args.url,
103
104
  tab: args.tab,
104
105
  wait_until: args.wait_until || undefined,
105
- });
106
+ }, { timeoutMs: timeoutForTool('browse_navigate', args) });
106
107
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
107
108
  }
108
109
 
@@ -133,7 +134,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
133
134
  target: args.target,
134
135
  params: actParams(args),
135
136
  tab: args.tab
136
- });
137
+ }, { timeoutMs: timeoutForTool('browse_act', args) });
137
138
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
138
139
  }
139
140
 
@@ -177,7 +178,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
177
178
  text: args.text,
178
179
  timeout_ms: args.timeout_ms,
179
180
  tab: args.tab
180
- });
181
+ }, { timeoutMs: timeoutForTool('browse_wait', args) });
181
182
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
182
183
  }
183
184
 
@@ -153,12 +153,23 @@ export function createWsClient({
153
153
 
154
154
  // JSON-RPC call; resolves to the result, rejects on {error} / timeout /
155
155
  // connection failure. Uses the shared connection via getWs().
156
- function call(method, params = {}) {
156
+ //
157
+ // `opts.timeoutMs`:**每次调用**自己的 deadline。此前这里只有模块级的 15s,
158
+ // 于是 `browse_wait {timeout_ms:60000}` / `browse_act {timeout_ms:120000}`
159
+ // 在第 15 秒就被传输层掐掉,而服务端还在正常轮询 —— 调用方看到的是
160
+ // "WS timeout",会以为是服务端卡住。预算换算见 shared/tool_timeout.js。
161
+ function call(method, params = {}, opts = {}) {
162
+ const waitMs = Number(opts && opts.timeoutMs) > 0 ? Number(opts.timeoutMs) : timeout;
157
163
  return getWs().then((conn) => new Promise((resolve, reject) => {
158
164
  const id = ++_rpcId;
165
+ const t0 = Date.now();
159
166
  const timer = setTimeout(() => {
160
- if (_pending.has(id)) { _pending.delete(id); reject(new Error('WS timeout')); }
161
- }, timeout);
167
+ if (_pending.has(id)) {
168
+ _pending.delete(id);
169
+ // 带上方法与已耗时:否则"15 秒还是 120 秒到期"只能靠猜。
170
+ reject(new Error(`WS timeout after ${Date.now() - t0}ms (method ${method})`));
171
+ }
172
+ }, waitMs);
162
173
  _pending.set(id, (msg) => {
163
174
  clearTimeout(timer);
164
175
  if (msg.error) reject(new Error(msg.error.message || 'RPC error'));
@@ -37,7 +37,12 @@ import blankPage from '../shared/blank_page.cjs';
37
37
  // 见 shared/view_liveness.cjs 顶部(2026-10-30 白屏事故的 22 次崩溃)。
38
38
  // .cjs 用默认导入(全项目约定,且 tests/test_imports.js 的静态分析只认 ESM export)。
39
39
  import viewLiveness from '../shared/view_liveness.cjs';
40
+ import ipcGuard from '../shared/ipc_guard.cjs';
41
+ import treeFocus from '../shared/tree_focus.cjs';
42
+ import uploadGuard from '../shared/upload_guard.cjs';
43
+ import evalRoute from '../shared/eval_route.cjs';
40
44
  const { isAlive, liveness } = viewLiveness;
45
+ const { acceptResult, eventFromTab } = ipcGuard;
41
46
  // "关掉一个 tab 时哪些 per-tab 容器必须跟着消失"的唯一清单(纯函数)。
42
47
  // 为什么是表而不是逐行 delete:这类清理历史上漏过两轮(Bug 5 补了 4 个字段,
43
48
  // 2026-10-30 评估又查出 3 个漏网)。清单数据化 + 完整性闸门单测之后,
@@ -389,7 +394,9 @@ class PageManager {
389
394
  ipcMain.on('ai:tree', (_event, payload) => {
390
395
  const id = payload && payload.id;
391
396
  const pending = (id !== undefined) ? self._pendingRequests.get(id) : null;
392
- if (pending) {
397
+ // 归属校验:谁的 tab 发的、什么通道。详见 shared/ipc_guard.cjs 顶部注释
398
+ // (页面曾经能通过 __ai_browser__.sendTree 撞号喂假树)。
399
+ if (acceptResult({ senderTab: self._tabIdForContents(_event.sender), pending, expectedKind: 'tree' })) {
393
400
  self._pendingRequests.delete(id);
394
401
  pending.resolve(payload);
395
402
  }
@@ -398,7 +405,7 @@ class PageManager {
398
405
  ipcMain.on('ai:action_result', (_event, result) => {
399
406
  const id = result && result.id;
400
407
  const pending = (id !== undefined) ? self._pendingRequests.get(id) : null;
401
- if (pending) {
408
+ if (acceptResult({ senderTab: self._tabIdForContents(_event.sender), pending, expectedKind: 'action' })) {
402
409
  self._pendingRequests.delete(id);
403
410
  // Strip routing id from the payload before resolving.
404
411
  const { id: _drop, ...clean } = result;
@@ -406,23 +413,16 @@ class PageManager {
406
413
  }
407
414
  });
408
415
 
409
- ipcMain.on('ai:evaluate_result', (_event, result) => {
410
- const id = result && result.id;
411
- const pending = (id !== undefined) ? self._pendingRequests.get(id) : null;
412
- if (pending) {
413
- self._pendingRequests.delete(id);
414
- if (result.error) pending.reject(new Error(result.error));
415
- else pending.resolve(result.value);
416
- }
417
- });
418
-
419
- ipcMain.on('ai:diff', (_event, changes) => {
420
- this._broadcast('dom_change', { changes });
421
- });
416
+ // ai:diff 已删除:它唯一的产出者是 preload 暴露给页面的 sendDiff,而那个
417
+ // 暴露面在 2026-10-31 被移除(页面可借它伪造 dom_change)。通道一并删掉,
418
+ // 免得留下"能收但没人发"的死路。
422
419
 
423
420
  ipcMain.on('ai:event', (_event, payload) => {
424
- // Tag events with active tab
425
- this._broadcast(payload.event, payload.data || {});
421
+ // Tag events with the tab that produced them. 归属不明的事件不许广播 ——
422
+ // 否则一个不该发事件的上下文也能把 agent 引到别的页面上。
423
+ const tab = eventFromTab({ senderTab: self._tabIdForContents(_event.sender) });
424
+ if (tab === null) return;
425
+ self._broadcast(payload.event, { ...(payload.data || {}), tab });
426
426
  });
427
427
 
428
428
  // === window.open 垫片的主进程侧(见 preload/bridge.cjs 的注释)===
@@ -596,11 +596,15 @@ class PageManager {
596
596
  /** 组里还有哪些页(按 tabId 升序 = 创建顺序)。 */
597
597
  tabsInGroup(groupId) {
598
598
  const out = [];
599
- for (const [id] of this.tabs) {
599
+ for (const [id, view] of this.tabs) {
600
600
  if (this.groupOfTab(id) === groupId) {
601
+ // 存活判定收敛到 shared/view_liveness.cjs:视图被销毁后
602
+ // `view.webContents` 会变 undefined,裸解引用会击穿主进程
603
+ // (2026-10-30 白屏事故那一类)。这里填 null 而不是整条丢掉 ——
604
+ // 调用方要看到"这页还在、但已经读不到 URL"。
601
605
  out.push({
602
606
  id,
603
- url: this.tabs.get(id).webContents.getURL(),
607
+ url: isAlive(view) ? view.webContents.getURL() : null,
604
608
  usedAt: this._tabUsedAt.get(id) || 0,
605
609
  dialog: this._openDialogs.has(id) ? true : undefined,
606
610
  });
@@ -705,18 +709,25 @@ class PageManager {
705
709
  this._sessionTab.delete(sessionId);
706
710
  }
707
711
 
708
- _layoutAllViews(bounds) {
712
+ /**
713
+ * 视图几何的**唯一**公式。此前 `_layoutAllViews` 与 `_layoutView` 各抄一份,
714
+ * 改一处忘另一处必然漏(历史上就漏过 inset:新建 tab 走的是 _layoutView)。
715
+ */
716
+ _viewBounds(bounds) {
709
717
  // `_bottomInset`:窗口底部被别的东西占掉的高度(目前只有主进程异常横幅)。
710
- // 由 index.js 设置、这里统一扣减 —— 让每个"给视图定尺寸"的地方各自记住
711
- // 这 34px 必然会漏掉一处(新建 tab 走的是 _layoutView,不是这里)。
712
718
  const inset = this._bottomInset || 0;
719
+ return {
720
+ x: 0,
721
+ y: config.tabBarHeight,
722
+ width: bounds.width,
723
+ height: Math.max(0, bounds.height - config.tabBarHeight - inset),
724
+ };
725
+ }
726
+
727
+ _layoutAllViews(bounds) {
728
+ const rect = this._viewBounds(bounds);
713
729
  for (const [id, view] of this.tabs) {
714
- view.setBounds({
715
- x: 0,
716
- y: config.tabBarHeight,
717
- width: bounds.width,
718
- height: Math.max(0, bounds.height - config.tabBarHeight - inset),
719
- });
730
+ view.setBounds(rect);
720
731
  }
721
732
  }
722
733
 
@@ -1144,14 +1155,20 @@ class PageManager {
1144
1155
  return { ok: false, error: msg.slice(0, 300), waited_for: waitUntil };
1145
1156
  }
1146
1157
 
1147
- async getTree(focusedOnly = false, tabId) {
1158
+ /**
1159
+ * @param {boolean} focusedOnly 只返回焦点子树(见 shared/tree_focus.cjs)
1160
+ * @param {number} [tabId]
1161
+ * @param {{subset?: 'interactive'|'full'}} [opts] 剪枝选项。此前 subset/mode
1162
+ * 只在 ax:true 分支生效,默认读法**静默忽略** —— 调用方以为省了 token。
1163
+ */
1164
+ async getTree(focusedOnly = false, tabId, opts = {}) {
1148
1165
  const tid = tabId !== undefined ? tabId : this.activeTab;
1149
1166
  const view = this._getView(tid);
1150
1167
  if (!view) return { tree: null, context: null };
1151
1168
 
1152
1169
  const res = await new Promise((resolve, reject) => {
1153
1170
  const id = ++this._requestId;
1154
- this._pendingRequests.set(id, { resolve, reject });
1171
+ this._pendingRequests.set(id, { resolve, reject, tabId: tid, kind: 'tree' });
1155
1172
  view.webContents.send('ai:extract', { focusedOnly, id });
1156
1173
  setTimeout(() => {
1157
1174
  if (this._pendingRequests.has(id)) {
@@ -1167,7 +1184,7 @@ class PageManager {
1167
1184
  // 此前这条通路只在 ax:true 下存在,而**没有任何地方告诉调用方 ax:true
1168
1185
  // 的存在** —— B站图文编辑器(正文在 OOPIF 里)因此隐形了两小时,agent
1169
1186
  // 得出"编辑器没加载"的错误结论。现在默认读法自己补上这一步。
1170
- const frames = focusedOnly ? [] : await this._autoMergeOpaqueFrames(res, tid);
1187
+ const frames = await this._autoMergeOpaqueFrames(res, tid);
1171
1188
  // 「这棵树读到了多少页面文字」—— 与 frame_hints 的 text_coverage(只看帧)
1172
1189
  // 互补:那个回答"帧读够了吗",这个回答"整页读够了吗"。
1173
1190
  // 事故里 27 个节点、正文 0 字的页面,两个数字都会报警,而此前一个都没有。
@@ -1183,6 +1200,21 @@ class PageManager {
1183
1200
  const idx = await this._editorsIndex(tid, res.tree);
1184
1201
  if (idx) res.tree.editors = idx;
1185
1202
  }
1203
+ // subset:'interactive' —— 默认读法此前完全不看这个参数(只有 ax:true 分支
1204
+ // 在 getTreeViaAx 里剪枝)。判据复用同一个 filterInteractive,保证两条读法
1205
+ // 剪出来的形状一致;'full' / 缺省 = 不剪。
1206
+ if (res && res.tree && opts && opts.subset === 'interactive') {
1207
+ res.tree = axExtractor.filterInteractive(res.tree) || res.tree;
1208
+ }
1209
+ // focused_only —— 真正的裁剪在这里(抽取器不认这个参数,见 shared/tree_focus.cjs)
1210
+ if (focusedOnly && res) {
1211
+ const f = treeFocus.focusOnly(res.tree);
1212
+ res.tree = f.tree;
1213
+ if (!f.tree) {
1214
+ // 没有焦点就把话说清楚:调用方不能把"焦点不在页面上"当成"页面是空的"。
1215
+ res.context = { ...(res.context || {}), focused_only: { found: false, hint: 'No element has focus on this page. Click into a field first, or read without focused_only.' } };
1216
+ }
1217
+ }
1186
1218
  return res;
1187
1219
  }
1188
1220
 
@@ -1315,9 +1347,12 @@ class PageManager {
1315
1347
  // context 只有 modals/session/stats,登录墙、校验错误、必填提示全都来自
1316
1348
  // 这条 DOM 扫描 —— 两条读法给出不一致的 context 只会让调用方怀疑读数。
1317
1349
  async _readContext(view) {
1350
+ // 归属 tab 由 view 反查(本方法只收 view)。回执要认领 pending,就必须知道
1351
+ // 这条请求属于哪个 tab —— 见 shared/ipc_guard.cjs。
1352
+ const tid = this._tabIdForContents(view && view.webContents);
1318
1353
  const res = await new Promise((resolve, reject) => {
1319
1354
  const id = ++this._requestId;
1320
- this._pendingRequests.set(id, { resolve, reject });
1355
+ this._pendingRequests.set(id, { resolve, reject, tabId: tid, kind: 'tree' });
1321
1356
  view.webContents.send('ai:context', { id });
1322
1357
  setTimeout(() => {
1323
1358
  if (this._pendingRequests.has(id)) {
@@ -1472,8 +1507,15 @@ class PageManager {
1472
1507
  }
1473
1508
  }
1474
1509
  // 未知参数不再静默丢弃:调用方传了什么没被用上,回执里点名。
1510
+ //
1511
+ // `tab` 必须排除:它是**路由参数**(已经用来选中 tid 了),不是截图选项。
1512
+ // 此前调用方照文档传 `{tab, format}` 会收到 `ignored_params:['tab']`,
1513
+ // 看起来像"你传的 tab 被忽略了" —— 而它恰恰是唯一生效的那个。
1514
+ // 同理 `heal` / `node_id` 这类"调用层参数"也不该出现在这里。
1475
1515
  const known = { format: 1, quality: 1, fullPage: 1, clip: 1, path: 1 };
1476
- const ignored = Object.keys(opts || {}).filter((k) => !known[k]);
1516
+ const ROUTING_ONLY = { tab: 1 };
1517
+ const ignored = Object.keys(opts || {})
1518
+ .filter((k) => !known[k] && !ROUTING_ONLY[k]);
1477
1519
  return {
1478
1520
  ok: true,
1479
1521
  tab: tid,
@@ -2120,15 +2162,28 @@ class PageManager {
2120
2162
  if (r) return r;
2121
2163
  } catch (e) { /* fall through to preload */ }
2122
2164
  } else if (action === 'upload') {
2165
+ // 路径闸门(存在性 / 大小 / 敏感位置)。判据在 shared/upload_guard.cjs:
2166
+ // 这条动作能把本机任意文件塞进站点,是"读本地文件"的原语,必须拦。
2167
+ const gate = uploadGuard.checkUploadPath(params.file || '');
2168
+ if (!gate.ok) return { success: false, error: gate.error, hint: gate.hint };
2169
+ const file = gate.path;
2123
2170
  try {
2124
2171
  await this._ensureAxHandles(view, tid);
2125
- const r = await this._uploadViaCdp(view, target, params.file || '', tid);
2126
- if (r && r.success !== false) return r;
2172
+ const r = await this._uploadViaCdp(view, target, file, tid);
2173
+ // ⚠️ 不许动 `uploaded` —— 它是**文件名字符串**(既有契约:e2e/richtext F-03
2174
+ // 与调用方都按这个读)。大小与放开标记另开字段,别覆盖。
2175
+ if (r && r.success !== false) {
2176
+ return {
2177
+ ...r,
2178
+ ...(Number.isFinite(gate.size) ? { upload_bytes: gate.size } : {}),
2179
+ ...(gate.sensitive_override ? { sensitive_override: true } : {}),
2180
+ };
2181
+ }
2127
2182
  } catch (e) { /* fall through */ }
2128
2183
  // CDP 的 DOM.setFileInputFiles 只能写顶层文档里的 input;跨进程 iframe 里的
2129
2184
  // 上传控件(B站封面、编辑器插图等都属于这一类)必须走帧内注入。
2130
2185
  try {
2131
- const r = await this._uploadViaFrameJs(view, target, params.file || '', tid);
2186
+ const r = await this._uploadViaFrameJs(view, target, file, tid);
2132
2187
  if (r) return r;
2133
2188
  } catch (e) { /* fall through */ }
2134
2189
  // 无 CDP 时 preload 无法真正赋值文件(受安全限制),返回失败让 agent 感知。
@@ -2410,7 +2465,7 @@ class PageManager {
2410
2465
 
2411
2466
  return new Promise((resolve, reject) => {
2412
2467
  const id = ++this._requestId;
2413
- this._pendingRequests.set(id, { resolve, reject });
2468
+ this._pendingRequests.set(id, { resolve, reject, tabId: tid, kind: 'action' });
2414
2469
  view.webContents.send('ai:action', { action, target, params, id });
2415
2470
  setTimeout(() => {
2416
2471
  if (this._pendingRequests.has(id)) {
@@ -2462,18 +2517,27 @@ class PageManager {
2462
2517
  + ' — the ref may be stale (page re-rendered). Re-read the tree and retry.');
2463
2518
  }
2464
2519
  }
2465
- // Preferred path: CDP Runtime.evaluate. It runs on the DevTools protocol
2466
- // channel and is NOT subject to the page's CSP code-generation (eval)
2467
- // restrictions, so it works on strict sites (Bing, Gmail, ...) where the
2468
- // in-page `eval()` used by the preload bridge is blocked. It runs in the
2469
- // page's main world, identical privilege to the page's own JS (no Node:
2470
- // nodeIntegration:false + contextIsolation:true are unchanged).
2520
+ // 只有一条路:CDP Runtime.evaluate(页面的主世界,与页面自己的 JS 同权限)。
2521
+ //
2522
+ // ⚠️ 2026-10-31 删掉了原来的 `catch { return this._evaluateViaPreload(...) }`。
2523
+ // 那个 catch 把**页面脚本自己抛的异常**当成"CDP 不可用",于是任何会抛错的
2524
+ // 表达式都会被拿到 preload 用 Node 的 eval 重跑一次。实测
2525
+ // Function('return globalThis["pro"+"cess"].version')()
2526
+ // 拿到 "v20.18.3" —— 页面 → 宿主代码执行。guards.js 的正则只是字面量黑名单,
2527
+ // 拆词拼接即可绕过,所以"留一条降级路"不是安全选项。
2471
2528
  try {
2472
2529
  return await this._evaluateViaCdp(view, js);
2473
2530
  } catch (e) {
2474
- // Fallback: the original preload (ai:evaluate) path, for views without a
2475
- // usable CDP debugger (and for the vitest unit tests that mock IPC).
2476
- return await this._evaluateViaPreload(view, js);
2531
+ // 分类后**如实**抛出:脚本错就说脚本错(调用方该改脚本),环境错才说环境错。
2532
+ // 判据在 shared/eval_route.cjs(纯函数,表驱动单测钉住每种消息)。
2533
+ const r = evalRoute.evalFailureResult(e);
2534
+ const err = new Error(
2535
+ r.error.code === 'script-error' ? r.error.message : r.error.message + ' — ' + r.error.hint
2536
+ );
2537
+ err.code = r.error.code;
2538
+ err.hint = r.error.hint;
2539
+ err.retryable = r.error.retryable;
2540
+ throw err;
2477
2541
  }
2478
2542
  }
2479
2543
 
@@ -2511,20 +2575,6 @@ class PageManager {
2511
2575
  return r ? r.value : undefined;
2512
2576
  }
2513
2577
 
2514
- _evaluateViaPreload(view, js) {
2515
- return new Promise((resolve, reject) => {
2516
- const id = ++this._requestId;
2517
- this._pendingRequests.set(id, { resolve, reject });
2518
- view.webContents.send('ai:evaluate', { js, id });
2519
- setTimeout(() => {
2520
- if (this._pendingRequests.has(id)) {
2521
- this._pendingRequests.delete(id);
2522
- reject(new Error('evaluate timeout'));
2523
- }
2524
- }, 5000);
2525
- });
2526
- }
2527
-
2528
2578
  // === CDP 受信输入(通用化,无框架特判)===
2529
2579
  // 任何网页/富文本/编辑器(Draft、ProseMirror、Quill、antd、shadcn…)都无需
2530
2580
  // 专项适配:点击/键盘/文本全部走 Chromium 真实输入管线(受信事件),等价于
@@ -5098,14 +5148,7 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
5098
5148
  }
5099
5149
 
5100
5150
  _layoutView(view) {
5101
- const bounds = this.window.getContentBounds();
5102
- const inset = this._bottomInset || 0;
5103
- view.setBounds({
5104
- x: 0,
5105
- y: config.tabBarHeight,
5106
- width: bounds.width,
5107
- height: Math.max(0, bounds.height - config.tabBarHeight - inset),
5108
- });
5151
+ view.setBounds(this._viewBounds(this.window.getContentBounds()));
5109
5152
  }
5110
5153
 
5111
5154
  addSubscription(sessionId, events) {
@@ -5521,8 +5564,26 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
5521
5564
  }
5522
5565
  const entry = this._cdpTabs.get(tabId);
5523
5566
  if (!entry.domains.has(domain)) {
5524
- wc.debugger.sendCommand(domain + '.enable');
5567
+ // ⚠️ 记账必须能被撤销(2026-10-31 复核)。
5568
+ // 原实现是 `sendCommand(...); domains.add(domain)` —— 发出即算启用。
5569
+ // 一旦 enable 被 reject(导航中 / 域不可用),domains 里就**永久**留着
5570
+ // 一个没启用的域,之后所有依赖它的命令(Runtime.evaluate / Network.*)
5571
+ // 都以"看起来可用"的姿态失败,查起来像是工具本身坏了。
5572
+ // 这里返回 promise 并挂拒绝处理:失败就删掉记账、落盘一条原因,下次重试。
5525
5573
  entry.domains.add(domain);
5574
+ const p = wc.debugger.sendCommand(domain + '.enable');
5575
+ if (p && typeof p.then === 'function') {
5576
+ p.catch((e) => {
5577
+ try { entry.domains.delete(domain); } catch (_e) {}
5578
+ recordError('cdp_enable_failed', {
5579
+ tab: tabId,
5580
+ domain,
5581
+ message: String((e && e.message) || e).slice(0, 300),
5582
+ note: 'CDP 域启用失败,已撤销记账(下次调用会重试)',
5583
+ });
5584
+ });
5585
+ }
5586
+ return p;
5526
5587
  }
5527
5588
  } catch (e) { /* mid-navigation / already-attached elsewhere; skip this tab */ }
5528
5589
  }
@@ -5849,8 +5910,6 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
5849
5910
  this.tabs.clear();
5850
5911
  ipcMain.removeAllListeners('ai:tree');
5851
5912
  ipcMain.removeAllListeners('ai:action_result');
5852
- ipcMain.removeAllListeners('ai:evaluate_result');
5853
- ipcMain.removeAllListeners('ai:diff');
5854
5913
  ipcMain.removeAllListeners('ai:event');
5855
5914
  }
5856
5915
  }