@glittering0717/ai-browser 2.2.0 → 2.3.1

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
@@ -398,6 +398,46 @@ the write-verification will honestly report `input not verified` rather than pre
398
398
  `npm run multiagent` drives two connections against one browser and asserts all of the above,
399
399
  including 10 interleaved actions with no cross-contamination.
400
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
+
401
441
  ---
402
442
 
403
443
  This is the part most easily misunderstood, so plainly: **the agent drives the browser, and the human
@@ -742,7 +782,7 @@ not bugs. The full write-up, including why the first measurement of this was wro
742
782
  ## Test & dev
743
783
 
744
784
  ```bash
745
- npm test # vitest — 988 tests across 70 files
785
+ npm test # vitest — 1024 tests across 73 files
746
786
  npm run smoke # Electron contract layer, offline fixture — 31 checks
747
787
  npm run capabilities # text fields, canvas, page source, network, DOM editing — 54 checks
748
788
  npm run richtext # rich-text editors, nested menus, forms, errors, tags, upload — 117 checks
@@ -752,7 +792,7 @@ npm run canvas # canvas draw-call capture — 13 checks
752
792
  npm run modeldiff # canvas app data-model diff (the "unchanged" false green) — 12 checks
753
793
  npm run audit # every advertised action must exist; wait/downloads/permissions/quit — 35 checks
754
794
  npm run nav # address bar + load-failure error page (the "white screen" report) — 19 checks
755
- 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
756
796
  npm run interact # trusted drag / key press / wheel (pointer gestures) — 31 checks
757
797
  npm run view # viewport repaint budget + snapshot/diff verification — 29 checks
758
798
  npm run dialog # browser-level dialogs (native sheet blocks the renderer) — 15 checks
@@ -760,10 +800,10 @@ npm run wrapper # "in the tree but won't click" = matched a container, not
760
800
  npm run paint # blank-page self-check: verdicts, bounded ladder, no false alarms — 23 checks
761
801
  npm run layout # geometry invariants + "no twitching" (zero extra repaints on nav) — 25 checks
762
802
  npm run download # "clicked download": viewable media must display, the rest must save — 23 checks
763
- npm run multiagent # several agents at once: own tab each, no cross-talk, gone tab errors — 32 checks
803
+ npm run multiagent # several agents at once: own tab each, no cross-talk, gone tab errors — 46 checks
764
804
  npm run background # window hidden/minimized: every capability still works (headless-like) — 37 checks
765
805
  npm run flicker # frame-level: no frame may render the page shrunk (needs screen recording) — 6 checks
766
- npm run e2e:all # 一次跑完上面全部 22 个套件(每个独立端口)+ 可信汇总 — 728 checks
806
+ npm run e2e:all # 一次跑完上面全部 22 个套件(每个独立端口)+ 可信汇总 — 743 checks
767
807
  npm run verify:app # boot the packaged /Applications app and assert on it — 22 checks
768
808
  npm run realsites # navigate/read/act against a matrix of real sites
769
809
  ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@glittering0717/ai-browser",
3
- "version": "2.2.0",
3
+ "version": "2.3.1",
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": {
@@ -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) => {
@@ -9,25 +9,25 @@ description: >-
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
17
  ```
18
18
 
19
- 没这个命令就加前缀 `npx -y @glittering0717/ai-browser`;浏览器没开会自动拉起。
19
+ 没这个命令就加 `npx -y @glittering0717/ai-browser`,浏览器没开会自动拉起。
20
+ 方法名 = 工具名把 `browse_` 换成 `ui.`(tabs 等例外)。
20
21
 
21
- CLI 方法 = 工具名去掉 `browse_` 换 `ui.`(`get_tree` `act` `navigate` … 一一对应)。
22
- 不一一对应的 4 个(tabs/network/canvas/diff)见 `references/cli.md`。
22
+ ## 你的标签组
23
23
 
