@glittering0717/ai-browser 2.1.21 → 2.3.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
@@ -335,51 +335,109 @@ Notes that save round-trips:
335
335
 
336
336
  ## Letting a human step in
337
337
 
338
- ### It does not steal your focus
338
+ ### It does not steal your focus — and it does not need a window at all
339
339
 
340
- The agent works fine while the window is in the **background**. CDP trusted input
341
- (`Input.dispatchKeyEvent` / `Input.dispatchMouseEvent`) does not need the window to be frontmost, and
342
- the app already runs with `disable-backgrounding-occluded-windows`, `disable-renderer-backgrounding`
343
- and `disable-background-timer-throttling`, so a background window is neither throttled nor losing
344
- events.
340
+ The agent works fine while the window is in the **background**, minimised, or **not shown at all**.
341
+ CDP trusted input (`Input.dispatchKeyEvent` / `Input.dispatchMouseEvent`) does not need the window to
342
+ be frontmost, and the app runs with `disable-backgrounding-occluded-windows`,
343
+ `disable-renderer-backgrounding` and `disable-background-timer-throttling`, so a hidden window is
344
+ neither throttled nor losing events. Every tab also gets `setBackgroundThrottling(false)` from birth.
345
345
 
346
- That was already true for `act` / `get_tree` / `evaluate` / `peek` / `scroll` — but two paths used to
347
- drag the window to the front on **every** call: `new_tab` and `set_active_tab` (they called
348
- `webContents.focus()`, which activates the whole window). On top of that the window was shown with
349
- `show()` at boot even when the *agent* launched it. Both are fixed:
346
+ Three things used to make "run it in the background" impossible, and all three are fixed:
350
347
 
351
- - `new_tab` / `set_active_tab` no longer take window focus. The page still *thinks* it is focused —
348
+ - `new_tab` / `set_active_tab` dragged the window to the front on every call (they called
349
+ `webContents.focus()`). They no longer do. The page still *thinks* it is focused —
352
350
  `Emulation.setFocusEmulationEnabled` keeps `document.hasFocus()` and focus-dependent lazy-loading
353
- behaving normally — while the keyboard focus stays wherever you left it.
354
- - When the agent launches the browser (over MCP), the window appears via `showInactive()`:
355
- **visible, but not stealing focus**. When *you* run `npm start`, it comes up in front as usual.
356
-
357
- So the window stays visible — that is the whole point — but it is **not** dragged to the front while
358
- the agent drives. You can keep working.
351
+ behaving normally — while your keyboard focus stays wherever you left it.
352
+ - Any action **un-hid** a hidden window (`auto` restored it with `showInactive()`), so "hidden" was
353
+ never a steady state: the window crept back up every time the agent clicked something. Visibility is
354
+ now driven only by you (Dock icon) or by an explicit `ui.window` call.
355
+ - A tab that was never attached to the window had **no compositor surface**: reading, clicking and
356
+ typing worked, but `screenshot` returned 0 bytes and `paint_check` reported `no-frame` — a black box.
357
+ All tabs are now attached and z-ordered (`setTopBrowserView`), so a background tab renders and can be
358
+ screenshotted.
359
359
 
360
360
  ```bash
361
- AI_BROWSER_FOCUS=always npm start # pre-1.2 behaviour: show + moveTop + focus on every action
362
- AI_BROWSER_FOCUS=never npm start # never change focus (the window is still shown)
361
+ AI_BROWSER_START_HIDDEN=1 npm start # run with no window at all; click the Dock icon to bring it up
362
+ AI_BROWSER_FOCUS=always npm start # pre-1.2 behaviour: show + moveTop + focus on every action
363
+ AI_BROWSER_FOCUS=never npm start # same as the default now: never touch window state
363
364
  ```
364
365
 
365
- Default is `auto`: keep the window visible (restore it if it was minimised or hidden), but never steal
366
- focus. Whatever the value, the window is always displayed — that is a product invariant.
367
-
368
- `npm run focus` asserts all of this **from the outside** (macOS `lsappinfo`, no accessibility
369
- permission needed) and includes a deliberate control group configured to steal focus — so the suite
370
- would go red if the measurement ever stopped working, instead of passing vacuously.
366
+ While it is hidden, everything still works — read the tree, click, type, scroll, upload, download,
367
+ answer dialogs, capture network, screenshot, `paint_check`. Click the Dock icon at any moment and the
368
+ window appears showing the tab *you* were looking at; the agents keep working on theirs.
371
369
 
