@glittering0717/ai-browser 2.1.21 → 2.2.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,69 @@ 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
+
383
401
  ---
384
402
 
385
403
  This is the part most easily misunderstood, so plainly: **the agent drives the browser, and the human
@@ -742,8 +760,10 @@ npm run wrapper # "in the tree but won't click" = matched a container, not
742
760
  npm run paint # blank-page self-check: verdicts, bounded ladder, no false alarms — 23 checks
743
761
  npm run layout # geometry invariants + "no twitching" (zero extra repaints on nav) — 25 checks
744
762
  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
764
+ npm run background # window hidden/minimized: every capability still works (headless-like) — 37 checks
745
765
  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
766
+ npm run e2e:all # 一次跑完上面全部 22 个套件(每个独立端口)+ 可信汇总 — 728 checks
747
767
  npm run verify:app # boot the packaged /Applications app and assert on it — 22 checks
748
768
  npm run realsites # navigate/read/act against a matrix of real sites
749
769
  ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@glittering0717/ai-browser",
3
- "version": "2.1.21",
3
+ "version": "2.2.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",
@@ -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`;浏览器没开会自动拉起。
21
20
 
22
21
  CLI 方法 = 工具名去掉 `browse_` 换 `ui.`(`get_tree` `act` `navigate` … 一一对应)。
23
22
  不一一对应的 4 个(tabs/network/canvas/diff)见 `references/cli.md`。
24
23
 
24
+ ## 多 agent / 后台
25
+ 省略 `tab` = 操作你自己的页(`list` 里 `mine`);新页默认不抢用户视野(`show:true` 才显示)。
26
+ `tabs {"op":"window","visible":false}` → 后台运行,能力不变;要人登录再打开。
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(如 `e:a-3`);传页面文字会报 `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,7 +46,7 @@ CLI 方法 = 工具名去掉 `browse_` 换 `ui.`(`get_tree` `act` `navigate`
45
46
 
46
47
  ## 需要人帮忙
47
48
 
48
- 登录/扫码/滑块/支付:**请用户在自己的窗口里操作**,他说"好了"再重读树确认。不要编造密码。
49
+ 登录/扫码/滑块/支付:请用户在窗口里操作,他说"好了"再重读树确认;不要编造密码。
49
50
 
50
51
  ## 按需深挖
51
52
 
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 = () => {
@@ -190,7 +190,11 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
190
190
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
191
191
  }
192
192
  if (op === 'new') {
193
- const result = await wsClient.call('ui.new_tab', { url: args.url || null });
193
+ // show 不传 = 后台新建:agent 开页面不该把人正在看的那一页顶掉。
194
+ // 这是"多 agent / 无头式运行"的默认语义,见 shared/tab_route.cjs。
195
+ const params = { url: args.url || null };
196
+ if (args.show !== undefined) params.show = args.show === true;
197
+ const result = await wsClient.call('ui.new_tab', params);
194
198
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
195
199
  }
196
200
  if (op === 'close') {
@@ -198,11 +202,18 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
198
202
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
199
203
  }
200
204
  if (op === 'switch') {
201
- const result = await wsClient.call('ui.set_active_tab', { tab: args.tab });
205
+ // 只换目标、不抢视野:agent 说"切到这个标签页"通常只是想说
206
+ // "接下来都在这页上干活",不该把人的窗口内容换掉。
207
+ const result = await wsClient.call('ui.set_active_tab', { tab: args.tab, show: false });
208
+ return { content: [{ type: 'text', text: JSON.stringify(result) }] };
209
+ }
210
+ if (op === 'window') {
211
+ const params = args.visible === undefined ? {} : { visible: args.visible === true };
212
+ const result = await wsClient.call('ui.window', params);
202
213
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
203
214
  }
204
215
  return {
205
- content: [{ type: 'text', text: `Error: unknown op "${op}" — use list / new / close / switch` }],
216
+ content: [{ type: 'text', text: `Error: unknown op "${op}" — use list / new / close / switch / window` }],
206
217
  isError: true
207
218
  };
208
219
  }
@@ -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. switch = your default target (then omit tab). new never steals the user\'s view unless show:true. window = hide/show; work continues while hidden.',
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
  }
@@ -39,6 +39,9 @@ import { DownloadMonitor } from './download_monitor.js';
39
39
  // 2026-10-27 用户报"点证书下载 → 卡在正在打开… + 一坨 png URL")。
40
40
  import mediaDoc from '../shared/media_doc.cjs';
41
41
  import { MediaInline } from './media_inline.js';
42
+ // 默认目标标签页的判据(explicit > session > active > first)与"新标签页要不要
43
+ // 切到人眼前"的策略。见 shared/tab_route.cjs 顶部(多 agent 并用的三条事故)。
44
+ import tabRoute, { shouldShowChildTab } from '../shared/tab_route.cjs';
42
45
  import { probeCapabilities } from './capability_probe.js';
43
46
  import valueContract from '../shared/value_contract.cjs';
44
47
  // 输入成功与否的判定口径(纯函数,独立模块便于单测)。详见文件内注释:
@@ -186,6 +189,10 @@ class PageManager {
186
189
  this.window = browserWindow;
187
190
  this.tabs = new Map(); // tabId -> BrowserView
188
191
  this.activeTab = null;
192
+ // 启动时那一个标签页。它存在的唯一用途是判断"人眼前这一页是不是还没人动过":
193
+ // 是的话,agent 开的第一个标签页可以直接顶上去(否则用户会盯着百度首页,
194
+ // 以为 agent 什么都没干)。见 shared/tab_route.cjs 的 shouldShowNewTab。
195
+ this.startupTab = null;
189
196
  this.tabCounter = 0;
190
197
  // 窗口首次显示时的那一刻状态(tab / body_len / ready_state)。
191
198
  // 白屏类缺陷的根因是"窗口显示了但渲染器还没画出第一帧",而这只能从窗口侧
@@ -196,6 +203,13 @@ class PageManager {
196
203
  this._pendingRequests = new Map();
197
204
  this._requestId = 0;
198
205
  this._wsClients = new Map();
206
+ // sessionId -> tabId:**这个连接自己的工作标签页**。
207
+ //
208
+ // 为什么必须有(2026-10-27 多 agent 并用):默认目标以前是全局 activeTab,
209
+ // 也就是"人眼看的那一页"。多个 agent 同时干活时它立刻崩掉 —— A 开一个标签页,
210
+ // 所有人的默认目标都变成它;B 说"点提交",点在 A 的页面上。判据与优先级见
211
+ // shared/tab_route.cjs(explicit > session > active > first)。
212
+ this._sessionTab = new Map();
199
213
  this._openedTabs = new Map(); // sourceTabId -> { id, url } (new tab opened by window.open)
200
214
  this._windowOpenTokens = new Map(); // token -> { tabId, sourceTabId } (window.open shim, preload bridge.cjs)
201
215
  this._windowOpenShimTabs = new Set(); // 已注入 window.open 垫片的 tabId
@@ -484,9 +498,40 @@ class PageManager {
484
498
  this._wsClients.set(sessionId, ws);
485
499
  }
486
500
 
501
+ /**
502
+ * 把这个连接"自己的工作标签页"记下来。
503
+ * 断开连接时**不关页面**:agent 进程退出后,人可能正想看看它干到哪了。
504
+ */
505
+ bindSessionTab(sessionId, tabId) {
506
+ if (!sessionId) return;
507
+ if (tabId === undefined || tabId === null) this._sessionTab.delete(sessionId);
508
+ else this._sessionTab.set(sessionId, tabId);
509
+ }
510
+
511
+ sessionTabOf(sessionId) {
512
+ if (!sessionId) return null;
513
+ const t = this._sessionTab.get(sessionId);
514
+ return t === undefined ? null : t;
515
+ }
516
+
517
+ /**
518
+ * 这次调用操作哪个标签页。判据只有 shared/tab_route.cjs 一处,这里只把
519
+ * "当前有哪些标签页"和"人眼看的是哪个"喂给它。
520
+ * 返回 {tab, source, error?}:error 存在时调用方必须**报错**,不许就近挑一个。
521
+ */
522
+ resolveTargetTab({ explicit, sessionId } = {}) {
523
+ return tabRoute.resolveTarget({
524
+ explicit,
525
+ session: this.sessionTabOf(sessionId),
526
+ active: this.activeTab,
527
+ tabs: Array.from(this.tabs.keys()),
528
+ });
529
+ }
530
+
487
531
  unregisterClient(sessionId) {
488
532
  this._wsClients.delete(sessionId);
489
533
  this.subscriptions.delete(sessionId);
534
+ this._sessionTab.delete(sessionId);
490
535
  }
491
536
 
492
537
  _layoutAllViews(bounds) {
@@ -762,6 +807,9 @@ class PageManager {
762
807
  const tid = tabId !== undefined ? tabId : this.activeTab;
763
808
  const view = this._getView(tid);
764
809
  if (!view) return { ok: false, error: 'Tab not found' };
810
+ // 一旦有人在这一页上导航过,它就不再是"还没人动过的启动页"了 —— 新标签页
811
+ // 也就不该再顶替它(否则 agent 每开一页都把上一页顶掉,等于一直抢视野)。
812
+ this._spendStartupPrivilege();
765
813
  const w = navWait.normalizeWaitUntil(opts.waitUntil);
766
814
  if (w.error) return { ok: false, error: w.error, wait_until_valid: navWait.LEVELS };
767
815
  const waitUntil = w.value;
@@ -1631,6 +1679,8 @@ class PageManager {
1631
1679
  async executeAction(action, target, params = {}, tabId) {
1632
1680
  const ms = actionDeadlineMs(action, params);
1633
1681
  const tid = tabId !== undefined ? tabId : this.activeTab;
1682
+ // 见 navigate 里的同一句:动过手的页面不再是"启动页"。
1683
+ this._spendStartupPrivilege();
1634
1684
  // 本次动作的起始时刻:用来判断"有没有对话框是在这一次动作里被应答的",
1635
1685
  // 并把结果写进回执(否则 agent 不知道点击中间弹过确认框)。
1636
1686
  const startedAt = Date.now();
@@ -1990,7 +2040,13 @@ class PageManager {
1990
2040
  this._openedTabs.delete(tid);
1991
2041
  const mine = pickOpenedTab(entry, startedAt);
1992
2042
  if (!mine) return null;
1993
- if (keep !== true) this.setActive(mine.id);
2043
+ // 「自动跟随」是**目标**跟过去,不是**视野**跟过去:
2044
+ // - 人在看这一页(opener 就是可见 tab)→ 照浏览器惯例把新标签切出来;
2045
+ // - opener 是后台页 → 只把调用方的目标挪过去(ws 层据回执 opened_tab 绑定),
2046
+ // 人眼前的页面一动不动。
2047
+ // 这条以前是无条件 setActive,等于"agent 点任何 target=_blank 的链接,
2048
+ // 用户的视野就被拽走一次"。
2049
+ if (keep !== true && tid === this.activeTab) this.setActive(mine.id);
1994
2050
  // 记录里的 url 是**建标签那一刻**的值。window.open("") 这条路上它永远是
1995
2051
  // 'about:blank' —— 真实地址由随后的 ai:window_open_nav 才载入。直接回
1996
2052
  // 'about:blank' 会让 agent 以为"打开了个空白页",这恰恰是当初那个 bug 的样子。
@@ -3416,7 +3472,16 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
3416
3472
 
3417
3473
  // === Tab lifecycle ===
3418
3474
 
3419
- newTab(url = null) {
3475
+ /**
3476
+ * 新建标签页。
3477
+ *
3478
+ * @param {string|null} url
3479
+ * @param {{show?: boolean}} [opts] show=false 时**不把人眼前的页面顶掉**:
3480
+ * 视图保持不挂进窗口,但几何照算、脚本照跑、截图照出(后台标签页的完整能力
3481
+ * 有 `npm run background` 钉住)。默认 true 是给"人自己点的"和内部调用用的,
3482
+ * agent 侧由 ws_server 显式传 false(见 shared/tab_route.cjs 的说明)。
3483
+ */
3484
+ newTab(url = null, opts = {}) {
3420
3485
  const tabId = ++this.tabCounter;
3421
3486
  const self = this;
3422
3487
  const view = new BrowserView({
@@ -3440,6 +3505,10 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
3440
3505
  },
3441
3506
  });
3442
3507
  this.tabs.set(tabId, view);
3508
+ // 每个标签页、从出生起就关掉后台节流。以前只在 setActive 里设,于是"从没
3509
+ // 被显示过"的标签页永远带着节流:定时器被拉长到 1s、rAF 停摆,站点的轮询/
3510
+ // 动画/自动保存全部变慢,而 agent 看起来只是"这一页有点慢"。
3511
+ try { view.webContents.setBackgroundThrottling(false); } catch (_) { /* 老版本没有这个方法 */ }
3443
3512
 
3444
3513
  // Tabs created after a subscribe should inherit the CDP domains already
3445
3514
  // active, so network_response / js_error keep flowing without re-subscribing.
@@ -3465,15 +3534,39 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
3465
3534
 
3466
3535
  // Intercept window.open / new-window → create new tab instead
3467
3536
  view.webContents.setWindowOpenHandler(({ url: urlToOpen }) => {
3468
- const childId = self.newTab(urlToOpen);
3537
+ // 派生标签页跟**打开它的那一个**走:可见页里弹出来的照旧弹到人眼前
3538
+ // (浏览器惯例),后台页里弹出来的留在后台 —— agent 流程里登录/预览/
3539
+ // 下载这类弹窗极多,每弹一个就抢一次视野等于人没法用电脑。
3540
+ const childId = self.newTab(urlToOpen, {
3541
+ show: shouldShowChildTab({ openerIsVisible: tabId === self.activeTab }),
3542
+ });
3469
3543
  // Track which source tab opened a new tab so `executeAction` can report the
3470
3544
  // resulting tab and auto-follow it. Generic (any target=_blank / window.open).
3471
3545
  self._openedTabs.set(tabId, { id: childId, at: Date.now(), url: urlToOpen });
3472
3546
  return { action: 'deny' };
3473
3547
  });
3474
3548
 
3475
- // setActive handles addBrowserView + layout — don't add twice
3476
- this.setActive(tabId);
3549
+ // 可见与否由调用方决定,但**所有**标签页都挂进窗口、用 z 序决定谁在上面。
3550
+ //
3551
+ // 为什么不"不显示就不挂"(2026-10-28 实测):没挂进窗口的 BrowserView 根本
3552
+ // 没有合成表面 —— 读树/点击/输入/导航全都正常(那走的是渲染进程和 CDP 输入),
3553
+ // 但 ui.screenshot 拿到 0 字节、ui.paint_check 直接 no-frame。也就是说
3554
+ // "后台标签页"会变成一个**看不见也拍不到**的黑盒,而 agent 恰恰靠截图判断
3555
+ // "这一页到底画出什么了"。
3556
+ // 挂上去、把可见的那个置顶,就同时得到:真实表面(可截图/可自检)+ 人只看到
3557
+ // 他该看的那一页。
3558
+ const show = opts.show !== false;
3559
+ this._attachView(view);
3560
+ if (show || this.activeTab === null) {
3561
+ this.setActive(tabId);
3562
+ } else {
3563
+ this._layoutView(view);
3564
+ try { view.webContents.setBackgroundThrottling(false); } catch (_) { /* 老版本 */ }
3565
+ // 新挂的视图默认在最上层 —— 马上把"人该看的那一页"顶回去,否则后台新建
3566
+ // 的标签页会盖住用户正在看的页面(那就是"抢视野"的另一种形态)。
3567
+ const vis = this._getView(this.activeTab);
3568
+ if (vis) this._raiseView(vis);
3569
+ }
3477
3570
 
3478
3571
  // canvas 绘制记录必须在**首个真实导航之前**装好,否则页面早画完了什么都录不到。
3479
3572
  // 但它又必须在 setActive 之后:BrowserView 还没被加进窗口时,debugger 通道
@@ -4055,6 +4148,11 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
4055
4148
  _schedulePaintAudit(tabId, delay = 450) {
4056
4149
  if (!this._paintAuditEnabled) return;
4057
4150
  if (tabId !== this.activeTab) return;
4151
+ // 窗口不可见(隐藏/最小化/后台运行)时**不做**判定:这时"屏幕上有没有画出来"
4152
+ // 没有观测意义,取帧拿到的要不是空的、要不是陈旧的,而阶梯会据此 reload ——
4153
+ // 那是自己制造的一场重载风暴(后台 agent 每加载一页就刷一次)。
4154
+ // 人把窗口点开时由 ui.window{visible:true} 走 afterShowRelayout + 一次自检。
4155
+ if (!this._windowVisible()) return;
4058
4156
  const prev = this._paintTimers.get(tabId);
4059
4157
  if (prev) clearTimeout(prev);
4060
4158
  const t = setTimeout(() => {
@@ -4366,18 +4464,54 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
4366
4464
  return list;
4367
4465
  }
4368
4466
 
4467
+ /**
4468
+ * 把视图挂进窗口(幂等)。所有标签页都挂着,靠 z 序决定谁可见 ——
4469
+ * 原因见 newTab 里的注释(没挂 = 没表面 = 截不到图)。
4470
+ */
4471
+ _attachView(view) {
4472
+ if (!view || !this.window) return;
4473
+ try {
4474
+ const attached = this.window.getBrowserViews ? this.window.getBrowserViews() : [];
4475
+ if (attached.indexOf(view) < 0) this.window.addBrowserView(view);
4476
+ } catch (_) { /* 窗口正在销毁 */ }
4477
+ }
4478
+
4479
+ /** 把某个视图提到最上层(= 人看到它)。老版本没有 setTopBrowserView 时退回 remove+add。 */
4480
+ _raiseView(view) {
4481
+ if (!view || !this.window) return;
4482
+ try {
4483
+ if (typeof this.window.setTopBrowserView === 'function') {
4484
+ this.window.setTopBrowserView(view);
4485
+ return;
4486
+ }
4487
+ } catch (_) { /* 落到下面的兼容路径 */ }
4488
+ try {
4489
+ this.window.removeBrowserView(view);
4490
+ this.window.addBrowserView(view);
4491
+ } catch (_) { /* 已销毁 */ }
4492
+ }
4493
+
4494
+ /** 「人眼前还是启动页」这个判断只对**没被动过**的启动页成立(见 shouldShowNewTab)。 */
4495
+ _spendStartupPrivilege() {
4496
+ this.startupTab = null;
4497
+ }
4498
+
4369
4499
  setActive(tabId) {
4370
4500
  if (!this.tabs.has(tabId)) return false;
4371
- // Remove all browser views from window, then re-add only the active one
4372
- for (const [id, view] of this.tabs) {
4373
- try { this.window.removeBrowserView(view); } catch(e) {}
4374
- }
4501
+ // 「人眼前还是启动页」这个特权是一次性的:一旦有人(人点了标签页、或 agent 显式
4502
+ // 把某一页顶到眼前)真正选过一次,之后新开的标签页就不再顶替它了 ——
4503
+ // 否则 agent 每开一页都会把上一页顶掉,等于永远在抢视野。
4504
+ if (this.startupTab !== null && tabId !== this.startupTab) this.startupTab = null;
4375
4505
  this.activeTab = tabId;
4376
4506
  // body / 记录淘汰要"先牺牲后台 tab",所以必须让它知道谁是活跃的。
4377
4507
  this.networkMonitor.setActiveTab(tabId);
4378
4508
  const view = this._getView(tabId);
4379
4509
  if (view) {
4380
- this.window.addBrowserView(view);
4510
+ // 只调 z 序:以前是"把所有视图 remove 掉、再 add 一个",那等于每次切标签页
4511
+ // 都让其余标签页失去合成表面(截图/自检全失效),而且 remove+add 本身会
4512
+ // 闪一帧白。
4513
+ this._attachView(view);
4514
+ this._raiseView(view);
4381
4515
  this._layoutView(view);
4382
4516
  this._focusWebContents(view);
4383
4517
  view.webContents.setBackgroundThrottling(false);
@@ -4437,6 +4571,116 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
4437
4571
  *
4438
4572
  * 不传尺寸时纯读;传了就 setBounds + 立刻重排,再回读实际结果(不做乐观报告)。
4439
4573
  */
4574
+ /**
4575
+ * 窗口可见性 / 最小化(读 + 改)。`ui.window`。
4576
+ *
4577
+ * 为什么必须有(2026-10-28,用户要求"跟无头浏览器一样无感知运行"):
4578
+ * 在这之前没有任何一条路能让 agent 自己决定窗口显示与否 —— 窗口一旦被隐藏,
4579
+ * 下一次操作触发的 _focusWindow 又把它拽回来,于是"后台运行"根本不是一个
4580
+ * 稳定状态。现在可见性成为显式状态:
4581
+ * - 人:Dock 图标(app 'activate')/ 手动最小化,随时能点开;
4582
+ * - agent:ui.window {visible|minimized},AI_BROWSER_START_HIDDEN=1 启动即隐藏。
4583
+ *
4584
+ * 三条实现约束:
4585
+ * 1. **隐藏不影响任何页面能力**。视图仍挂在这个窗口上、几何照算,读树/动作/
4586
+ * 截图/上传/下载/对话框全部照旧(`npm run background` 里 20 条断言钉住)。
4587
+ * 2. **隐藏不抢焦点**。show 默认走 showInactive(),只有调用方显式 focus:true
4588
+ * 才把窗口带到前台 —— 这是"人主动要打开它"和"agent 偷偷弹窗"的区别。
4589
+ * 3. **恢复显示后要重排**。macOS/Windows 显示瞬间 content 尺寸与隐藏时不同,
4590
+ * 不重排就会出现"视图底部溢出"(Windows 上实测 26px,见 showInitialWindow)。
4591
+ */
4592
+ /** 窗口此刻是不是"人真的能看见"。判断绘制类问题时它是前置条件(见 _schedulePaintAudit)。 */
4593
+ _windowVisible() {
4594
+ try {
4595
+ if (!this.window) return false;
4596
+ if (this.window.isMinimized && this.window.isMinimized()) return false;
4597
+ if (this.window.isVisible && !this.window.isVisible()) return false;
4598
+ return true;
4599
+ } catch (_) {
4600
+ return false;
4601
+ }
4602
+ }
4603
+
4604
+ windowState() {
4605
+ const out = { ok: true };
4606
+ try {
4607
+ out.visible = !!(this.window.isVisible && this.window.isVisible());
4608
+ out.minimized = !!(this.window.isMinimized && this.window.isMinimized());
4609
+ out.focused = !!(this.window.isFocused && this.window.isFocused());
4610
+ out.bounds = this.window.getBounds();
4611
+ } catch (_) {
4612
+ return { ok: false, error: 'no-window' };
4613
+ }
4614
+ out.tabs = this.tabs.size;
4615
+ out.active_tab = this.activeTab;
4616
+ out.headless_ready = true; // 后台能力已可用;留给调用方判断的显式承诺
4617
+ return out;
4618
+ }
4619
+
4620
+ setWindowVisible(visible, opts = {}) {
4621
+ if (!this.window) return { ok: false, error: 'no-window' };
4622
+ try {
4623
+ if (visible) {
4624
+ if (this.window.isMinimized && this.window.isMinimized()) {
4625
+ try { this.window.restore(); } catch (_) { /* 已销毁 */ }
4626
+ }
4627
+ if (opts.focus === true && this.window.show) this.window.show();
4628
+ else if (typeof this.window.showInactive === 'function') this.window.showInactive();
4629
+ else if (this.window.show) this.window.show();
4630
+ this.afterShowRelayout();
4631
+ // 人刚刚把窗口点开:立刻自检一次"这一页到底画出来没有"。
4632
+ // 后台期间故意不判(见 _schedulePaintAudit),所以这里是唯一能兜住
4633
+ // "agent 在后台把页面搞白了、人一打开正好看到白屏"的时刻。
4634
+ this._schedulePaintAudit(this.activeTab, 700);
4635
+ } else {
4636
+ if (this.window.hide) this.window.hide();
4637
+ }
4638
+ } catch (e) {
4639
+ return { ok: false, error: String(e && e.message || e), ...this.windowState() };
4640
+ }
4641
+ return this.windowState();
4642
+ }
4643
+
4644
+ async setWindowMinimized(min) {
4645
+ if (!this.window) return { ok: false, error: 'no-window' };
4646
+ try {
4647
+ if (min) {
4648
+ if (this.window.minimize) this.window.minimize();
4649
+ } else {
4650
+ if (this.window.restore) this.window.restore();
4651
+ this.afterShowRelayout();
4652
+ }
4653
+ } catch (e) {
4654
+ return { ok: false, error: String(e && e.message || e), ...this.windowState() };
4655
+ }
4656
+ // macOS 的 miniaturize 是带动画的:isMinimized() 在动画结束前仍返回 false,
4657
+ // 当场回读会告诉调用方"没最小化"(实测踩到)。等动画走完再报,回执才是真的。
4658
+ await new Promise((r) => setTimeout(r, 280));
4659
+ return this.windowState();
4660
+ }
4661
+
4662
+ /**
4663
+ * 显示之后补几次重排。Windows 上 show() 之后原生边框才生效,content 高度会变
4664
+ * 而外框不变 → 不触发 resize → 视图按显示前的尺寸布局,底部溢出(实测 26px)。
4665
+ * 与 index.js 的 showInitialWindow 同一套理由,三次是为了覆盖边框真正应用的时刻。
4666
+ */
4667
+ afterShowRelayout() {
4668
+ const relayout = () => {
4669
+ try {
4670
+ for (const [id, v] of this.tabs) {
4671
+ if (id === this.activeTab) this._layoutView(v);
4672
+ }
4673
+ const v = this._getView(this.activeTab);
4674
+ if (v && v.webContents && !v.webContents.isDestroyed()) v.webContents.invalidate();
4675
+ } catch (_) { /* 窗口/视图已销毁 */ }
4676
+ };
4677
+ relayout();
4678
+ const t1 = setTimeout(relayout, 150);
4679
+ const t2 = setTimeout(relayout, 450);
4680
+ if (t1.unref) t1.unref();
4681
+ if (t2.unref) t2.unref();
4682
+ }
4683
+
4440
4684
  windowBounds(next) {
4441
4685
  const snapshot = () => {
4442
4686
  const out = { ok: true };
@@ -4660,37 +4904,29 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
4660
4904
  * 拽到最前,等于人完全没法用电脑。
4661
4905
  *
4662
4906
  * AI_BROWSER_FOCUS:
4663
- * auto (默认) 只在窗口被最小化/隐藏时恢复可见,**不** moveTop、**不** focus。
4664
- * CDP 受信输入(Input.dispatchKeyEvent / dispatchMouseEvent)在窗口
4665
- * 非前台时依然生效,加上已有的 disable-backgrounding-occluded-windows /
4666
- * disable-renderer-backgrounding / disable-background-timer-throttling,
4667
- * 后台窗口不会被降频或丢事件。
4907
+ * auto (默认) **完全不碰窗口状态**:不 show、不 moveTop、不 focus。
4908
+ * CDP 受信输入(Input.dispatchKeyEvent / dispatchMouseEvent)在窗口
4909
+ * 非前台、最小化、甚至隐藏时依然生效(加上已有的
4910
+ * disable-backgrounding-occluded-windows / disable-renderer-backgrounding /
4911
+ * disable-background-timer-throttling,后台窗口不会被降频或丢事件)。
4912
+ * 这是"无头式运行"的前提:窗口隐藏必须是**稳定状态**,而不是
4913
+ * "下一次操作就弹回来"。
4668
4914
  * always 旧行为:每次都 show + moveTop + focus(需要抢焦点时用)。
4669
- * never 完全不碰窗口状态。
4915
+ * never 与 auto 相同(保留这个名字是为了兼容老配置)。
4916
+ *
4917
+ * ⚠️ 2026-10-28 之前 auto 会"窗口被最小化/隐藏就 restore + showInactive",
4918
+ * 依据是当时的产品不变量"窗口必须真实可见"。多 agent 并用之后这条不变量反过来
4919
+ * 咬人:agent 每操作一次,隐藏的窗口就自己爬出来一次 —— 人在用电脑,窗口在
4920
+ * 后台不停弹。现在改成:**窗口可见性只由人(Dock/activate)和显式 ui.window 决定**。
4670
4921
  */
4671
4922
  _focusWindow(view) {
4672
4923
  const policy = String(process.env.AI_BROWSER_FOCUS || 'auto').toLowerCase();
4673
- if (policy === 'never') return;
4924
+ if (policy !== 'always') return;
4674
4925
  try {
4675
- if (policy === 'always') {
4676
- if (this.window.show) this.window.show();
4677
- if (this.window.moveTop) this.window.moveTop();
4678
- if (this.window.focus) this.window.focus();
4679
- if (view && view.webContents && view.webContents.focus) view.webContents.focus();
4680
- return;
4681
- }
4682
- // auto:产品承诺"窗口真实可见、人可随时介入",所以被最小化/隐藏时要恢复可见;
4683
- // 但不主动抢到最前 —— 人可以继续用别的窗口,需要时自己点过来。
4684
- // 用 showInactive(),语义才前后一致:auto 分支**从不**夺走键盘焦点。
4685
- const hidden = (this.window.isVisible && !this.window.isVisible()) ||
4686
- (this.window.isMinimized && this.window.isMinimized());
4687
- if (hidden) {
4688
- if (this.window.isMinimized && this.window.isMinimized() && this.window.restore) {
4689
- try { this.window.restore(); } catch (e) { /* 已销毁 */ }
4690
- }
4691
- if (typeof this.window.showInactive === 'function') this.window.showInactive();
4692
- else if (this.window.show) this.window.show();
4693
- }
4926
+ if (this.window.show) this.window.show();
4927
+ if (this.window.moveTop) this.window.moveTop();
4928
+ if (this.window.focus) this.window.focus();
4929
+ if (view && view.webContents && view.webContents.focus) view.webContents.focus();
4694
4930
  } catch (e) { /* 窗口已销毁等情况,忽略 */ }
4695
4931
  }
4696
4932
 
@@ -11,6 +11,9 @@ import findRefUtil from '../shared/find_ref.cjs';
11
11
  // 错误日志:RPC 层异常必须落盘(此前只回一句 JSON-RPC error,现场永久丢失),
12
12
  // 每次调用的摘要进环形缓冲,作为崩溃时的上下文。
13
13
  import { recordError, noteCall, recentErrors } from './error_log.js';
14
+ // 默认目标标签页的判据(explicit > session > active > first),理由与两条不可
15
+ // 退让的约束见 shared/tab_route.cjs 顶部(多 agent 并用时"目标被别人改掉")。
16
+ import tabRoute from '../shared/tab_route.cjs';
14
17
 
15
18
  // Each startWSServer() owns a private WebSocketServer. Keeping it local (not a
16
19
  // module global) means multiple servers can coexist — required by tests that
@@ -45,6 +48,15 @@ function findWaitTarget(tree, target) {
45
48
  // 不够稳;pid + started_at 两个一起才足以判定"是不是同一个进程"。
46
49
  const serverStartedAt = Math.floor(Date.now() / 1000);
47
50
 
51
+ // 这些方法**不碰页面**,所以"你的标签页没了"不该拦它们 —— 否则 agent 在标签页
52
+ // 被别人关掉之后,连 ui.new_tab / ui.list_tabs 这种自救动作都会被错误挡回去,
53
+ // 等于把人锁在门外。
54
+ const TABLESS_METHODS = new Set([
55
+ 'ui.new_tab', 'ui.list_tabs', 'ui.close_tab', 'ui.server_info', 'ui.errors',
56
+ 'ui.window', 'ui.window_bounds', 'ui.window_shown', 'ui.quit',
57
+ 'ui.subscribe', 'ui.unsubscribe',
58
+ ]);
59
+
48
60
  export function startWSServer(pageManager, port = config.wsPort, onQuit = null) {
49
61
  // Bind loopback only — the protocol carries no auth. ws' default (host
50
62
  // omitted) is 0.0.0.0, which would expose the browser — including all its
@@ -94,13 +106,55 @@ export function startWSServer(pageManager, port = config.wsPort, onQuit = null)
94
106
  }
95
107
 
96
108
  const { id, method, params = {} } = msg;
97
- const tabId = params.tab; // optional tab routing
109
+ // 这次调用操作哪个标签页:调用方点名 > 本连接自己的标签页 > 人眼看的那一个。
110
+ //
111
+ // 以前这里是 `const tabId = params.tab`,缺省就落到全局 activeTab —— 单 agent
112
+ // 时看不出问题,多个 agent 同时用时就是灾难:A 开一个标签页,所有人的默认
113
+ // 目标都变成它;人切一下标签页,把所有 agent 的目标一起切走。判据集中在
114
+ // shared/tab_route.cjs,这里只负责把会话维度接上去。
115
+ //
116
+ // 全程 try/catch + 能力探测:单测用的是 Mock PageManager(没有 tabs /
117
+ // sessionTabOf),路由不该因此把每个方法都打成 500。
118
+ let routed;
119
+ try {
120
+ if (typeof pageManager.resolveTargetTab === 'function') {
121
+ routed = pageManager.resolveTargetTab({ explicit: params.tab, sessionId });
122
+ } else {
123
+ const known = (pageManager.tabs && typeof pageManager.tabs.keys === 'function')
124
+ ? Array.from(pageManager.tabs.keys()) : [];
125
+ routed = tabRoute.resolveTarget({
126
+ explicit: params.tab,
127
+ session: typeof pageManager.sessionTabOf === 'function' ? pageManager.sessionTabOf(sessionId) : null,
128
+ active: pageManager.activeTab,
129
+ tabs: known,
130
+ });
131
+ // 拿不到标签页清单(单测 mock)→ 不参与路由,按调用方给的来
132
+ if (!known.length && (params.tab === undefined || params.tab === null)) {
133
+ routed = { tab: null, source: 'unknown' };
134
+ }
135
+ }
136
+ } catch (_) {
137
+ routed = { tab: params.tab === undefined ? null : params.tab, source: 'unknown' };
138
+ }
139
+ const tabId = routed.tab;
98
140
  const send = (payload) => {
99
141
  if (ws.readyState === 1) ws.send(JSON.stringify(payload));
100
142
  };
143
+ // 会话标签页没了 → 必须在这一层拦住(否则会退回到别人的页面继续执行)。
144
+ //
145
+ // 但"点名了一个不存在的 tab"**不**在这里报:那是方法自己的校验,而且各方法
146
+ // 的词汇更准(ui.repaint 报 no-such-tab、ui.diff 报 tab-mismatch,
147
+ // 后者是语义检查而不是"找不到")。在这里统一改写成 RPC error 会把
148
+ // "跨 tab 比对被拒绝"这类可诊断的结论一并抹平。
149
+ const routingError = () => {
150
+ if (!routed.error || routed.source === 'gone') return false;
151
+ send({ jsonrpc: '2.0', id, error: { code: -32001, message: routed.error, data: { source: routed.source } } });
152
+ return true;
153
+ };
101
154
 
102
155
  const t0 = Date.now();
103
156
  try {
157
+ if (!TABLESS_METHODS.has(method) && routingError()) return;
104
158
  switch (method) {
105
159
  case 'ui.get_tree': {
106
160
  // P0 probe: params.ax routes to the AX read layer (getFullAXTree);
@@ -139,6 +193,12 @@ export function startWSServer(pageManager, port = config.wsPort, onQuit = null)
139
193
  if (hoisted.hoisted.length && result && typeof result === 'object' && !result.params_hoisted) {
140
194
  result.params_hoisted = hoisted.hoisted;
141
195
  }
196
+ // 这次点击开出了新标签页(target=_blank / window.open)→ 把这个连接的
197
+ // 工作目标挪过去。注意只是**目标**:人眼前的页面由 page_manager 决定
198
+ // (opener 可见时才会真的切过去),后台任务不会被这个跟随顶到前台。
199
+ if (result && result.opened_tab && result.opened_tab.id) {
200
+ pageManager.bindSessionTab(sessionId, result.opened_tab.id);
201
+ }
142
202
  send({ jsonrpc: '2.0', id, result });
143
203
  } catch (e) {
144
204
  if (e && e.__deadline) {
@@ -274,17 +334,45 @@ export function startWSServer(pageManager, port = config.wsPort, onQuit = null)
274
334
  }
275
335
  // === Tab management ===
276
336
  case 'ui.new_tab': {
277
- const newTabId = pageManager.newTab(params.url || null);
278
- send({ jsonrpc: '2.0', id, result: { tab: newTabId } });
337
+ // show 缺省 = **不显示**:人正在看的那一页是人的东西,agent 开一个新
338
+ // 页面不该把它顶掉(多 agent 时更是如此:谁也说不清该顶掉谁)。
339
+ // 例外见 shared/tab_route.cjs 的 shouldShowNewTab:显式 show:true、
340
+ // 或者当前根本没有可见标签页(否则人打开窗口看到一片空白)。
341
+ const show = tabRoute.shouldShowNewTab({
342
+ requested: params.show === undefined ? undefined : params.show === true,
343
+ hasVisible: !!pageManager.activeTab,
344
+ // 人眼前还是启动页 = 还没有"人的页面"可保护,agent 的第一页直接顶上去
345
+ visibleIsStartup: pageManager.activeTab !== null &&
346
+ pageManager.activeTab === pageManager.startupTab,
347
+ });
348
+ const newTabId = pageManager.newTab(params.url || null, { show });
349
+ // 新标签页立刻成为**这个连接的**工作目标(不影响别的连接、也不影响人)。
350
+ if (typeof pageManager.bindSessionTab === 'function') pageManager.bindSessionTab(sessionId, newTabId);
351
+ send({ jsonrpc: '2.0', id, result: { tab: newTabId, shown: show } });
279
352
  break;
280
353
  }
281
354
  case 'ui.close_tab': {
282
- const ok = pageManager.closeTab(params.tab);
283
- send({ jsonrpc: '2.0', id, result: { ok } });
355
+ const target = params.tab !== undefined && params.tab !== null ? params.tab : tabId;
356
+ const ok = pageManager.closeTab(target);
357
+ // **只有自己关掉自己那个页**才解绑:那是一次明确的"我不用它了",
358
+ // 之后的调用照浏览器惯例落到当前可见页。
359
+ // 别人的页被关掉时绑定要留着 —— 下一次调用必须明确报"你的页没了",
360
+ // 否则 agent 会在**另一个 agent 的页面**上继续执行,回执还是 success。
361
+ if (ok && typeof pageManager.sessionTabOf === 'function' &&
362
+ pageManager.sessionTabOf(sessionId) === target) {
363
+ pageManager.bindSessionTab(sessionId, null);
364
+ }
365
+ send({ jsonrpc: '2.0', id, result: { ok, tab: target } });
284
366
  break;
285
367
  }
286
368
  case 'ui.list_tabs': {
287
369
  const tabs = pageManager.listTabs();
370
+ // mine:只在自己那一条上出现(不加的人拿不到这个字段,省 token)。
371
+ // 多 agent 时"我在哪个标签页上"必须能问出来,否则 agent 只能靠猜。
372
+ const mine = typeof pageManager.sessionTabOf === 'function' ? pageManager.sessionTabOf(sessionId) : null;
373
+ if (mine !== null && mine !== undefined) {
374
+ for (const t of tabs) if (t.id === mine) t.mine = true;
375
+ }
288
376
  send({ jsonrpc: '2.0', id, result: { tabs } });
289
377
  break;
290
378
  }
@@ -298,8 +386,49 @@ export function startWSServer(pageManager, port = config.wsPort, onQuit = null)
298
386
  break;
299
387
  }
300
388
  case 'ui.set_active_tab': {
301
- const ok = pageManager.setActive(params.tab);
302
- send({ jsonrpc: '2.0', id, result: { ok } });
389
+ // 语义:把这个会话的工作目标换成 params.tab,并(默认)把它显示出来。
390
+ // show:false = "我只想换目标,别动人眼前的页面"。
391
+ //
392
+ // tab 不存在时回 `{ok:false, error:'no-such-tab'}`(**不是** JSON-RPC error):
393
+ // 这是"这一次切换没成功",不是"这次调用本身不合法",调用方要能用同一个
394
+ // 回执通道区分它和"路由崩了"。契约由 test_ws_handlers 的 TAB-2 钉住。
395
+ const target = params.tab;
396
+ const exists = target !== undefined && target !== null &&
397
+ pageManager.tabs && typeof pageManager.tabs.has === 'function' && pageManager.tabs.has(target);
398
+ // 回执形状是 2026-10-19 那次事故的回归点(agent 曾收到 `{}`):
399
+ // 成功就回 `{ok:true}`,多余字段一个都不加 —— 只有调用方显式要
400
+ // `show:false`(新语义)时才多一个 `shown`。
401
+ if (!exists && pageManager.tabs && typeof pageManager.tabs.has === 'function') {
402
+ send({ jsonrpc: '2.0', id, result: { ok: false, error: 'no-such-tab', tab: target } });
403
+ break;
404
+ }
405
+ if (!exists) {
406
+ // 没有 tabs 能力的调用方(单测 mock):按老契约让 setActive 自己回
407
+ const okMock = typeof pageManager.setActive === 'function' ? pageManager.setActive(target) : false;
408
+ send({ jsonrpc: '2.0', id, result: okMock
409
+ ? (params.show === false ? { ok: true, shown: false } : { ok: true })
410
+ : { ok: false, error: 'no-such-tab' } });
411
+ break;
412
+ }
413
+ if (typeof pageManager.bindSessionTab === 'function') pageManager.bindSessionTab(sessionId, target);
414
+ const ok = params.show === false ? true : pageManager.setActive(target);
415
+ send({ jsonrpc: '2.0', id, result: ok
416
+ ? (params.show === false ? { ok: true, shown: false } : { ok: true })
417
+ : { ok: false, error: 'no-such-tab', tab: target } });
418
+ break;
419
+ }
420
+ // 窗口可见性 / 最小化。后台运行(无头式无人值守)的唯一开关,
421
+ // 详见 page_manager.windowState 的注释。
422
+ case 'ui.window': {
423
+ if (typeof pageManager.windowState !== 'function') {
424
+ send({ jsonrpc: '2.0', id, result: { ok: false, error: 'window control not available (no Electron window)' } });
425
+ break;
426
+ }
427
+ let r;
428
+ if (params.visible !== undefined) r = pageManager.setWindowVisible(params.visible === true, { focus: params.focus === true });
429
+ else if (params.minimized !== undefined) r = await pageManager.setWindowMinimized(params.minimized === true);
430
+ else r = pageManager.windowState();
431
+ send({ jsonrpc: '2.0', id, result: r });
303
432
  break;
304
433
  }
305
434
  // 服务端的进程身份。存在的理由(2026-10-15 实测):调用方**无法确认
@@ -320,6 +449,11 @@ export function startWSServer(pageManager, port = config.wsPort, onQuit = null)
320
449
  // 渲染路径:{gpu:true|false, reason:'default'|'env'|'fallback'}。
321
450
  // 白屏/缩放类缺陷的复现与"这条路有没有关系"都要靠它。
322
451
  ...(pageManager.renderPath ? { render_path: pageManager.renderPath } : {}),
452
+ // 窗口状态:后台运行时要能问到"现在到底是不是隐藏的",否则
453
+ // "我没看到窗口却以为它在显示"这类问题只能靠猜。
454
+ ...(pageManager.windowState ? { window: pageManager.windowState() } : {}),
455
+ // 这个连接的工作标签页(多 agent 时用来核对自己绑到了哪一页)
456
+ ...(pageManager.sessionTabOf ? { session_tab: pageManager.sessionTabOf(sessionId) } : {}),
323
457
  },
324
458
  });
325
459
  break;
@@ -71,6 +71,9 @@ export const VALID_METHODS = [
71
71
  'ui.paint_check',
72
72
  // 窗口/视图几何(读 + 改)。布局类缺陷需要它才能复现与回归。
73
73
  'ui.window_bounds',
74
+ // 窗口可见性 / 最小化(读 + 改)。后台运行(无头式无人值守)的开关:
75
+ // 隐藏是一个**稳定状态**,不会因为 agent 的下一次操作自己弹回来。
76
+ 'ui.window',
74
77
  'ui.snapshot',
75
78
  'ui.diff',
76
79
  'ui.capabilities',
@@ -0,0 +1,99 @@
1
+ // shared/tab_route.cjs — 「这次调用到底操作哪个标签页」的唯一判据
2
+ //
3
+ // # 为什么需要它(2026-10-27,多 agent 并用)
4
+ //
5
+ // 以前默认目标是**全局** `activeTab` —— 也就是"人眼看的那一个"。单 agent 时它
6
+ // 恰好等于"agent 正在干的活",所以看不出问题。多个 agent 同时用的时候它立刻
7
+ // 崩掉:
8
+ // - A 开一个标签页 → 所有人的默认目标都变成它;
9
+ // - B 只说了"点一下提交",结果点在 A 的页面上;
10
+ // - 人切到别的标签页看热闹 → 把所有 agent 的目标一起切走。
11
+ // 这三件事的共同点:**动作落在哪个页面,取决于别人做了什么**。这是最难查的
12
+ // 一类 bug(回执 success、页面确实变了,但不是该变的那个)。
13
+ //
14
+ // 所以默认目标的优先级写在这一处,且只有这一处:
15
+ //
16
+ // explicit(调用方点名) > session(这个连接自己的标签页) > active(人眼看的) > 第一个
17
+ //
18
+ // 两条不可退让的约束:
19
+ // 1. **点名不存在的 tab 必须报错**,绝不"就近挑一个"。静默改目标 = 在错的页面上
20
+ // 执行成功 = 比失败更糟。
21
+ // 2. **会话标签页被关掉也要报错**(而不是退回 active)。owner 自己关的会清掉绑定,
22
+ // 所以走到这条分支意味着"别人动了你的页面" —— 调用方需要知道,而不是继续
23
+ // 在另一个页面上操作。
24
+
25
+ /**
26
+ * @param {object} o
27
+ * @param {number|null|undefined} o.explicit 调用方显式传的 tab
28
+ * @param {number|null|undefined} o.session 这个连接绑定的标签页
29
+ * @param {number|null|undefined} o.active 人眼看的那一个
30
+ * @param {number[]} o.tabs 当前存在的标签页
31
+ * @returns {{tab:number|null, source:string, error?:string}}
32
+ * source: explicit | session | active | first | none | gone | session-gone
33
+ */
34
+ function resolveTarget(o) {
35
+ const opts = o || {};
36
+ const known = Array.isArray(opts.tabs) ? opts.tabs : [];
37
+ const has = (id) => id !== undefined && id !== null && known.indexOf(id) >= 0;
38
+ const explicit = opts.explicit;
39
+ const session = opts.session;
40
+ const active = opts.active;
41
+
42
+ if (explicit !== undefined && explicit !== null) {
43
+ if (!has(explicit)) {
44
+ return {
45
+ tab: explicit,
46
+ source: 'gone',
47
+ error: 'tab ' + explicit + ' does not exist (open one with ui.new_tab, or check ui.list_tabs)',
48
+ };
49
+ }
50
+ return { tab: explicit, source: 'explicit' };
51
+ }
52
+
53
+ if (session !== undefined && session !== null) {
54
+ if (!has(session)) {
55
+ return {
56
+ tab: null,
57
+ source: 'session-gone',
58
+ error: 'your tab ' + session + ' is gone (closed); call ui.new_tab to open a new one, or ui.set_active_tab to pick one that still exists. Refusing to fall back to another tab — that would run this call on someone else\'s page.',
59
+ };
60
+ }
61
+ return { tab: session, source: 'session' };
62
+ }
63
+
64
+ if (has(active)) return { tab: active, source: 'active' };
65
+ if (known.length) return { tab: known[0], source: 'first' };
66
+ return { tab: null, source: 'none', error: 'no tabs open' };
67
+ }
68
+
69
+ /**
70
+ * 新建标签页要不要**切到人眼前**。
71
+ *
72
+ * 默认 **否**:人正在看的那一页是人的东西,agent 开一个新页面不该把它顶掉。
73
+ * 三种情况例外:
74
+ * - 调用方显式要求(show:true)——"这一步需要你看一眼",比如扫码登录;
75
+ * - 人自己点的「+」(UI 层用 defaultShow:true 调);
76
+ * - 当前根本没有可见标签页,或者可见的还是**启动页** —— 那种时候没有"人的页面"
77
+ * 可保护,不看新页反而像什么都没发生(agent 干活,用户盯着百度首页)。
78
+ */
79
+ function shouldShowNewTab(o) {
80
+ const opts = o || {};
81
+ if (opts.requested === true) return true;
82
+ if (opts.requested === false) return false;
83
+ if (opts.defaultShow === true) return true;
84
+ if (!opts.hasVisible) return true;
85
+ return opts.visibleIsStartup === true;
86
+ }
87
+
88
+ /**
89
+ * 站点 window.open / target=_blank 派生出来的标签页要不要显示:
90
+ * **跟着打开它的那一个走**。后台标签页里弹出来的窗口,也不该蹦到人眼前 ——
91
+ * agent 的流程里这种弹窗极多(登录、下载、预览),每弹一个就抢一次视野。
92
+ */
93
+ function shouldShowChildTab(o) {
94
+ const opts = o || {};
95
+ if (opts.openerIsVisible === true) return true;
96
+ return false;
97
+ }
98
+
99
+ module.exports = { resolveTarget, shouldShowNewTab, shouldShowChildTab };
@@ -2,4 +2,4 @@
2
2
  // Kept in JS (not imported from package.json) to avoid Node import-attribute
3
3
  // (JSON module) compatibility issues inside Electron. package.json "version"
4
4
  // is manually synced to this value; tests assert they match.
5
- export const VERSION = '2.1.21';
5
+ export const VERSION = '2.2.0';