24
- ## 多 agent / 后台
25
- 省略 `tab` = 操作你自己的页(`list` 里 `mine`);新页默认不抢用户视野(`show:true` 才显示)。
26
- `tabs {"op":"window","visible":false}` → 后台运行,能力不变;要人登录再打开。
24
+ 第一次动手会给你一页**空白工作页**,归在你自己的标签组;多 agent 各一组,互不相干。
25
+ 省略 `tab` 就打它;用户的页不会被碰也不会被顶掉。组有上限,满了先关再开。
26
+ 看用户的页 / 人登录扫码 / 全程后台:`references/tabs.md`。
27
27
 
28
28
  ## 点东西只认 id
29
29
 
30
- `act` 的 `target` 只接受 `get_tree` 给的 id(如 `e:a-3`);传页面文字会报 `target_not_found`。
30
+ `act` 的 `target` 只认 `get_tree` 给的 id;传文字会报 `target_not_found`。
31
31
 
32
32
  ## 操作后先看 effect_state
33
33
 
@@ -46,10 +46,11 @@ CLI 方法 = 工具名去掉 `browse_` 换 `ui.`(`get_tree` `act` `navigate`
46
46
 
47
47
  ## 需要人帮忙
48
48
 
49
- 登录/扫码/滑块/支付:请用户在窗口里操作,他说"好了"再重读树确认;不要编造密码。
49
+ 登录、扫码、滑块、支付:请用户在窗口里操作,说"好了"再重读树;不要编造密码。
50
50
 
51
51
  ## 按需深挖
52
52
 
53
+ - `references/tabs.md` — 标签组、上限、把页面交给人的正确姿势
53
54
  - `references/cli.md` — CLI 全部方法与参数对照
54
55
  - `references/troubleshooting.md` — 失败排查顺序
55
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
+ 误解的连续操作(比如连续删除)。
@@ -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({
@@ -210,7 +210,7 @@ export const MCP_TOOLS = [
210
210
  {
211
211
  name: 'browse_tabs',
212
212
  title: 'Tabs',
213
- description: 'Tabs: list/new/close/switch/window. switch = your default target (then omit tab). new never steals the user\'s view unless show:true. window = hide/show; work continues while hidden.',
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 里。这是合并的唯一语义代价,接受。
@@ -289,7 +289,7 @@ export const MCP_TOOLS = [
289
289
  {
290
290
  name: 'browse_canvas',
291
291
  title: 'Read canvas',
292
- 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.',
293
293
  annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true },
294
294
  inputSchema: {
295
295
  type: 'object',
@@ -354,7 +354,7 @@ export const MCP_TOOLS = [
354
354
  {
355
355
  name: 'browse_downloads',
356
356
  title: 'List downloads',
357
- 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.',
358
358
  annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false },
359
359
  inputSchema: {
360
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
 
@@ -42,6 +42,8 @@ import { MediaInline } from './media_inline.js';
42
42
  // 默认目标标签页的判据(explicit > session > active > first)与"新标签页要不要
43
43
  // 切到人眼前"的策略。见 shared/tab_route.cjs 顶部(多 agent 并用的三条事故)。
44
44
  import tabRoute, { shouldShowChildTab } from '../shared/tab_route.cjs';
45
+ import tabGroup from '../shared/tab_group.cjs';
46
+ import placeholder from '../shared/placeholder.cjs';
45
47
  import { probeCapabilities } from './capability_probe.js';
46
48
  import valueContract from '../shared/value_contract.cjs';
47
49
  // 输入成功与否的判定口径(纯函数,独立模块便于单测)。详见文件内注释:
@@ -210,6 +212,17 @@ class PageManager {
210
212
  // 所有人的默认目标都变成它;B 说"点提交",点在 A 的页面上。判据与优先级见
211
213
  // shared/tab_route.cjs(explicit > session > active > first)。
212
214
  this._sessionTab = new Map();
215
+ // ---- 标签页归属(人的一组,每个 agent 一组)----
216
+ //
217
+ // 为什么需要它:会话级目标解决了"动作落在哪一页",但标签条上仍然是一锅粥 ——
218
+ // 人看不出哪些页是自己的、哪些是哪个 agent 的;也没有任何东西**约束** agent
219
+ // 开页面的数量,一个跑长任务的 agent 能悄悄开二十个,内存被无声吃掉。
220
+ // 归属同时承担三件事:标签栏怎么归拢、上限算谁的、人点开 agent 的页只是"看"。
221
+ this._tabGroup = new Map(); // tabId -> groupId
222
+ this._groups = new Map(); // groupId -> { id, kind, label, color, limit, createdAt }
223
+ this._tabUsedAt = new Map(); // tabId -> 最后一次被导航/动作的时间(LRU 淘汰用)
224
+ this._groupSeq = 0; // 组编号(Agent 1 / Agent 2 …)
225
+ this.evictions = []; // 被上限挤掉的标签页(最多 20 条,ui.list_tabs 回采后清空)
213
226
  this._openedTabs = new Map(); // sourceTabId -> { id, url } (new tab opened by window.open)
214
227
  this._windowOpenTokens = new Map(); // token -> { tabId, sourceTabId } (window.open shim, preload bridge.cjs)
215
228
  this._windowOpenShimTabs = new Set(); // 已注入 window.open 垫片的 tabId
@@ -502,6 +515,132 @@ class PageManager {
502
515
  * 把这个连接"自己的工作标签页"记下来。
503
516
  * 断开连接时**不关页面**:agent 进程退出后,人可能正想看看它干到哪了。
504
517
  */
518
+ // ---- 标签页归属 ----------------------------------------------------------
519
+ //
520
+ // 组 id 有两条来源:HUMAN_GROUP(人点「+」、启动页、人点链接派生出来的页)
521
+ // 和 groupIdForSession(sessionId)(一个 agent 连接一组)。
522
+ // 一个组没有标签页了就删掉 —— 否则标签栏会积一堆空的分组。
523
+
524
+ /** 建(或取)一个 agent 的组。label 是给人看的("Agent 2" / 客户端名)。 */
525
+ ensureGroup(sessionId, label, opts) {
526
+ const id = tabGroup.groupIdForSession(sessionId);
527
+ let g = this._groups.get(id);
528
+ if (!g) {
529
+ this._groupSeq += 1;
530
+ g = {
531
+ id,
532
+ kind: 'agent',
533
+ label: String(label || '').trim().slice(0, 24) || ('Agent ' + this._groupSeq),
534
+ // 颜色按组的诞生顺序取,不按 sessionId 哈希:人记的是"紫色的那个",
535
+ // 哈希出来每组都可能撞色。
536
+ color: tabGroup.colorFor(this._groupSeq - 1),
537
+ limit: tabGroup.limitFromEnv(process.env),
538
+ // capped = 这个组受限额约束。只有**声明过自己是 agent** 的连接才有
539
+ // (ui.hello);裸 WS(e2e / 脚本 / 调试)拿到组只是为了让标签页有归属,
540
+ // 不受限 —— 否则一次性开二十个标签的回归套件会突然报 group-full。
541
+ capped: false,
542
+ createdAt: Date.now(),
543
+ };
544
+ this._groups.set(id, g);
545
+ } else if (label) {
546
+ g.label = String(label).trim().slice(0, 24) || g.label;
547
+ }
548
+ if (opts && opts.capped === true) g.capped = true;
549
+ return g;
550
+ }
551
+
552
+ groupOfTab(tabId) {
553
+ return this._tabGroup.get(tabId) || tabGroup.HUMAN_GROUP;
554
+ }
555
+
556
+ groupMeta(groupId) {
557
+ const id = groupId || tabGroup.HUMAN_GROUP;
558
+ if (id === tabGroup.HUMAN_GROUP) {
559
+ return { id, kind: 'human', label: '我的标签页', color: null, limit: null };
560
+ }
561
+ return this._groups.get(id) || { id, kind: 'agent', label: id, color: null, limit: null };
562
+ }
563
+
564
+ /** 组里还有哪些页(按 tabId 升序 = 创建顺序)。 */
565
+ tabsInGroup(groupId) {
566
+ const out = [];
567
+ for (const [id] of this.tabs) {
568
+ if (this.groupOfTab(id) === groupId) {
569
+ out.push({
570
+ id,
571
+ url: this.tabs.get(id).webContents.getURL(),
572
+ usedAt: this._tabUsedAt.get(id) || 0,
573
+ dialog: this._openDialogs.has(id) ? true : undefined,
574
+ });
575
+ }
576
+ }
577
+ return out;
578
+ }
579
+
580
+ /** 这个组还能不能再开一页。 */
581
+ canOpenInGroup(groupId) {
582
+ const meta = this.groupMeta(groupId);
583
+ // 没被标记 capped 的组(裸 WS / 脚本拿到的组)不限量:组只是个归属标签。
584
+ if (meta.capped !== true) return { allowed: true, count: this.tabsInGroup(groupId).length, limit: null, remaining: null };
585
+ return tabGroup.decideOpen({
586
+ group: groupId,
587
+ count: this.tabsInGroup(groupId).length,
588
+ limit: meta.limit,
589
+ });
590
+ }
591
+
592
+ /** 组满时的牺牲品:最久没用、不在看、没有等人点的对话框。没有就返回 null。 */
593
+ pickEvictableInGroup(groupId, exceptTabId) {
594
+ const meta = this.groupMeta(groupId);
595
+ if (tabGroup.isHumanGroup(groupId)) return null;
596
+ if (meta.capped !== true) return null; // 不受限的组永远不需要牺牲谁
597
+ if (meta.limit && this.tabsInGroup(groupId).length < meta.limit) return null;
598
+ return tabGroup.pickEvictable({
599
+ tabs: this.tabsInGroup(groupId),
600
+ except: exceptTabId,
601
+ activeTab: this.activeTab,
602
+ });
603
+ }
604
+
605
+ /**
606
+ * 记录"这一页刚被用过",供 LRU 淘汰排序。
607
+ * 只在导航/动作这类**作用于页面**的地方调:读一次树不算用过,
608
+ * 否则 agent 循环读树会让真正在用的页被判定为"新",反而淘汰掉该留的。
609
+ */
610
+ touchTab(tabId) {
611
+ if (tabId === undefined || tabId === null) return;
612
+ this._tabUsedAt.set(tabId, Date.now());
613
+ }
614
+
615
+ /** 标签栏/接口用的分组清单(空组已在上面的清理里去掉,这里再滤一遍保险)。 */
616
+ listGroups() {
617
+ const out = [];
618
+ for (const [gid, meta] of this._groups) {
619
+ const tabs = this.tabsInGroup(gid);
620
+ if (!tabs.length) continue;
621
+ out.push({ ...meta, count: tabs.length });
622
+ }
623
+ out.sort((a, b) => a.createdAt - b.createdAt);
624
+ return out;
625
+ }
626
+
627
+ _forgetTab(tabId) {
628
+ const gid = this._tabGroup.get(tabId);
629
+ this._tabGroup.delete(tabId);
630
+ this._tabUsedAt.delete(tabId);
631
+ if (!gid || gid === tabGroup.HUMAN_GROUP) return;
632
+ // 组空了就删:留在 Map 里会让标签栏出现一个 0 页的分组,下次同名 agent
633
+ // 重连还会复用那个组的编号/颜色,看起来像"上一轮的残留"。
634
+ if (!this.tabsInGroup(gid).length) this._groups.delete(gid);
635
+ }
636
+
637
+ /** 把一页挪进某个组(人"接手" agent 的页 / 反向都走这条)。 */
638
+ moveToGroup(tabId, groupId) {
639
+ if (!this.tabs.has(tabId)) return false;
640
+ this._tabGroup.set(tabId, groupId || tabGroup.HUMAN_GROUP);
641
+ return true;
642
+ }
643
+
505
644
  bindSessionTab(sessionId, tabId) {
506
645
  if (!sessionId) return;
507
646
  if (tabId === undefined || tabId === null) this._sessionTab.delete(sessionId);
@@ -740,15 +879,18 @@ class PageManager {
740
879
  showDownloadResult(tabId, rec) {
741
880
  const view = this.tabs.get(tabId);
742
881
  if (!view || view.webContents.isDestroyed()) return false;
743
- const q = new URLSearchParams();
744
- q.set('id', rec.id || '');
745
- q.set('name', rec.filename || 'download');
746
- q.set('path', rec.path || '');
747
- q.set('mime', rec.mime || '');
748
- q.set('size', String(rec.total_bytes || 0));
749
- q.set('url', rec.url || '');
750
882
  const pagePath = path.join(__dirname, '../renderer/download.html');
751
- const target = 'file://' + pagePath + '?' + q.toString();
883
+ // 一律走 shared/placeholder.cjs 的构造器:手拼 'file://' + path 在打包后
884
+ // (/Applications/AI Browser.app 含空格)加载不出来。
885
+ const target = placeholder.fileUrlWithQuery(pagePath, {
886
+ id: rec.id || '',
887
+ name: rec.filename || 'download',
888
+ path: rec.path || '',
889
+ mime: rec.mime || '',
890
+ size: String(rec.total_bytes || 0),
891
+ url: rec.url || '',
892
+ });
893
+ if (!target) return false;
752
894
  view.webContents.loadURL(target).catch(() => {});
753
895
  return true;
754
896
  }
@@ -807,6 +949,7 @@ class PageManager {
807
949
  const tid = tabId !== undefined ? tabId : this.activeTab;
808
950
  const view = this._getView(tid);
809
951
  if (!view) return { ok: false, error: 'Tab not found' };
952
+ this.touchTab(tid);
810
953
  // 一旦有人在这一页上导航过,它就不再是"还没人动过的启动页"了 —— 新标签页
811
954
  // 也就不该再顶替它(否则 agent 每开一页都把上一页顶掉,等于一直抢视野)。
812
955
  this._spendStartupPrivilege();
@@ -1679,6 +1822,7 @@ class PageManager {
1679
1822
  async executeAction(action, target, params = {}, tabId) {
1680
1823
  const ms = actionDeadlineMs(action, params);
1681
1824
  const tid = tabId !== undefined ? tabId : this.activeTab;
1825
+ this.touchTab(tid);
1682
1826
  // 见 navigate 里的同一句:动过手的页面不再是"启动页"。
1683
1827
  this._spendStartupPrivilege();
1684
1828
  // 本次动作的起始时刻:用来判断"有没有对话框是在这一次动作里被应答的",
@@ -3505,6 +3649,10 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
3505
3649
  },
3506
3650
  });
3507
3651
  this.tabs.set(tabId, view);
3652
+ // 归属在最早的这一刻定下来:后面所有涉及"组"的判断(上限、标签栏、关闭
3653
+ // 后清理空组)都读这一条,晚设一步就会出现"页已经在了、但没人认领"的窗口期。
3654
+ this._tabGroup.set(tabId, opts.group || tabGroup.HUMAN_GROUP);
3655
+ this._tabUsedAt.set(tabId, Date.now());
3508
3656
  // 每个标签页、从出生起就关掉后台节流。以前只在 setActive 里设,于是"从没
3509
3657
  // 被显示过"的标签页永远带着节流:定时器被拉长到 1s、rAF 停摆,站点的轮询/
3510
3658
  // 动画/自动保存全部变慢,而 agent 看起来只是"这一页有点慢"。
@@ -3537,8 +3685,25 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
3537
3685
  // 派生标签页跟**打开它的那一个**走:可见页里弹出来的照旧弹到人眼前
3538
3686
  // (浏览器惯例),后台页里弹出来的留在后台 —— agent 流程里登录/预览/
3539
3687
  // 下载这类弹窗极多,每弹一个就抢一次视野等于人没法用电脑。
3688
+ //
3689
+ // 归属也跟打开者走:agent 的页弹出来的子页仍然属于那个 agent,否则它会
3690
+ // 悄悄跑到"人的标签页"里,下次人清理自己的标签就把 agent 的流程删了。
3691
+ const parentGroup = self.groupOfTab(tabId);
3692
+ // 弹窗把组撑满时不能拒绝(站点的脚本在等这个窗口),只能牺牲一页:
3693
+ // 最久没用、不在人眼前、没有挂着对话框的那个。
3694
+ if (!self.canOpenInGroup(parentGroup).allowed) {
3695
+ const victim = self.pickEvictableInGroup(parentGroup, tabId);
3696
+ if (victim !== null) {
3697
+ const deadUrl = (self._getView(victim) || {}).webContents
3698
+ ? self._getView(victim).webContents.getURL() : '';
3699
+ self.evictions.push({ tab: victim, url: deadUrl, at: Date.now(), reason: 'group-full' });
3700
+ if (self.evictions.length > 20) self.evictions.shift();
3701
+ self.closeTab(victim);
3702
+ }
3703
+ }
3540
3704
  const childId = self.newTab(urlToOpen, {
3541
3705
  show: shouldShowChildTab({ openerIsVisible: tabId === self.activeTab }),
3706
+ group: parentGroup,
3542
3707
  });
3543
3708
  // Track which source tab opened a new tab so `executeAction` can report the
3544
3709
  // resulting tab and auto-follow it. Generic (any target=_blank / window.open).
@@ -3600,6 +3765,8 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
3600
3765
  let signalReady = () => {};
3601
3766
  const ready = new Promise((resolve) => { signalReady = resolve; });
3602
3767
  this._windowOpenShimReady.set(tabId, ready);
3768
+ // 占位页地址:proceed 要用它判断"这一页还在不在等我"。
3769
+ const placeholderUrl = this._loadingPlaceholderUrl(targetUrl);
3603
3770
  let proceeded = false;
3604
3771
  const proceed = () => {
3605
3772
  if (proceeded) return;
@@ -3608,6 +3775,17 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
3608
3775
  // 失败也放行:宁可这个 tab 没有垫片,也不能把它卡在占位页。
3609
3776
  signalReady();
3610
3777
  if (targetUrl && wc0 && !wc0.isDestroyed()) {
3778
+ // ⚠️ 延迟到达的 proceed **绝不能覆盖已经发生的真实导航**。
3779
+ //
3780
+ // 实测(2026-10-28,npm run background 在 v2.2.0 上同样复现):
3781
+ // 垫片安装偶尔会挂十几秒,这期间 agent 已经把这一页导航走了;
3782
+ // 等它终于 resolve,下面这行 loadURL(启动页) 又把页面盖回去 ——
3783
+ // 表现是"打开的是目标页,下一刻自己跳回首页",读到的树也成了首页的。
3784
+ // 判据只看一句:现在还在占位页上吗?不在就什么都不做。
3785
+ // 注意判据在 shared/placeholder.cjs 里(按文件名,不按字符串相等)——
3786
+ // 这里踩过两次:收紧成"必须等于占位页"会让新标签页永远卡住,
3787
+ // 而字符串相等在打包路径含空格时恒为 false。
3788
+ if (!placeholder.isPlaceholderUrl(wc0.getURL())) return;
3611
3789
  // 让"正在加载"可被观测:白屏最贵的地方不是慢,是慢得无法和
3612
3790
  // "开错了"区分(见 listTabs 的 state 字段)。
3613
3791
  this._tabNavState.set(tabId, 'loading');
@@ -3636,7 +3814,7 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
3636
3814
  // loading.html 只做展示(目标地址 + 转圈),不发请求不跳转,真实导航
3637
3815
  // 仍由上面的 proceed 发起。无目标 URL 的占位 tab(window.open("") 的
3638
3816
  // 老站模式)保持 about:blank:它本来就要停在这里等 location 赋值。
3639
- wc0.loadURL(this._loadingPlaceholderUrl(targetUrl)).catch(() => {});
3817
+ wc0.loadURL(placeholderUrl).catch(() => {});
3640
3818
  wc0.once('did-finish-load', () => { clearTimeout(guard); proceed(); });
3641
3819
  }
3642
3820
 
@@ -3720,13 +3898,14 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
3720
3898
  pagePath = path.join(__dirname, '../renderer/error_page.html');
3721
3899
  } catch (_) { return; }
3722
3900
 
3723
- const q = new URLSearchParams({
3901
+ const target = placeholder.fileUrlWithQuery(pagePath, {
3724
3902
  url: String(validatedURL || ''),
3725
3903
  code: String(errorCode),
3726
3904
  text: String(errorDescription || ''),
3727
3905
  });
3728
3906
  try {
3729
- view.webContents.loadURL('file://' + pagePath + '?' + q.toString());
3907
+ if (!target) throw new Error('bad page path');
3908
+ view.webContents.loadURL(target);
3730
3909
  } catch (e) {
3731
3910
  console.error('[page_manager] error page load failed:', e.message);
3732
3911
  this._failureGuard.delete(tabId);
@@ -4353,6 +4532,7 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
4353
4532
  view.webContents.close();
4354
4533
  }
4355
4534
  this.tabs.delete(tabId);
4535
+ this._forgetTab(tabId);
4356
4536
  // window.open 垫片记账:这个 tab 若是某次 window.open 的目标,token 已
4357
4537
  // 失去意义(nav 到达也只会在上面打一行 warn),清掉防止 Map 无限增长。
4358
4538
  for (const [token, entry] of this._windowOpenTokens) {
@@ -4442,11 +4622,20 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
4442
4622
  listTabs() {
4443
4623
  const list = [];
4444
4624
  for (const [id, view] of this.tabs) {
4625
+ const gid = this.groupOfTab(id);
4626
+ const g = this.groupMeta(gid);
4445
4627
  list.push({
4446
4628
  id,
4447
4629
  url: view.webContents.getURL(),
4448
4630
  title: view.webContents.getTitle(),
4449
4631
  active: id === this.activeTab,
4632
+ // 归属:'human' = 人的页,'agent:<session>' = 某个 agent 的工作区。
4633
+ // agent 靠它判断"这一页是不是我的",人靠它在标签栏归拢。
4634
+ group: gid,
4635
+ group_label: g.label,
4636
+ ...(g.color ? { group_color: g.color } : {}),
4637
+ ...(g.capped === true && g.limit ? { group_limit: g.limit } : {}),
4638
+ ...(g.kind === 'agent' ? { group_kind: 'agent' } : {}),
4450
4639
  // 'pending' = 停在占位页等脚本注入(真实导航还没发起)
4451
4640
  // 'loading' = 真实导航已发起、还没完成 —— 这时候页面多半还是空的,
4452
4641
  // 是"正在打开"而不是"开错了",等它,不要重试
@@ -5159,14 +5348,11 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
5159
5348
  // "正在打开 <url>"),无目标地址时保持 about:blank(window.open("") 的
5160
5349
  // 占位 tab 要停在这里等站点赋 location,不能显示成"正在打开")。
5161
5350
  _loadingPlaceholderUrl(targetUrl) {
5162
- if (!targetUrl) return 'about:blank';
5163
- try {
5164
- const pagePath = path.join(__dirname, '../renderer/loading.html');
5165
- const q = new URLSearchParams({ url: String(targetUrl) });
5166
- return 'file://' + pagePath + '?' + q.toString();
5167
- } catch (_e) {
5168
- return 'about:blank';
5169
- }
5351
+ // 用 pathToFileURL 而不是 'file://' + path:打包后的路径含空格
5352
+ // (/Applications/AI Browser.app/...),手拼出来的 URL 与 Chromium 报回来的
5353
+ // 一个是字面空格、一个是 %20,任何"字符串相等"的判据都会失效。详见
5354
+ // shared/placeholder.cjs 顶部(v2.3.0 的事故)。
5355
+ return placeholder.placeholderUrlFor(path.join(__dirname, '../renderer/loading.html'), targetUrl);
5170
5356
  }
5171
5357
 
5172
5358
  _ensureWindowOpenShim(tabId, view) {