372
- It also proves the stronger claim — that the window **does not need to be in the foreground at all**.
373
- With another app holding the foreground, it runs a representative slice of the API and checks the real
374
- result of each one: typing lands, a click fires exactly once, `get_tree` returns a tree, canvas
375
- `getImageData` returns real pixels, `network_list` sees the request, `navigate` completes — and after
376
- sitting in the background for 10 seconds it still does all of the above without ever coming forward.
370
+ `npm run focus` asserts the focus behaviour **from the outside** (macOS `lsappinfo`, no accessibility
371
+ permission needed) with a deliberate control group configured to steal focus, so the suite goes red if
372
+ the measurement ever stops working instead of passing vacuously. `npm run background` covers the
373
+ window-hidden half: it boots with `AI_BROWSER_START_HIDDEN=1` and runs the full capability slice
374
+ against a window that never appeared.
377
375
 
378
376
  > Note on `document.hasFocus()`: it returns `true` even when the window is in the background, because
379
377
  > `Emulation.setFocusEmulationEnabled` is deliberately on — that is what keeps focus-dependent
380
378
  > lazy-loading and animations from stalling. So it is **not** a valid way to detect "am I in the
381
379
  > foreground"; the test uses the external observer instead.
382
380
 
381
+ ### Several agents at once
382
+
383
+ Each WebSocket connection (each MCP process) gets **its own working tab**. When a call omits `tab`,
384
+ the target is resolved as `explicit > your tab > the tab the human is looking at > the first tab`, so:
385
+
386
+ - `browse_tabs {"op":"new"}` opens a tab **without** taking over the user's view (`show:true` when you
387
+ want them to look at it). The single exception is the untouched start page — otherwise the user
388
+ would sit staring at a blank homepage while the agent works.
389
+ - `browse_tabs {"op":"list"}` marks your own tab with `mine: true`.
390
+ - If **someone else** closes your tab, your next call fails with `-32001` instead of silently running
391
+ on their page. Closing your *own* tab falls back to the visible one, like a normal browser.
392
+ - Tabs opened by a click (`target=_blank`) move your **target** to the new tab; they only move the
393
+ user's **view** if the tab they were watching is the one that opened them.
394
+
395
+ Different tabs run fully in parallel. Two agents typing into the *same* field is not coordinated —
396
+ the write-verification will honestly report `input not verified` rather than pretending both landed.
397
+
398
+ `npm run multiagent` drives two connections against one browser and asserts all of the above,
399
+ including 10 interleaved actions with no cross-contamination.
400
+
401
+ ### Tab groups: every agent gets its own corner
402
+
403
+ Targets are per-connection, but tabs still shared one strip — you could not tell whose tab was whose,
404
+ and nothing stopped an agent from opening twenty of them. Both are fixed by **ownership**:
405
+
406
+ ```
407
+ group = 'human' | 'agent:<session>'
408
+ ```
409
+
410
+ An agent declares itself with `ui.hello` (the MCP server and the CLI both do it on connect). From then
411
+ on, the **first** call that touches a page and has no target yet gets a blank tab of its own, in its own
412
+ group, and a one-time hint in the result:
413
+
414
+ ```json
415
+ {"workspace": {"tab": 7, "group": "Claude", "created": true, "hint": "..."}}
416
+ ```
417
+
418
+ So an agent **never** defaults to the tab you are looking at. Reading your page is still possible and
419
+ still cheap — `browse_tabs {"op":"list"}`, find the entry with `group: "human"`, pass its `tab`
420
+ explicitly. Reading does not take it over.
421
+
422
+ In the tab strip your tabs stay as they were; each agent group collapses into a pill (its colour, name
423
+ and tab count), expands on hover, pins on click, and stays expanded while you are looking at one of its
424
+ tabs. Clicking a tab inside a group only changes what **you** see — it does not change the agent's target.
425
+
426
+ Each group is capped (8 by default, `AI_BROWSER_TAB_LIMIT`). Opening past the cap is **refused**, not
427
+ "quietly evicted", with the list of tabs you could close:
428
+
429
+ ```
430
+ -32001 your tab group is full (8/8) — close one before opening another
431
+ data: { reason: "group-full", limit: 8, tabs: [{tab, url}, ...] }
432
+ ```
433
+
434
+ Popups cannot be refused (the page's script is waiting for the window), so in that one case the least
435
+ recently used tab in the group — never the visible one, never one with a dialog open — is closed
436
+ instead, and reported in `browse_tabs {"op":"list"}` as `evicted`.
437
+
438
+ `npm run multiagent` (46 checks) covers it, M7–M9: auto workspace, the cap and its refusal payload,
439
+ and that one full group does not affect anybody else's.
440
+
383
441
  ---
384
442
 
385
443
  This is the part most easily misunderstood, so plainly: **the agent drives the browser, and the human
@@ -724,7 +782,7 @@ not bugs. The full write-up, including why the first measurement of this was wro
724
782
  ## Test & dev
725
783
 
726
784
  ```bash
727
- npm test # vitest — 988 tests across 70 files
785
+ npm test # vitest — 1024 tests across 73 files
728
786
  npm run smoke # Electron contract layer, offline fixture — 31 checks
729
787
  npm run capabilities # text fields, canvas, page source, network, DOM editing — 54 checks
730
788
  npm run richtext # rich-text editors, nested menus, forms, errors, tags, upload — 117 checks
@@ -734,7 +792,7 @@ npm run canvas # canvas draw-call capture — 13 checks
734
792
  npm run modeldiff # canvas app data-model diff (the "unchanged" false green) — 12 checks
735
793
  npm run audit # every advertised action must exist; wait/downloads/permissions/quit — 35 checks
736
794
  npm run nav # address bar + load-failure error page (the "white screen" report) — 19 checks
737
- npm run focus # no focus stealing + full capability while backgrounded — 32 checks
795
+ npm run focus # no focus stealing + full capability while backgrounded — 33 checks
738
796
  npm run interact # trusted drag / key press / wheel (pointer gestures) — 31 checks
739
797
  npm run view # viewport repaint budget + snapshot/diff verification — 29 checks
740
798
  npm run dialog # browser-level dialogs (native sheet blocks the renderer) — 15 checks
@@ -742,8 +800,10 @@ npm run wrapper # "in the tree but won't click" = matched a container, not
742
800
  npm run paint # blank-page self-check: verdicts, bounded ladder, no false alarms — 23 checks
743
801
  npm run layout # geometry invariants + "no twitching" (zero extra repaints on nav) — 25 checks
744
802
  npm run download # "clicked download": viewable media must display, the rest must save — 23 checks
803
+ npm run multiagent # several agents at once: own tab each, no cross-talk, gone tab errors — 46 checks
804
+ npm run background # window hidden/minimized: every capability still works (headless-like) — 37 checks
745
805
  npm run flicker # frame-level: no frame may render the page shrunk (needs screen recording) — 6 checks
746
- npm run e2e:all # 一次跑完上面全部 20 个套件(每个独立端口)+ 可信汇总 — 659 checks
806
+ npm run e2e:all # 一次跑完上面全部 22 个套件(每个独立端口)+ 可信汇总 — 743 checks
747
807
  npm run verify:app # boot the packaged /Applications app and assert on it — 22 checks
748
808
  npm run realsites # navigate/read/act against a matrix of real sites
749
809
  ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@glittering0717/ai-browser",
3
- "version": "2.1.21",
3
+ "version": "2.3.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": {
@@ -88,7 +88,9 @@
88
88
  "paint": "node e2e/paint_ws.cjs",
89
89
  "layout": "node e2e/layout_ws.cjs",
90
90
  "flicker": "node e2e/flicker_ws.cjs",
91
- "download": "node e2e/download_ws.cjs"
91
+ "download": "node e2e/download_ws.cjs",
92
+ "multiagent": "node e2e/multiagent_ws.cjs",
93
+ "background": "node e2e/background_ws.cjs"
92
94
  },
93
95
  "dependencies": {
94
96
  "@modelcontextprotocol/sdk": "^1.29.0",
@@ -92,6 +92,15 @@ function rpcCall({ port, timeout, method, params }) {
92
92
  }, timeout);
93
93
 
94
94
  ws.on('open', () => {
95
+ // 自报家门,但**不要**自动工作区:CLI 是人坐在终端前敲的,"不传 tab
96
+ // 就打当前页"才是他期望的语义。auto_workspace:false 只关掉"自动开一页",
97
+ // 分组照旧 —— 它自己 new_tab 出来的页仍然归到 "Terminal" 组里。
98
+ try {
99
+ ws.send(JSON.stringify({
100
+ jsonrpc: '2.0', method: 'ui.hello',
101
+ params: { label: 'Terminal', auto_workspace: false },
102
+ }));
103
+ } catch (_) { /* 发不出去就退化成匿名连接 */ }
95
104
  ws.send(JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }));
96
105
  });
97
106
  ws.on('message', (data) => {
@@ -7,30 +7,31 @@ description: >-
7
7
 
8
8
  # ai-browser
9
9
 
10
- ## 两条路,选一条就能干活
10
+ ## 两条路
11
11
 
12
- 工具在就 `browse_navigate {"url":"https://example.com"}`;**不在也不用配任何东西**,走 CLI(同一引擎,装完即用):
12
+ 工具在就 `browse_navigate {"url":"https://example.com"}`。不在也不用配,走 CLI(同一引擎):
13
13
 
14
14
  ```
15
15
  ai-browser call ui.get_tree '{"subset":"interactive"}' # 读页面,拿 e:xxx
16
16
  ai-browser call ui.act '{"action":"click","target":"e:a-3"}' # 点它
17
- ai-browser call ui.navigate '{"url":"https://example.com"}'
18
17
  ```
19
18
 
20
- 没这个命令就加前缀 `npx -y @glittering0717/ai-browser`。浏览器没开时会自动拉起。
19
+ 没这个命令就加 `npx -y @glittering0717/ai-browser`,浏览器没开会自动拉起。
20
+ 方法名 = 工具名把 `browse_` 换成 `ui.`(tabs 等例外)。
21
21
 
22
- CLI 方法 = 工具名去掉 `browse_` 换 `ui.`(`get_tree` `act` `navigate` … 一一对应)。
23
- 不一一对应的 4 个(tabs/network/canvas/diff)见 `references/cli.md`。
22
+ ## 你的标签组
23
+
24
+ 第一次动手会给你一页**空白工作页**,归在你自己的标签组;多 agent 各一组,互不相干。
25
+ 省略 `tab` 就打它;用户的页不会被碰也不会被顶掉。组有上限,满了先关再开。
26
+ 看用户的页 / 人登录扫码 / 全程后台:`references/tabs.md`。
24
27
 
25
28
  ## 点东西只认 id
26
29
 
27
- `get_tree` 每个节点有 `id`(形如 `e:a-3`)。`act` 的 `target` **只接受这个 id**,
28
- 传页面上的文字会报 `target_not_found`。
30
+ `act` 的 `target` 只认 `get_tree` 给的 id;传文字会报 `target_not_found`。
29
31
 
30
32
  ## 操作后先看 effect_state
31
33
 
32
- `committed` 已生效 → 继续|`none` 页面没动 → 换 target 或重读树|
33
- `unknown` 说不准 → **先重读树再决定**,盲目重试会提交两次。
34
+ `committed` 继续|`none` 换 target 或重读树|`unknown` **先重读树**再决定,盲目重试会提交两次。
34
35
 
35
36
  ## 卡住时
36
37
 
@@ -45,10 +46,11 @@ CLI 方法 = 工具名去掉 `browse_` 换 `ui.`(`get_tree` `act` `navigate`
45
46
 
46
47
  ## 需要人帮忙
47
48
 
48
- 登录/扫码/滑块/支付:**请用户在自己的窗口里操作**,他说"好了"再重读树确认。不要编造密码。
49
+ 登录、扫码、滑块、支付:请用户在窗口里操作,说"好了"再重读树;不要编造密码。
49
50
 
50
51
  ## 按需深挖
51
52
 
53
+ - `references/tabs.md` — 标签组、上限、把页面交给人的正确姿势
52
54
  - `references/cli.md` — CLI 全部方法与参数对照
53
55
  - `references/troubleshooting.md` — 失败排查顺序
54
56
  - `references/hard-pages.md` — canvas / 富文本 / iframe / 上传
@@ -0,0 +1,66 @@
1
+ # 标签组:每个 agent 一块自己的空间
2
+
3
+ 浏览器里同时有两个人在干活:**用户**,和**每一个 agent**。他们的标签页不混在一起。
4
+
5
+ ## 你的工作页从哪来
6
+
7
+ 第一次真正动手(读树、导航、点击…)而还没指定过目标时,浏览器会给你开一页
8
+ **空白标签**并归到你自己的组里。回执里会出现一次:
9
+
10
+ ```json
11
+ {"workspace": {"tab": 7, "group": "Agent 2", "created": true, "hint": "..."}}
12
+ ```
13
+
14
+ 从那以后,**省略 `tab` 就等于打这一页**。这不是"当前显示的那一页" —— 用户切到哪
15
+ 都不会改变你的目标。
16
+
17
+ ## 三条容易踩的
18
+
19
+ | 情况 | 会发生什么 |
20
+ |---|---|
21
+ | 你显式传了 `tab` | 就按你点的来(不会因此把目标钉住;只有 `new` / `switch` 才会改默认目标) |
22
+ | 你的页被别人关了 | 下一次调用报 `-32001 ... is gone`,**不会**悄悄换到别人的页上。自己 `new` 一页继续 |
23
+ | 你想同时干两件事 | 开多个 tab,并发调用时各自带 `tab`。同一页上的并发写不做协调(值校验会如实报 `input not verified`) |
24
+
25
+ ## 上限
26
+
27
+ 每个组默认 **8 页**(`AI_BROWSER_TAB_LIMIT` 可调)。满了:
28
+
29
+ ```
30
+ -32001 your tab group is full (8/8) — close one before opening another
31
+ data.tabs = [{tab, url}, ...]
32
+ ```
33
+
34
+ 先把不用的关掉(`browse_tabs {"op":"close","tab":N}`)再开。上限存在的意义不是
35
+ 刁难:后台运行时没人看得见你的标签页,不设限就会一路开到内存告急。
36
+
37
+ 页面自己弹的窗口(`window.open` / `target=_blank`)不能拒绝 —— 站点的脚本在等它。
38
+ 那种情况下会顶掉本组里**最久没用、不在人眼前、也没有挂着对话框**的那一页,
39
+ 并在下一次 `browse_tabs {"op":"list"}` 的 `evicted` 里告诉你。
40
+
41
+ ## 把页面交给用户
42
+
43
+ 用户要用自己的眼睛/手介入时(登录、扫码、滑块、确认支付、看结果):
44
+
45
+ ```
46
+ browse_tabs {"op":"switch","tab":7,"show":true}
47
+ ```
48
+
49
+ `switch` 同时做两件事:把这一页顶到用户眼前,并把它设成你的默认目标。
50
+ 只想让用户**看**、不想改自己的目标,就不要用它 —— 用户自己点标签页就行。
51
+
52
+ 用户点开你那一页只是"看",**不会**抢走你的目标;你继续在上面操作,他看到的是
53
+ 实时画面。要避免"我正要输入他却盯着看"的尴尬,就提前说一句。
54
+
55
+ ## 关于"后台"
56
+
57
+ ```json
58
+ {"op": "window", "visible": false}
59
+ ```
60
+
61
+ 窗口隐藏后所有能力照旧:读树、点击、输入、滚动、上传、对话框、抓包、截图、白屏自检。
62
+ 单实例启动时也可以用 `AI_BROWSER_START_HIDDEN=1` 让窗口从头就不出现。
63
+ 用户点 Dock 图标随时叫回来,落在他上次看的那一页,你的任务不受影响。
64
+
65
+ ⚠️ 只有隐藏窗口**不等于**没人看:用户可能正盯着你那一页。别在页面上做会让人
66
+ 误解的连续操作(比如连续删除)。
package/src/main/index.js CHANGED
@@ -355,6 +355,21 @@ if (gotLock) {
355
355
  mainWindow.focus();
356
356
  }
357
357
  });
358
+ // Dock 图标被点击(macOS 上"再点一次已运行的应用"、或窗口被隐藏后想找回它)。
359
+ //
360
+ // 后台模式(AI_BROWSER_START_HIDDEN / ui.window{visible:false})下窗口默认是隐藏的,
361
+ // 这是人把它叫回来的**唯一**约定入口 —— 没有它,"随时可以点开使用"就成了空话,
362
+ // 用户只能去活动监视器里杀进程。
363
+ app.on('activate', () => {
364
+ if (!mainWindow || mainWindow.isDestroyed()) return;
365
+ try {
366
+ if (pageManager && pageManager.setWindowVisible) {
367
+ pageManager.setWindowVisible(true, { focus: true });
368
+ } else {
369
+ mainWindow.show();
370
+ }
371
+ } catch (_) { /* 窗口正在销毁 */ }
372
+ });
358
373
  } else if (!(process.platform === 'darwin' && app.isPackaged)) {
359
374
  // A real second instance would fight the first one over the :9223 WS port.
360
375
  // Still tolerant of weird environments (EPERM on sandboxed setups, and
@@ -446,7 +461,7 @@ function createWindow() {
446
461
  const START_URL = process.env.AI_BROWSER_START_URL !== undefined
447
462
  ? (process.env.AI_BROWSER_START_URL || null)
448
463
  : 'https://www.baidu.com';
449
- pageManager.newTab(START_URL);
464
+ pageManager.startupTab = pageManager.newTab(START_URL);
450
465
 
451
466
  // 启动阶段崩溃排的队到这里兑现:窗口、标签栏、页面视图都已就绪,横幅才挂得上。
452
467
  flushPendingBanner();
@@ -705,10 +720,19 @@ function showInitialWindow() {
705
720
  if (!mainWindow) return;
706
721
  const policy = String(process.env.AI_BROWSER_FOCUS || 'auto').toLowerCase();
707
722
  const byAgent = process.env.AI_BROWSER_LAUNCHED_BY_AGENT === '1';
708
- // 窗口**一定**要显示出来 —— 这是产品不变量(人可随时手动介入:登录、扫码、过验证码、
709
- // 纠正 agent 的操作),任何策略值都不允许把窗口变成看不见的黑盒。
710
- // 策略只决定**显示时抢不抢焦点**:只有人手动启动、或显式 always,才显示并激活;
711
- // agent 拉起(或 never)走 showInactive —— 窗口出现,但键盘焦点留在用户那边。
723
+ // 后台模式:进程起来但**不出窗口**。这是"跟无头浏览器一样无感知运行"的入口 ——
724
+ // agent 无人值守跑任务时,不该在用户桌面上开一个窗口。
725
+ // 与"人可随时介入"不矛盾:Dock 图标一点(app 'activate')就显示出来,
726
+ // 也可以 ui.window{visible:true} 显式打开。
727
+ if (/^(1|true|yes|on)$/i.test(String(process.env.AI_BROWSER_START_HIDDEN || ''))) {
728
+ console.log('[window] AI_BROWSER_START_HIDDEN=1 — 后台运行,窗口不显示(Dock 点击可打开)');
729
+ pageManager.windowShownAt = null;
730
+ return;
731
+ }
732
+ // 默认(非后台模式):窗口**一定**要显示出来 —— 人可随时手动介入(登录、扫码、
733
+ // 过验证码、纠正 agent 的操作)。策略只决定**显示时抢不抢焦点**:只有人手动启动、
734
+ // 或显式 always,才显示并激活;agent 拉起走 showInactive —— 窗口出现,但键盘焦点
735
+ // 留在用户那边。
712
736
  const shouldActivate = policy === 'always' || (policy !== 'never' && !byAgent);
713
737
 
714
738
  const doShow = () => {
@@ -44,8 +44,25 @@ const wsClient = createWsClient({
44
44
  url: WS_URL,
45
45
  timeout: WS_TIMEOUT,
46
46
  ensureRunning: () => ensureBrowser(),
47
+ // 自报家门:告诉浏览器"我是一个 agent",于是它会给我一块自己的标签组
48
+ // (默认目标永远是组里我自己的页,绝不开在人眼前那一页上)。
49
+ // 名字只用于标签栏上那个小圆点旁边的文字,猜不出来就留空让服务端编号。
50
+ hello: { label: agentLabel(), auto_workspace: true },
47
51
  });
48
52
 
53
+ /** 从环境推断是哪个客户端在驱动我。猜不出来就返回空串(服务端会编 "Agent N")。 */
54
+ function agentLabel() {
55
+ const env = process.env;
56
+ const explicit = String(env.AI_BROWSER_AGENT_NAME || '').trim();
57
+ if (explicit) return explicit.slice(0, 24);
58
+ if (env.CLAUDECODE || env.CLAUDE_CODE_ENTRYPOINT) return 'Claude';
59
+ if (env.CURSOR_TRACE_ID || env.CURSOR_AGENT) return 'Cursor';
60
+ if (env.TRAE_ENV || env.TRAE_AGENT) return 'Trae';
61
+ if (env.CODEX_HOME || env.OPENAI_CODEX) return 'Codex';
62
+ if (env.CLINE_ACTIVE) return 'Cline';
63
+ return '';
64
+ }
65
+
49
66
  /** 拉起浏览器(幂等)。失败时抛带原因的 Error,由 mcp_ws 并进最终错误信息。 */
50
67
  async function ensureBrowser() {
51
68
  const info = await ensureRunning({
@@ -190,7 +207,11 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
190
207
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
191
208
  }
192
209
  if (op === 'new') {
193
- const result = await wsClient.call('ui.new_tab', { url: args.url || null });
210
+ // show 不传 = 后台新建:agent 开页面不该把人正在看的那一页顶掉。
211
+ // 这是"多 agent / 无头式运行"的默认语义,见 shared/tab_route.cjs。
212
+ const params = { url: args.url || null };
213
+ if (args.show !== undefined) params.show = args.show === true;
214
+ const result = await wsClient.call('ui.new_tab', params);
194
215
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
195
216
  }
196
217
  if (op === 'close') {
@@ -198,11 +219,18 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
198
219
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
199
220
  }
200
221
  if (op === 'switch') {
201
- const result = await wsClient.call('ui.set_active_tab', { tab: args.tab });
222
+ // 只换目标、不抢视野:agent 说"切到这个标签页"通常只是想说
223
+ // "接下来都在这页上干活",不该把人的窗口内容换掉。
224
+ const result = await wsClient.call('ui.set_active_tab', { tab: args.tab, show: false });
225
+ return { content: [{ type: 'text', text: JSON.stringify(result) }] };
226
+ }
227
+ if (op === 'window') {
228
+ const params = args.visible === undefined ? {} : { visible: args.visible === true };
229
+ const result = await wsClient.call('ui.window', params);
202
230
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
203
231
  }
204
232
  return {
205
- content: [{ type: 'text', text: `Error: unknown op "${op}" — use list / new / close / switch` }],
233
+ content: [{ type: 'text', text: `Error: unknown op "${op}" — use list / new / close / switch / window` }],
206
234
  isError: true
207
235
  };
208
236
  }
@@ -11,7 +11,7 @@ export const MCP_TOOLS = [
11
11
  {
12
12
  name: 'browse_navigate',
13
13
  title: 'Navigate tab',
14
- description: 'Navigate the active/focused tab to a URL. Returns as soon as the requested milestone is reached (default: DOM ready) — it does not wait for the load event, which SPAs often never fire.',
14
+ description: 'Navigate your tab to a URL. Returns at the requested milestone (default: DOM ready) — it does not wait for load, which SPAs often never fire.',
15
15
  annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true },
16
16
  inputSchema: {
17
17
  type: 'object',
@@ -90,31 +90,31 @@ export const MCP_TOOLS = [
90
90
  },
91
91
  drag: {
92
92
  type: 'object',
93
- description: 'drag only. Give from/to for absolute points, dx/dy for a relative move, or target_to to drop onto another element.',
93
+ description: 'drag only. from/to = points, dx/dy = relative, target_to = drop onto an element.',
94
94
  properties: {
95
95
  from: {
96
96
  type: 'object',
97
- description: 'Start point. Omit to start from target.',
97
+ description: 'Start point (default: target).',
98
98
  properties: {
99
99
  x: { type: 'number' },
100
100
  y: { type: 'number' },
101
- anchor: { type: 'string', enum: ['center', 'left', 'right', 'top', 'bottom'], description: 'A side prefers that node\'s connection handle.' }
101
+ anchor: { type: 'string', enum: ['center', 'left', 'right', 'top', 'bottom'], description: 'A side prefers that handle.' }
102
102
  }
103
103
  },
104
104
  to: {
105
105
  type: 'object',
106
- description: 'End point in viewport coords.',
106
+ description: 'End point (viewport).',
107
107
  properties: {
108
108
  x: { type: 'number' },
109
109
  y: { type: 'number' },
110
110
  anchor: { type: 'string', enum: ['center', 'left', 'right', 'top', 'bottom'] }
111
111
  }
112
112
  },
113
- dx: { type: 'number', description: 'Horizontal distance instead of to.x.' },
114
- dy: { type: 'number', description: 'Vertical distance instead of to.y.' },
115
- target_to: { type: 'string', description: 'data-ai-id to drop onto (e.g. connect one node\'s output to another).' },
116
- hold: { type: 'array', items: { type: 'string' }, description: 'Modifiers held during the drag, e.g. ["Shift"].' },
117
- button: { type: 'string', enum: ['left', 'middle', 'right'], description: 'Canvas apps often pan on middle/right drag.' }
113
+ dx: { type: 'number', description: 'Instead of to.x.' },
114
+ dy: { type: 'number', description: 'Instead of to.y.' },
115
+ target_to: { type: 'string', description: 'data-ai-id to drop onto.' },
116
+ hold: { type: 'array', items: { type: 'string' }, description: 'Held modifiers, e.g. ["Shift"].' },
117
+ button: { type: 'string', enum: ['left', 'middle', 'right'], description: 'Canvas apps pan on middle/right drag.' }
118
118
  }
119
119
  },
120
120
  tab: { type: 'integer', description: 'Tab id (default: active tab).' }
@@ -184,7 +184,7 @@ export const MCP_TOOLS = [
184
184
  {
185
185
  name: 'browse_screenshot',
186
186
  title: 'Screenshot the viewport',
187
- description: 'Screenshot the viewport (base64 in data). Use FIRST when an action misbehaves: the element tree cannot show overlays, canvas, occlusion or glitches. Warns if a visible password input is on screen.',
187
+ description: 'Screenshot the viewport (base64). Use FIRST when an action misbehaves: the tree cannot show overlays, canvas, occlusion or glitches. Warns about visible password inputs.',
188
188
  annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: true },
189
189
  inputSchema: {
190
190
  type: 'object',
@@ -210,7 +210,7 @@ export const MCP_TOOLS = [
210
210
  {
211
211
  name: 'browse_tabs',
212
212
  title: 'Tabs',
213
- description: 'Tabs: op=list / new / close / switch. switch makes a tab the default target for later calls, so you rarely pass tab explicitly.',
213
+ description: 'Tabs: list/new/close/switch/window. Yours are grouped and capped (list: count/limit). Full → close one. switch = default target. new never steals the view unless show:true. window = hide/show.',
214
214
  // 合并前是 4 个工具(list / new / close / set_active),每个只承载一个动词。
215
215
  // 合并后 destructiveHint 只能是 false —— 否则 op=list 也会被标成破坏性操作;
216
216
  // close 的破坏性写在 description 里。这是合并的唯一语义代价,接受。
@@ -218,9 +218,11 @@ export const MCP_TOOLS = [
218
218
  inputSchema: {
219
219
  type: 'object',
220
220
  properties: {
221
- op: { type: 'string', enum: ['list', 'new', 'close', 'switch'], description: 'list = id/url/title/active for every tab. switch = make `tab` the default target.' },
221
+ op: { type: 'string', enum: ['list', 'new', 'close', 'switch', 'window'], description: 'list = every tab; switch = set default; window = hide/show.' },
222
222
  tab: { type: 'integer', description: 'close / switch: the target tab id.' },
223
- url: { type: 'string', description: 'new: open at this URL (default about:blank).' }
223
+ url: { type: 'string', description: 'new: open at this URL (default about:blank).' },
224
+ show: { type: 'boolean', description: 'new: bring it to the front (default: background).' },
225
+ visible: { type: 'boolean', description: 'window: true = show, false = hide.' }
224
226
  },
225
227
  required: ['op']
226
228
  }
@@ -287,7 +289,7 @@ export const MCP_TOOLS = [
287
289
  {
288
290
  name: 'browse_canvas',
289
291
  title: 'Read canvas',
290
- description: 'Read <canvas> through captured draw calls (not pixels): list canvases, read texts/regions, configure, or capture a PNG fallback. 2D canvas text comes from fillText, so no OCR needed; WebGL is opaque.',
292
+ description: 'Read <canvas> via captured draw calls (not pixels): list, read texts/regions, configure, or capture a PNG fallback. 2D text comes from fillText, so no OCR; WebGL is opaque.',
291
293
  annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true },
292
294
  inputSchema: {
293
295
  type: 'object',
@@ -352,7 +354,7 @@ export const MCP_TOOLS = [
352
354
  {
353
355
  name: 'browse_downloads',
354
356
  title: 'List downloads',
355
- description: 'List downloads for a tab with their on-disk paths. Use after clicking an export/download button — downloads are asynchronous, so poll this rather than expecting the path in the click response.',
357
+ description: 'List a tab\'s downloads with on-disk paths. Downloads are async: poll this after clicking export/download instead of expecting the path in the click response.',
356
358
  annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false },
357
359
  inputSchema: {
358
360
  type: 'object',
@@ -29,6 +29,11 @@ export function createWsClient({
29
29
  maxRetryDelay = 10000,
30
30
  ensureRunning = null, // Lazy launch hook: async; called on connection
31
31
  // failure so the server can spawn Electron on demand.
32
+ hello = null, // 连接建立后立刻发的自报家门(ui.hello 通知)。
33
+ // 为什么必须发:服务端只看得到一个 socket,分不清
34
+ // 对面是"一个 agent"还是"一段脚本"。而"要不要给你
35
+ // 自己的工作区/标签组"必须区分这两者 —— 脚本期望
36
+ // 老行为(不传 tab 就打当前页),agent 期望隔离。
32
37
  } = {}) {
33
38
  let _ws = null; // current OPEN socket (or null)
34
39
  let _connecting = null; // in-flight getWs() promise (dedupes concurrent callers)
@@ -97,6 +102,12 @@ export function createWsClient({
97
102
  if (open) {
98
103
  _ws = ws;
99
104
  attachPersistent(ws);
105
+ // 自报家门必须在**第一条 RPC 之前**发出去:TCP/WS 保序,服务端会先
106
+ // 处理它,于是第一条业务调用就已经带着身份(能拿到自己的标签组)。
107
+ if (hello) {
108
+ try { ws.send(JSON.stringify({ jsonrpc: '2.0', method: 'ui.hello', params: hello })); }
109
+ catch (_e) { /* 发不出去就退化成匿名连接,不影响调用 */ }
110
+ }
100
111
  return ws;
101
112
  }
102
113