@glittering0717/ai-browser 2.1.20 → 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 +53 -32
- package/package.json +5 -2
- package/scripts/marketing/data_snapshot.sh +19 -1
- package/scripts/release.cjs +13 -4
- package/skills/ai-browser/SKILL.md +10 -9
- package/src/main/download_monitor.js +7 -0
- package/src/main/index.js +160 -27
- package/src/main/mcp_server.js +14 -3
- package/src/main/mcp_tools.js +16 -14
- package/src/main/media_inline.js +104 -0
- package/src/main/page_manager.js +378 -37
- package/src/main/ws_server.js +150 -7
- package/src/preload/bridge.cjs +10 -0
- package/src/renderer/download.html +217 -0
- package/src/renderer/tab_bar.html +45 -0
- package/src/shared/media_doc.cjs +154 -0
- package/src/shared/protocol.js +7 -0
- package/src/shared/tab_route.cjs +99 -0
- package/src/shared/version.js +1 -1
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
|
|
341
|
-
(`Input.dispatchKeyEvent` / `Input.dispatchMouseEvent`) does not need the window to
|
|
342
|
-
the app
|
|
343
|
-
and `disable-background-timer-throttling`, so a
|
|
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
|
-
|
|
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`
|
|
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
|
|
354
|
-
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
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
|
-
|
|
362
|
-
AI_BROWSER_FOCUS=
|
|
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
|
-
|
|
366
|
-
|
|
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
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
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
|
|
@@ -724,7 +742,7 @@ not bugs. The full write-up, including why the first measurement of this was wro
|
|
|
724
742
|
## Test & dev
|
|
725
743
|
|
|
726
744
|
```bash
|
|
727
|
-
npm test # vitest —
|
|
745
|
+
npm test # vitest — 988 tests across 70 files
|
|
728
746
|
npm run smoke # Electron contract layer, offline fixture — 31 checks
|
|
729
747
|
npm run capabilities # text fields, canvas, page source, network, DOM editing — 54 checks
|
|
730
748
|
npm run richtext # rich-text editors, nested menus, forms, errors, tags, upload — 117 checks
|
|
@@ -741,8 +759,11 @@ npm run dialog # browser-level dialogs (native sheet blocks the renderer)
|
|
|
741
759
|
npm run wrapper # "in the tree but won't click" = matched a container, not a link — 13 checks
|
|
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
|
|
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
|
|
744
765
|
npm run flicker # frame-level: no frame may render the page shrunk (needs screen recording) — 6 checks
|
|
745
|
-
npm run e2e:all # 一次跑完上面全部
|
|
766
|
+
npm run e2e:all # 一次跑完上面全部 22 个套件(每个独立端口)+ 可信汇总 — 728 checks
|
|
746
767
|
npm run verify:app # boot the packaged /Applications app and assert on it — 22 checks
|
|
747
768
|
npm run realsites # navigate/read/act against a matrix of real sites
|
|
748
769
|
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@glittering0717/ai-browser",
|
|
3
|
-
"version": "2.
|
|
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": {
|
|
@@ -87,7 +87,10 @@
|
|
|
87
87
|
"wrapper": "node e2e/wrapper_ws.cjs",
|
|
88
88
|
"paint": "node e2e/paint_ws.cjs",
|
|
89
89
|
"layout": "node e2e/layout_ws.cjs",
|
|
90
|
-
"flicker": "node e2e/flicker_ws.cjs"
|
|
90
|
+
"flicker": "node e2e/flicker_ws.cjs",
|
|
91
|
+
"download": "node e2e/download_ws.cjs",
|
|
92
|
+
"multiagent": "node e2e/multiagent_ws.cjs",
|
|
93
|
+
"background": "node e2e/background_ws.cjs"
|
|
91
94
|
},
|
|
92
95
|
"dependencies": {
|
|
93
96
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
@@ -27,7 +27,25 @@ CLONEU14=$(jqf "repos/Glittering/ai-browser/traffic/clones" '.uniques' '?')
|
|
|
27
27
|
|
|
28
28
|
# --- npm ---
|
|
29
29
|
NPM_VER=$(curl -s --max-time 15 "https://registry.npmjs.org/@glittering0717%2Fai-browser" 2>/dev/null | python3 -c "import json,sys; print(json.load(sys.stdin)['dist-tags']['latest'])" 2>/dev/null || echo '?')
|
|
30
|
-
|
|
30
|
+
# npm 周下载:显式区间端点(今天-7 → 今天-1,共 7 天)。
|
|
31
|
+
# 2026-10-27 事故:last-week/last-day 相对端点全局故障——对所有包(express 对照组同样中招)
|
|
32
|
+
# 返回数月前陈旧窗口,导致 npm_dl 假性归零;故改用 range 端点自行汇总。
|
|
33
|
+
# 已知局限:npm 近日数据有回填滞后(读取数日后才修正),末 1-2 天可能低估。
|
|
34
|
+
# 防护:校验响应窗口与请求窗口一致,不一致则记 N/A,避免再次静默采到陈旧数据。
|
|
35
|
+
NPM_DL_START=$(date -u -v-7d +%Y-%m-%d 2>/dev/null || date -u -d '7 days ago' +%Y-%m-%d)
|
|
36
|
+
NPM_DL_END=$(date -u -v-1d +%Y-%m-%d 2>/dev/null || date -u -d '1 day ago' +%Y-%m-%d)
|
|
37
|
+
NPM_DL=$(curl -s --max-time 15 "https://api.npmjs.org/downloads/range/${NPM_DL_START}:${NPM_DL_END}/@glittering0717/ai-browser" 2>/dev/null | NPM_EXP_START="$NPM_DL_START" NPM_EXP_END="$NPM_DL_END" python3 -c "
|
|
38
|
+
import json,sys,os
|
|
39
|
+
try:
|
|
40
|
+
d=json.load(sys.stdin)
|
|
41
|
+
dl=d.get('downloads')
|
|
42
|
+
if not dl: raise ValueError('empty downloads')
|
|
43
|
+
if d.get('start')!=os.environ['NPM_EXP_START'] or d.get('end')!=os.environ['NPM_EXP_END']:
|
|
44
|
+
raise ValueError('window mismatch: %s..%s' % (d.get('start'), d.get('end')))
|
|
45
|
+
print(sum(x.get('downloads',0) for x in dl))
|
|
46
|
+
except Exception:
|
|
47
|
+
print('N/A')
|
|
48
|
+
" 2>/dev/null || echo 'N/A')
|
|
31
49
|
|
|
32
50
|
# --- MCP Registry(取 isLatest 条目;API 偶发超时,带重试)---
|
|
33
51
|
mcp_fetch() {
|
package/scripts/release.cjs
CHANGED
|
@@ -3,8 +3,8 @@
|
|
|
3
3
|
// push(GitHub) → npm publish → MCP registry publish。
|
|
4
4
|
//
|
|
5
5
|
// 为什么要这个脚本(而不是每次手工敲 8 条命令):
|
|
6
|
-
// 发版最容易漏的不是编译,是**同步**。版本号有
|
|
7
|
-
// server.json 两处、src/shared/version.js),GitHub 有 2 条分支 + 1 个 tag,
|
|
6
|
+
// 发版最容易漏的不是编译,是**同步**。版本号有 5 处(package.json、
|
|
7
|
+
// package-lock 两处、server.json 两处、src/shared/version.js),GitHub 有 2 条分支 + 1 个 tag,
|
|
8
8
|
// 发布有 2 个仓库(npm、MCP registry)。漏一处不会报错,只会让用户在
|
|
9
9
|
// issue 里报一个不存在的版本、或者让 npx 拉到的还是旧版 —— 而且要到
|
|
10
10
|
// 下一次有人装的时候才发现。机器不会漏,人会。
|
|
@@ -108,7 +108,16 @@ rewrite('package.json', (s) => s.replace(`"version": "${from}"`, `"version": "${
|
|
|
108
108
|
// registry 认为"清单说 2.1.3、实际包是 2.1.2",校验直接不通过。
|
|
109
109
|
rewrite('server.json', (s) => s.split(`"version": "${from}"`).join(`"version": "${to}"`));
|
|
110
110
|
rewrite('src/shared/version.js', (s) => s.replace(`VERSION = '${from}'`, `VERSION = '${to}'`));
|
|
111
|
-
|
|
111
|
+
// package-lock 里的 version 字段(顶层 + packages[""])也得改。npm 自己不校验它,
|
|
112
|
+
// 但任何人 `npm install` 一次就会把它刷成新值 —— 于是工作区变脏、下一次发版的
|
|
113
|
+
// 「前置检查」直接卡住(2026-10-25 就在这上面卡过一轮)。锁文件的两个 version
|
|
114
|
+
// 都替换;少了任何一处,下次 install 又会漂回去。
|
|
115
|
+
try {
|
|
116
|
+
rewrite('package-lock.json', (s) => s.split(`"version": "${from}"`).join(`"version": "${to}"`));
|
|
117
|
+
} catch (e) {
|
|
118
|
+
warn('package-lock.json 版本号未同步(可能本来就漂着):' + String(e.message).split('\n')[0]);
|
|
119
|
+
}
|
|
120
|
+
ok('5 处版本号已同步(package.json / package-lock×2 / server.json×2 / version.js)');
|
|
112
121
|
mark('版本号');
|
|
113
122
|
|
|
114
123
|
// ---- 2. 测试 --------------------------------------------------------------
|
|
@@ -132,7 +141,7 @@ step('提交并打 tag');
|
|
|
132
141
|
const notes = notesFile
|
|
133
142
|
? fs.readFileSync(notesFile, 'utf8').trim()
|
|
134
143
|
: `v${to}`;
|
|
135
|
-
git('add', 'package.json', 'server.json', 'src/shared/version.js');
|
|
144
|
+
git('add', 'package.json', 'package-lock.json', 'server.json', 'src/shared/version.js');
|
|
136
145
|
git('commit', '-m', `chore(release): v${to}`);
|
|
137
146
|
ok(`commit chore(release): v${to}`);
|
|
138
147
|
mark('commit');
|
|
@@ -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`
|
|
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`
|
|
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
|
|
|
@@ -28,6 +28,9 @@ export class DownloadMonitor {
|
|
|
28
28
|
this._byTab = new Map();
|
|
29
29
|
this._seq = 0;
|
|
30
30
|
this._broadcast = opts.broadcast || (() => {});
|
|
31
|
+
// 下载**开始**时的钩子(不是 done):调用方据此判断"这个 tab 是不是就为了
|
|
32
|
+
// 这次下载而开的"—— 那种 tab 永远等不到导航提交,会一直停在占位页上。
|
|
33
|
+
this._onStart = opts.onStart || null;
|
|
31
34
|
this._installed = false;
|
|
32
35
|
}
|
|
33
36
|
|
|
@@ -65,6 +68,10 @@ export class DownloadMonitor {
|
|
|
65
68
|
started_at: new Date().toISOString(),
|
|
66
69
|
};
|
|
67
70
|
this._push(tabId, rec);
|
|
71
|
+
if (typeof this._onStart === 'function') {
|
|
72
|
+
// 这个钩子绝不能拖垮下载本身:它只做 UI 接管,出错就当地不存在。
|
|
73
|
+
try { this._onStart(rec, tabId); } catch (_) { /* ignore */ }
|
|
74
|
+
}
|
|
68
75
|
|
|
69
76
|
item.on('updated', (_e, state) => {
|
|
70
77
|
rec.received_bytes = item.getReceivedBytes();
|
package/src/main/index.js
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
// main/index.js — Electron entry v5 (multi-tab, real UI)
|
|
2
2
|
// One process, one WS server, multiple tabs with real tab bar.
|
|
3
|
-
import { app, BrowserWindow, BrowserView, ipcMain, net, session, dialog, screen, powerMonitor } from 'electron';
|
|
3
|
+
import { app, BrowserWindow, BrowserView, ipcMain, net, session, dialog, screen, powerMonitor, shell, nativeImage } from 'electron';
|
|
4
4
|
import path from 'node:path';
|
|
5
5
|
import fs from 'node:fs';
|
|
6
6
|
import { fileURLToPath } from 'node:url';
|
|
7
7
|
import { startWSServer } from './ws_server.js';
|
|
8
8
|
import { PageManager } from './page_manager.js';
|
|
9
9
|
import { config } from '../shared/config.js';
|
|
10
|
+
import mediaDoc from '../shared/media_doc.cjs';
|
|
10
11
|
import { parseWatchdogTargets, isWatchdogEnabled } from '../shared/watchdog.js';
|
|
11
12
|
import { wrapSetActive } from '../shared/tab_hooks.js';
|
|
12
13
|
import { initErrorLog, recordError, markShutdown, getLogPath } from './error_log.js';
|
|
@@ -354,6 +355,21 @@ if (gotLock) {
|
|
|
354
355
|
mainWindow.focus();
|
|
355
356
|
}
|
|
356
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
|
+
});
|
|
357
373
|
} else if (!(process.platform === 'darwin' && app.isPackaged)) {
|
|
358
374
|
// A real second instance would fight the first one over the :9223 WS port.
|
|
359
375
|
// Still tolerant of weird environments (EPERM on sandboxed setups, and
|
|
@@ -445,7 +461,7 @@ function createWindow() {
|
|
|
445
461
|
const START_URL = process.env.AI_BROWSER_START_URL !== undefined
|
|
446
462
|
? (process.env.AI_BROWSER_START_URL || null)
|
|
447
463
|
: 'https://www.baidu.com';
|
|
448
|
-
pageManager.newTab(START_URL);
|
|
464
|
+
pageManager.startupTab = pageManager.newTab(START_URL);
|
|
449
465
|
|
|
450
466
|
// 启动阶段崩溃排的队到这里兑现:窗口、标签栏、页面视图都已就绪,横幅才挂得上。
|
|
451
467
|
flushPendingBanner();
|
|
@@ -475,18 +491,7 @@ function createWindow() {
|
|
|
475
491
|
ipcMain.on('error-banner:close', () => { setImmediate(hideErrorBanner); });
|
|
476
492
|
|
|
477
493
|
// === 地址栏 / 导航按钮 ===
|
|
478
|
-
ipcMain.handle('nav:state', () =>
|
|
479
|
-
const wc = activeWebContents();
|
|
480
|
-
if (!wc) return { tab: null, url: '', canBack: false, canForward: false, loading: false, status: '' };
|
|
481
|
-
return {
|
|
482
|
-
tab: pageManager.activeTab,
|
|
483
|
-
url: wc.getURL(),
|
|
484
|
-
canBack: wc.navigationHistory ? wc.navigationHistory.canGoBack() : wc.canGoBack(),
|
|
485
|
-
canForward: wc.navigationHistory ? wc.navigationHistory.canGoForward() : wc.canGoForward(),
|
|
486
|
-
loading: wc.isLoading(),
|
|
487
|
-
status: wc.isLoading() ? '加载中…' : '',
|
|
488
|
-
};
|
|
489
|
-
});
|
|
494
|
+
ipcMain.handle('nav:state', () => buildNavState());
|
|
490
495
|
ipcMain.on('nav:go', (_e, input) => {
|
|
491
496
|
const url = normalizeUrlInput(input);
|
|
492
497
|
if (!url) return;
|
|
@@ -499,6 +504,59 @@ function createWindow() {
|
|
|
499
504
|
ipcMain.on('nav:forward', () => { const wc = activeWebContents(); if (wc && wc.navigationHistory) wc.navigationHistory.goForward(); });
|
|
500
505
|
ipcMain.on('nav:reload', () => { const wc = activeWebContents(); if (wc) wc.reload(); });
|
|
501
506
|
ipcMain.on('nav:stop', () => { const wc = activeWebContents(); if (wc) wc.stop(); });
|
|
507
|
+
// 工具条上的「下载」:当前页是一份被救回来的图片/视频/PDF 时,存进下载目录。
|
|
508
|
+
// 为什么不在页面里放按钮:站点页面的 DOM 我们不该改(会被 CSS 打架、被 CSP 拦、
|
|
509
|
+
// 也会让"页面内容"不再可信);按钮挂在自家 chrome 上,任何站点都一致。
|
|
510
|
+
ipcMain.on('nav:download', () => {
|
|
511
|
+
if (!pageManager) return;
|
|
512
|
+
pageManager.downloadCurrent(pageManager.activeTab);
|
|
513
|
+
});
|
|
514
|
+
|
|
515
|
+
// === 下载结果页(renderer/download.html)===
|
|
516
|
+
//
|
|
517
|
+
// ⚠️ `__ai_browser__.dl` 挂在每个标签页的 window 上(含站点页面),所以这里
|
|
518
|
+
// 必须自己把门:只受理我们自己的界面页,并且路径必须在下载目录之内。
|
|
519
|
+
// 少了这道门,任意站点都能让浏览器"打开/在 Finder 里高亮"用户下载过的文件。
|
|
520
|
+
const isChromeSender = (event) => {
|
|
521
|
+
try { return mediaDoc.isChromePageUrl(event.sender.getURL()); } catch (_) { return false; }
|
|
522
|
+
};
|
|
523
|
+
const insideDownloads = (p) => {
|
|
524
|
+
try {
|
|
525
|
+
const base = path.resolve(pageManager.downloadMonitor.baseDir);
|
|
526
|
+
const abs = path.resolve(String(p || ''));
|
|
527
|
+
return abs === base || abs.startsWith(base + path.sep);
|
|
528
|
+
} catch (_) { return false; }
|
|
529
|
+
};
|
|
530
|
+
ipcMain.handle('dl:record', (event) => {
|
|
531
|
+
if (!isChromeSender(event)) return { found: false };
|
|
532
|
+
const tab = pageManager._tabIdOfWebContents(event.sender);
|
|
533
|
+
if (tab === undefined) return { found: false };
|
|
534
|
+
const list = pageManager.downloadMonitor.list(tab).downloads || [];
|
|
535
|
+
const rec = list[list.length - 1];
|
|
536
|
+
if (!rec) return { found: false };
|
|
537
|
+
const out = {
|
|
538
|
+
found: true,
|
|
539
|
+
state: rec.state,
|
|
540
|
+
received: rec.received_bytes,
|
|
541
|
+
total: rec.total_bytes,
|
|
542
|
+
path: rec.path,
|
|
543
|
+
filename: rec.filename,
|
|
544
|
+
mime: rec.mime,
|
|
545
|
+
};
|
|
546
|
+
if (rec.state === 'completed' && mediaDoc.kindOf(rec.mime) === 'image') {
|
|
547
|
+
out.thumb = thumbDataUrl(rec.path);
|
|
548
|
+
}
|
|
549
|
+
return out;
|
|
550
|
+
});
|
|
551
|
+
ipcMain.on('dl:open', (event, p) => {
|
|
552
|
+
if (!isChromeSender(event) || !insideDownloads(p)) return;
|
|
553
|
+
try { if (fs.existsSync(p)) shell.openPath(p).catch(() => {}); } catch (_) { /* ignore */ }
|
|
554
|
+
});
|
|
555
|
+
ipcMain.on('dl:reveal', (event, p) => {
|
|
556
|
+
if (!isChromeSender(event) || !insideDownloads(p)) return;
|
|
557
|
+
try { shell.showItemInFolder(p); } catch (_) { /* ignore */ }
|
|
558
|
+
});
|
|
559
|
+
|
|
502
560
|
// 错误页里的重试 / 返回(错误页是我们自己的 renderer,同样走 ipc)
|
|
503
561
|
ipcMain.on('error-page:navigate', (_e, input) => {
|
|
504
562
|
const wc = activeWebContents();
|
|
@@ -662,10 +720,19 @@ function showInitialWindow() {
|
|
|
662
720
|
if (!mainWindow) return;
|
|
663
721
|
const policy = String(process.env.AI_BROWSER_FOCUS || 'auto').toLowerCase();
|
|
664
722
|
const byAgent = process.env.AI_BROWSER_LAUNCHED_BY_AGENT === '1';
|
|
665
|
-
//
|
|
666
|
-
//
|
|
667
|
-
//
|
|
668
|
-
//
|
|
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
|
+
// 留在用户那边。
|
|
669
736
|
const shouldActivate = policy === 'always' || (policy !== 'never' && !byAgent);
|
|
670
737
|
|
|
671
738
|
const doShow = () => {
|
|
@@ -883,21 +950,87 @@ function updateWindowTitle() {
|
|
|
883
950
|
try { mainWindow.setTitle(next); } catch (_) { /* 窗口在关闭竞态里 */ }
|
|
884
951
|
}
|
|
885
952
|
|
|
953
|
+
/**
|
|
954
|
+
* 地址栏 + 工具条需要的一切状态。
|
|
955
|
+
*
|
|
956
|
+
* 单一实现:`nav:state`(初始化时自取)与 `pushNavState`(事件 + 1.5s 轮询)
|
|
957
|
+
* 必须是同一份 —— 两处各写一遍的结果是"某些字段只在某条路上有",表现为
|
|
958
|
+
* 按钮有时出现有时不出现,而且极难复现。
|
|
959
|
+
*/
|
|
960
|
+
function buildNavState() {
|
|
961
|
+
const wc = activeWebContents();
|
|
962
|
+
if (!wc) {
|
|
963
|
+
return { tab: null, url: '', canBack: false, canForward: false, loading: false, status: '', media_doc: null, download: null };
|
|
964
|
+
}
|
|
965
|
+
const tab = pageManager.activeTab;
|
|
966
|
+
const url = wc.getURL();
|
|
967
|
+
let media = null;
|
|
968
|
+
try { media = pageManager.mediaDocOf(tab); } catch (_) { media = null; }
|
|
969
|
+
return {
|
|
970
|
+
tab,
|
|
971
|
+
url,
|
|
972
|
+
canBack: wc.navigationHistory ? wc.navigationHistory.canGoBack() : wc.canGoBack(),
|
|
973
|
+
canForward: wc.navigationHistory ? wc.navigationHistory.canGoForward() : wc.canGoForward(),
|
|
974
|
+
loading: wc.isLoading(),
|
|
975
|
+
status: wc.isLoading() ? '加载中…' : '',
|
|
976
|
+
// 当前页是一份"本来会被下载、被救回来显示"的文档(图片/视频/音频/PDF)
|
|
977
|
+
// → 工具条显示「下载」按钮。
|
|
978
|
+
media_doc: media ? { url: media.url, mime: media.mime, kind: media.kind } : null,
|
|
979
|
+
// 页面里发起的下载(导出 CSV、点附件…)完成后的回执。下载结果页本身就在
|
|
980
|
+
// 展示文件,再弹一条是重复信息,所以那里不显示。
|
|
981
|
+
download: recentDownloadOf(tab, url),
|
|
982
|
+
};
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
/** 8 秒内的"刚下载完"回执;超时就不再提示(不留一个永远挂着的角标)。 */
|
|
986
|
+
const RECENT_DOWNLOAD_MS = 8000;
|
|
987
|
+
function recentDownloadOf(tab, currentUrl) {
|
|
988
|
+
if (mediaDoc.isChromePageUrl(currentUrl)) return null;
|
|
989
|
+
try {
|
|
990
|
+
const list = pageManager.downloadMonitor.list(tab).downloads || [];
|
|
991
|
+
const last = list[list.length - 1];
|
|
992
|
+
if (!last || last.state !== 'completed' || !last.finished_at) return null;
|
|
993
|
+
const at = Date.parse(last.finished_at);
|
|
994
|
+
if (!isFinite(at) || Date.now() - at > RECENT_DOWNLOAD_MS) return null;
|
|
995
|
+
return { name: last.filename, path: last.path, size: last.total_bytes };
|
|
996
|
+
} catch (_) {
|
|
997
|
+
return null;
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
/**
|
|
1002
|
+
* 图片缩略图(只在"这张图已经下载完"时生成)。
|
|
1003
|
+
*
|
|
1004
|
+
* 走 nativeImage 而不是让页面写 `<img src="file://…">`:file:// 页面对 file://
|
|
1005
|
+
* 子资源的访问在 Chromium 里并不保证,做成 data URL 则哪里都能显示。
|
|
1006
|
+
* 按路径缓存 —— 结果页每 500ms 轮询一次,不缓存就会反复解码同一张图。
|
|
1007
|
+
*/
|
|
1008
|
+
const thumbCache = new Map();
|
|
1009
|
+
function thumbDataUrl(p) {
|
|
1010
|
+
if (!p) return null;
|
|
1011
|
+
if (thumbCache.has(p)) return thumbCache.get(p);
|
|
1012
|
+
let url = null;
|
|
1013
|
+
try {
|
|
1014
|
+
const img = nativeImage.createFromPath(p);
|
|
1015
|
+
if (img && !img.isEmpty()) {
|
|
1016
|
+
const size = img.getSize();
|
|
1017
|
+
const small = size.width > 480 ? img.resize({ width: 480, quality: 'good' }) : img;
|
|
1018
|
+
const jpg = small.toJPEG(72);
|
|
1019
|
+
if (jpg && jpg.length) url = 'data:image/jpeg;base64,' + jpg.toString('base64');
|
|
1020
|
+
}
|
|
1021
|
+
} catch (_) { url = null; }
|
|
1022
|
+
if (thumbCache.size > 16) thumbCache.clear();
|
|
1023
|
+
thumbCache.set(p, url);
|
|
1024
|
+
return url;
|
|
1025
|
+
}
|
|
1026
|
+
|
|
886
1027
|
/** 把地址栏需要的一切状态推给 tab bar renderer。 */
|
|
887
1028
|
function pushNavState() {
|
|
888
1029
|
// 标题先更新:它不依赖 tabBarView 是否存活(横幅/崩溃场景下 tabBarView
|
|
889
1030
|
// 可能已被销毁,但窗口标题仍应反映真实页面)。
|
|
890
1031
|
updateWindowTitle();
|
|
891
1032
|
if (!tabBarView || tabBarView.webContents.isDestroyed()) return;
|
|
892
|
-
const
|
|
893
|
-
const state = wc ? {
|
|
894
|
-
tab: pageManager.activeTab,
|
|
895
|
-
url: wc.getURL(),
|
|
896
|
-
canBack: wc.navigationHistory ? wc.navigationHistory.canGoBack() : wc.canGoBack(),
|
|
897
|
-
canForward: wc.navigationHistory ? wc.navigationHistory.canGoForward() : wc.canGoForward(),
|
|
898
|
-
loading: wc.isLoading(),
|
|
899
|
-
status: wc.isLoading() ? '加载中…' : '',
|
|
900
|
-
} : { tab: null, url: '', canBack: false, canForward: false, loading: false, status: '' };
|
|
1033
|
+
const state = buildNavState();
|
|
901
1034
|
tabBarView.webContents.executeJavaScript(
|
|
902
1035
|
'window.__onNavState && window.__onNavState(' + JSON.stringify(state) + ')'
|
|
903
1036
|
).catch(() => {});
|
package/src/main/mcp_server.js
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
}
|