@glittering0717/ai-browser 2.5.2 → 2.5.5

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
@@ -77,8 +77,24 @@ Two things to know before you download it:
77
77
  - **It is not notarized.** macOS Gatekeeper will refuse to open it on the first try. Right-click
78
78
  the app → **Open**, confirm once, and it runs normally afterwards. (A paid Apple Developer
79
79
  account is what removes this step; until then, this is the honest cost.)
80
- - **Only macOS `arm64` is built.** Windows and Linux have no package yet, because neither has
81
- been verified on this project — see [Compatibility](#compatibility).
80
+ - **Only macOS `arm64` and Windows `x64` are built.** Linux has no package yet — see
81
+ [Compatibility](#compatibility).
82
+
83
+ ### Option A2 — Windows installer
84
+
85
+ Grab `AI-Browser-<version>-win32-x64-Setup.exe` from the same Releases page (~79 MB). Run it and
86
+ click through: it installs **per user** to `%LOCALAPPDATA%\Programs\AI Browser` (no admin prompt,
87
+ no UAC), creates the **Start Menu** entry and a **Desktop** shortcut by itself, and offers to launch
88
+ the browser when it finishes. Uninstall is a normal entry in **Settings → Apps**; it removes the
89
+ program and both shortcuts but leaves `~/.ai-browser` alone, so your profiles and logins survive a
90
+ reinstall.
91
+
92
+ Two things to know:
93
+
94
+ - **It is not code-signed.** SmartScreen may show "Windows protected your PC" → **More info** →
95
+ **Run anyway**. (A code-signing certificate is what removes this step.)
96
+ - The installer is a plain NSIS wizard, so you can pick the install location; the default is the
97
+ per-user path above.
82
98
 
83
99
  Agents still connect through the MCP server (Option B below), and the two channels cooperate:
84
100
  when the packaged app is already running, the MCP server finds it on port 9223 and **reuses it
@@ -220,7 +236,7 @@ small surface, since every tool schema is injected into your agent's context on
220
236
  | `browse_tabs` | Tabs: `list` / `new` / `close` / `switch` / `window`. `switch` = default; add `show:true`. `new` never steals the view unless `show:true`. |
221
237
  | `browse_network` | Chrome-DevTools-style network inspection: `list` (filter by method / URL / status / type), `get` (request + response headers and bodies), `clear`, `configure`. |
222
238
  | `browse_auth_state` | Login-state self-check for a tab: are we logged in, or bounced to a login wall. Cheap — no tree is built. |
223
- | `browse_screenshot` | Diagnostic viewport/element capture (`png`/`jpeg`/`webp`, `clip`, `fullPage`). Not the read path — use it when the tree and the screen disagree. |
239
+ | `browse_screenshot` | Diagnostic viewport/element capture (`png`/`jpeg`/`webp`, `clip`, `fullPage`, `source: auto`/`surface`/`cdp`). Not the read path — use it when the tree and the screen disagree. The receipt says which tier answered. |
224
240
  | `browse_errors` | Recent errors the browser recorded (crashes, failed navigations, RPC failures) with hints. Ask here when behaviour doesn't match the docs. |
225
241
  | `browse_quit` | Shut the whole browser down and release the process. |
226
242
 
@@ -375,13 +391,21 @@ Three things used to make "run it in the background" impossible, and all three a
375
391
  ```bash
376
392
  AI_BROWSER_START_HIDDEN=1 npm start # run with no window at all; click the Dock icon to bring it up
377
393
  AI_BROWSER_FOCUS=always npm start # pre-1.2 behaviour: show + moveTop + focus on every action
378
- AI_BROWSER_FOCUS=never npm start # same as the default now: never touch window state
394
+ AI_BROWSER_FOCUS=never npm start # never touch window state *or* page focus — see the caveat below
395
+ AI_BROWSER_INPUT_FOCUS=0 npm start # don't emulate page focus for a tab that can't receive input
379
396
  ```
380
397
 
381
398
  While it is hidden, everything still works — read the tree, click, type, scroll, upload, download,
382
399
  answer dialogs, capture network, screenshot, `paint_check`. Click the Dock icon at any moment and the
383
400
  window appears showing the tab *you* were looking at; the agents keep working on theirs.
384
401
 
402
+ ⚠️ "click and type work while hidden" is a promise the browser now *makes* true, not a property of
403
+ Chromium: simulated input is dropped on any document reporting `visibilityState: hidden`, so each
404
+ trusted-input action first checks that tab and, if needed, gives it the page-focus emulation the front
405
+ tab already has (see *Tab groups* above). `AI_BROWSER_FOCUS=never` switches that emulation off
406
+ altogether, and then a hidden window genuinely cannot receive simulated input — `ui.act` fails with
407
+ `input_blocked: true` instead of reporting success. That is the honest outcome, not a regression.
408
+
385
409
  `npm run focus` asserts the focus behaviour **from the outside** (macOS `lsappinfo`, no accessibility
386
410
  permission needed) with a deliberate control group configured to steal focus, so the suite goes red if
387
411
  the measurement ever stops working instead of passing vacuously. `npm run background` covers the
@@ -443,7 +467,7 @@ Each group is capped (8 by default, `AI_BROWSER_TAB_LIMIT`). Opening past the ca
443
467
 
444
468
  ```
445
469
  -32001 your tab group is full (8/8) — close one before opening another
446
- data: { reason: "group-full", limit: 8, tabs: [{tab, url}, ...] }
470
+ data: { reason: "group-full", limit: 8, tabs: [{tab, url, draft?, downloading?}, ...] }
447
471
  ```
448
472
 
449
473
  Over MCP the agent receives this as a tool result with `isError: true` and the readable text
@@ -451,11 +475,48 @@ Over MCP the agent receives this as a tool result with `isError: true` and the r
451
475
  acts on, not a JSON-RPC protocol error. The `data` fields above are the raw-WS detail.
452
476
 
453
477
  Popups cannot be refused (the page's script is waiting for the window), so in that one case the least
454
- recently used tab in the group — never the visible one, never one with a dialog open — is closed
455
- instead, and reported in `browse_tabs {"op":"list"}` as `evicted`.
456
-
457
- `npm run multiagent` (46 checks) covers it, M7–M9: auto workspace, the cap and its refusal payload,
458
- and that one full group does not affect anybody else's.
478
+ recently used tab in the group is closed instead — never the visible one, never one with a dialog
479
+ open, and since 2026-11-03 also never one holding **unsubmitted input** (a `type`/`setContent`/`paste`
480
+ that hasn't been followed by a real navigation) or an **in-progress download**. The reason for the
481
+ last two is that eviction here is a full tab close, harsher than Chrome's discard: a discard leaves
482
+ the form, our close leaves nothing. If nothing qualifies, the group is allowed one tab over the cap —
483
+ better a page too many than a page you were working on swallowed. Whatever got closed is reported in
484
+ `browse_tabs {"op":"list"}` as `evicted`, and the two protections are marked in the refusal payload
485
+ (`tabs[].draft` / `tabs[].downloading`) because when it's *your* turn to decide what to close, that's
486
+ the only evidence you have.
487
+
488
+ **Sound follows the visible tab only.** Every tab lives in one window and z-order decides which one
489
+ the human sees — audio has no z-order, so an agent's background video plays out loud and there is no
490
+ speaker to find. Non-active tabs of an agent group are muted from birth; the tab in front and your own
491
+ tabs are never muted (Chrome leaves those playing too). Muted tabs carry `muted: true` in
492
+ `browse_tabs {"op":"list"}`. Muting is **output gain, not pause**: `currentTime` keeps advancing, so
493
+ the page the agent reads is not secretly a stalled one. Turn the rule off with `AI_BROWSER_BG_MUTE=0`.
494
+
495
+ **Trusted input reaches the tab you aimed at, not just the visible one.** Chromium *drops* simulated
496
+ input on any document that reports `visibilityState: hidden` — and in a window that was never shown,
497
+ the only page that reports `visible` is the one that got CDP page-focus emulation, which the browser
498
+ normally hands to the front tab alone. The old shape was the worst possible one: the event vanished,
499
+ nothing was clicked, and `ui.act` still answered `{success:true, clicked_via:'cdp-click'}`. So before
500
+ every trusted-input action (`click`/`hover`/`drag`/`wheel`/`type`/`setContent`/`clear`/`press`/`paste`)
501
+ the browser asks that tab "are you visible?", and if it isn't, hands it the same focus emulation it
502
+ already gives the front tab — no z-order change, no window shown, `activeTab` and mute state untouched,
503
+ and nothing is restored afterwards (the emulation is sticky; toggling it would put every page through
504
+ visible→hidden→visible on every action). If a tab still can't receive input, the action is **not
505
+ dispatched** and the receipt says so: `success:false` + `input_blocked:true` + the page's visibility,
506
+ with the escape hatches named (JS path via `ui.evaluate`, or show the window once). Measured 2026-11-03:
507
+ raising the tab (`setTopBrowserView`), `webContents.focus()`, detach+reattach, `setBounds`,
508
+ `setBackgroundThrottling(false)` and `Page.setWebLifecycleState{active}` do **not** deliver input;
509
+ `Emulation.setPageVisibilityOverride` does not exist in Chromium 130. "The active tab is always visible"
510
+ turned out to be false too — under `AI_BROWSER_FOCUS=never` even it reports hidden and input is dropped,
511
+ which is why every trusted-input action pays one short (800ms-capped) probe. `AI_BROWSER_INPUT_FOCUS=0`
512
+ turns off the *emulation* only; honesty about the failure is not switchable.
513
+
514
+ `npm run multiagent` (80 checks) covers the positive half — M11 clicks and types into a background tab
515
+ in a never-shown window while the control tab and `activeTab` stay put. `npm run input_routing`
516
+ (15 checks, two instances) covers the honest-failure half under `AI_BROWSER_INPUT_FOCUS=0` and
517
+ `AI_BROWSER_FOCUS=never`. Both also pin the rest of it: auto workspace, the cap and its refusal payload,
518
+ that one full group does not affect anybody else's, who gets evicted when a popup needs the space, and
519
+ that a muted tab is still playing.
459
520
 
460
521
  ---
461
522
 
@@ -627,6 +688,16 @@ Because the events arrive as real keyboard and mouse input,
627
688
  Draft.js, ProseMirror, CKEditor, Quill, and plain `<textarea>` all work through the same path without
628
689
  per-framework branches.
629
690
 
691
+ **Popups.** A site asking for an overlay — `window.open(url, name, 'width=420,height=520,left=120,top=80')`
692
+ (login boxes, payment QR codes, pickers) — gets one: that tab's view is placed at exactly the rectangle it
693
+ requested, on top of its parent, instead of filling the window. The geometry is read from the third argument,
694
+ which this project used to discard on both entry points (the handler destructured `url`, the page-world shim
695
+ named its parameter `_features` and never used it), so every 420×520 login box grew into a full-size tab and
696
+ laid itself out for 1280px. Only size-bearing features count, exactly as in Chrome: `noopener` / `_blank` are
697
+ not sizes and still open an ordinary tab — the suite runs that negative control in the same pass. Shrinking
698
+ the window re-clamps the overlay; growing it does not enlarge the overlay back. `ui.list_tabs` adds a `popup`
699
+ rectangle for those tabs, because clicking or screenshotting them on full-window coordinates misses.
700
+
630
701
  **Where it is thin.** `extractor.cjs` is a heuristic over the DOM, not a clean-room specification: it
631
702
  handles ordinary pages well and will mislabel exotic ones. The window runs with hardware acceleration
632
703
  off plus three Chromium switches
@@ -658,15 +729,39 @@ node examples/read-page.mjs
658
729
 
659
730
  ## Troubleshooting
660
731
 
661
- **The page updated but the window still shows the old one.** This used to require clicking tabs
662
- back and forth, because the only thing that forced the compositor to redraw a `BrowserView` was
663
- `setActiveTab` doing `removeBrowserView` + `addBrowserView` + `setBounds` — navigation never did it.
664
- Now every navigation signal triggers it: `did-navigate`, `did-navigate-in-page` (SPA route changes
665
- fire no load event at all), `did-frame-finish-load` (a canvas editor inside an iframe boots long
666
- after the top document finished), plus window `show` / `restore` / `focus` — which matters here
667
- because this window is designed never to steal your focus, so it sits behind your editor for
668
- minutes at a time. If it still looks stale, `ui.repaint` forces it on demand and returns
669
- `repaint_count` so you can confirm a repaint actually happened.
732
+ **The page updated but the window still shows the old one.** A `BrowserView`'s surface is only
733
+ re-rasterized when something forces it, so the app asks for a repaint on window `show` / `restore` /
734
+ `focus` — that matters because this window is designed never to steal your focus, so it can sit behind
735
+ your editor for minutes while the agent works. `ui.repaint` forces it on demand and reports
736
+ `repaint_count`, the only externally observable proof that a repaint actually happened.
737
+
738
+ Two things to know about that knob:
739
+
740
+ - The default is **soft** (`webContents.invalidate()`): it never touches geometry, so it cannot make
741
+ the window jump. It is deliberately not stronger. A 1px bounds nudge is the only thing that rebuilds
742
+ a surface whose *pixels* are wrong, and it costs two relayouts — which is exactly the
743
+ "grows-then-shrinks, flickers" complaint this app got when that ran on the hot paths
744
+ (`e2e/layout_ws` G4/G5 now pin navigation and tab-switch to zero repaints by default).
745
+ - **"A login overlay with a different site behind it" is not this class of bug** (root-caused
746
+ 2026-11-02). Every tab's view stays attached to the window, stacked on the *same* bounds, and
747
+ only z-order decides which one you see — but z-order decides who is *on top*, not that the top
748
+ one is *opaque*. A page with a transparent root background (a login page designed to live inside
749
+ an iframe overlay, opened as a top-level document; its own captured frame measured 86.3% of
750
+ pixels with alpha<255) reveals whichever tab sits directly underneath it. Each tab view is now
751
+ created as an **opaque surface** (`#FFFFFF`, the same thing a real browser does with a
752
+ transparent top-level page), so those pixels are filled by that tab itself. `npm run paint` P6
753
+ pins the invariant: an active tab's frame must not contain a single transparent pixel.
754
+ - If you really are seeing **this tab's own stale pixels** — the DOM reports the new page while
755
+ the window shows the old one — set `AI_BROWSER_HOT_REPAINT=hard` and take the flicker: it
756
+ upgrades repaint on navigation-finish, tab switch and window re-show. `disable-back-forward-cache`
757
+ is not the lever here; bfcache stores the page you navigate *away from*, so it cannot explain a
758
+ stale frame on a forward navigation, and switching it off costs you the instant back/forward restore.
759
+
760
+ Separate bug, same "the screen is lying" family: during the few hundred milliseconds between pressing
761
+ Enter and the new document committing, `webContents.getURL()` still returns the **old** page, so the
762
+ address bar used to flash back to it. It now shows the requested URL while `state` is `loading`
763
+ (`list_tabs` reports it as `pending_url`, never as `url` — an agent that read the target in `url`
764
+ would assume it had arrived and scrape the previous page).
670
765
 
671
766
  **An action reported success but nothing changed.** Two causes worth knowing:
672
767
 
@@ -755,6 +850,52 @@ Both paths are switchable: `AI_BROWSER_ERROR_BANNER=0` disables the bar, `AI_BRO
755
850
  forces the modal box — the latter blocks the main process, so it is only for staring at a startup
756
851
  crash on purpose.
757
852
 
853
+ ### A site calls it a captcha or "this browser may not be secure"
854
+
855
+ Risk control does not detect "automation" as a concept; it looks for a browser whose own fields
856
+ disagree. Ours did (measured 2026-11-01 against the same machine's Chrome 156): the UA said
857
+ `Macintosh … Chrome/130`, `navigator.platform` said `Win32`, `sec-ch-ua-platform` said `"Windows"`,
858
+ and WebGL reported a Windows D3D11 adapter. That combination does not read as "a Mac browser", it
859
+ reads as "someone edited this browser" — hence Baidu's slide captcha on almost every search and
860
+ Google's interstitial. So identity is computed by **one** function from the **real** runtime
861
+ (`src/shared/browser_identity.cjs`) and delivered in three layers: UA + UA-CH metadata through CDP,
862
+ Accept-Language as a clean preferred list (no `;q=0.9` — that value also lands in
863
+ `navigator.languages`), and the navigation-time `sec-ch-ua*` headers, which Electron's engine does
864
+ not emit at all on document requests (page-initiated `fetch` does), added at the request egress.
865
+
866
+ Ask the app instead of guessing:
867
+
868
+ ```bash
869
+ node bin/ai-browser.cjs call ui.server_info # → identity: {user_agent, chrome_version, platform,
870
+ # platform_version, brands[], brands_mode, identity_override, navigation_hints_bridge,
871
+ # override_applied_tabs[]}
872
+ ```
873
+
874
+ **Google sign-in has a second, separate trap** (six-arm measurement, 2026-11-05). Our UA used to be
875
+ a *pure* `Chrome/130.0.0.0` string with `Google Chrome` in the brand list — i.e. we claimed to be
876
+ official Chrome. Google then holds you to Chrome's browser-layer attestation (`window.chrome`'s Gaia
877
+ bindings plus the install state), which an Electron shell cannot produce, and the sign-in page
878
+ answers `/v3/signin/rejected?rrk=46`. The closer you impersonate, the harder the verdict. The UA now
879
+ carries our own product token (`ai-browser/2.5.2` — Edge sends `Edg/`, Vivaldi sends `Vivaldi/`, for
880
+ exactly this reason) and the brand list reports `Chromium` only. We *are* Chromium; that is true. Same
881
+ machine, same account, same email-only submission: the server now continues to the password step.
882
+ `AI_BROWSER_BRANDS=chrome` and `AI_BROWSER_IDENTITY=0` exist only to re-run either arm of that
883
+ comparison — do not ship them. Details and the full table: `docs/SPEC.md`, "Google 登录".
884
+
885
+ What is still genuinely different, and what to do about it:
886
+
887
+ - **The engine is 26 majors behind** (`Chrome/130` vs a current `Chrome/156`). Consistent, but an
888
+ "outdated browser" signal on its own. The only cure is upgrading Electron — a dependency bump, so
889
+ it is a deliberate release, not a patch.
890
+ - **`window.chrome.loadTimes` / `.csi` are absent** (old Chrome telemetry stubs). Low weight, not
891
+ yet filled.
892
+ - **`data-ai-id` is written into the live DOM while reading the tree** (70 attributes on Baidu's
893
+ homepage). It is load-bearing for the CDP selector path, so removing it is a refactor, not a
894
+ switch — site scripts *can* see it. This is the loudest tell left.
895
+ - **The canvas recorder and the `window.open` shim patch page-visible natives.** Both are now
896
+ opt-in (`AI_BROWSER_CANVAS_HOOK`, `AI_BROWSER_POPUP_SHIM`), and the `__ai_browser__` bridge is no
897
+ longer exposed to site pages at all — see the canvas section above.
898
+
758
899
  ### The element is clearly on the page but not in the tree
759
900
 
760
901
  Before you write a site-specific script, work down this list. The reflex — "pin it with a
@@ -811,7 +952,7 @@ not bugs. The full write-up, including why the first measurement of this was wro
811
952
  ## Test & dev
812
953
 
813
954
  ```bash
814
- npm test # vitest — 1024 tests across 73 files
955
+ npm test # vitest — 1462 tests across 104 files
815
956
  npm run smoke # Electron contract layer, offline fixture — 31 checks
816
957
  npm run capabilities # text fields, canvas, page source, network, DOM editing — 54 checks
817
958
  npm run richtext # rich-text editors, nested menus, forms, errors, tags, upload — 117 checks
@@ -829,10 +970,11 @@ npm run wrapper # "in the tree but won't click" = matched a container, not
829
970
  npm run paint # blank-page self-check: verdicts, bounded ladder, no false alarms — 23 checks
830
971
  npm run layout # geometry invariants + "no twitching" (zero extra repaints on nav) — 25 checks
831
972
  npm run download # "clicked download": viewable media must display, the rest must save — 23 checks
832
- npm run multiagent # several agents at once: own tab each, no cross-talk, gone tab errors — 46 checks
973
+ npm run multiagent # several agents at once: own tab each, no cross-talk, eviction + mute + input reaches background tabs — 80 checks
974
+ npm run input_routing # input that cannot be delivered fails honestly (2 instances: INPUT_FOCUS=0 / FOCUS=never) — 15 checks
833
975
  npm run background # window hidden/minimized: every capability still works (headless-like) — 37 checks
834
976
  npm run flicker # frame-level: no frame may render the page shrunk (needs screen recording) — 6 checks
835
- npm run e2e:all # 一次跑完上面全部 22 个套件(每个独立端口)+ 可信汇总 — 743 checks
977
+ npm run e2e:all # 一次跑完 run_all 里全部 29 个套件(每个独立端口)+ 可信汇总
836
978
  npm run verify:app # boot the packaged /Applications app and assert on it — 22 checks
837
979
  npm run realsites # navigate/read/act against a matrix of real sites
838
980
  ```
@@ -984,6 +1126,18 @@ Two limits you should know:
984
1126
 
985
1127
  Disable entirely with `AI_BROWSER_CANVAS_HOOK=0`.
986
1128
 
1129
+ **It is off by default.** Wrapping `getContext` is something the page can see — one
1130
+ `Function.prototype.toString.call(HTMLCanvasElement.prototype.getContext)` and the site knows its
1131
+ canvas API was patched (measured on Baidu, 2026-11-01). The recorder is the loudest automation tell
1132
+ this browser carried, and every site paid for it while only canvas apps gained from it. So:
1133
+
1134
+ - per tab, on demand: `browse_canvas(operation: "configure", reload: true)` installs it and gives
1135
+ the full history for that page;
1136
+ - for a whole origin: `AI_BROWSER_CANVAS_HOOK=b.chaoxing.com,excalidraw.com` (comma-separated,
1137
+ subdomains included);
1138
+ - everywhere: `AI_BROWSER_CANVAS_HOOK=1` — what v2.4 and earlier did, and what risk controls
1139
+ noticed.
1140
+
987
1141
  ### Boundaries worth knowing before you rely on them
988
1142
 
989
1143
  - **`node.value` is truncated at 200 characters.** That is *our* limit, not CDP's. When it truncates
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@glittering0717/ai-browser",
3
- "version": "2.5.2",
3
+ "version": "2.5.5",
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": {
@@ -89,10 +89,12 @@
89
89
  "verify:app": "node e2e/shipped_ws.cjs",
90
90
  "wrapper": "node e2e/wrapper_ws.cjs",
91
91
  "paint": "node e2e/paint_ws.cjs",
92
+ "shot": "node e2e/shot_ws.cjs",
92
93
  "layout": "node e2e/layout_ws.cjs",
93
94
  "flicker": "node e2e/flicker_ws.cjs",
94
95
  "download": "node e2e/download_ws.cjs",
95
96
  "multiagent": "node e2e/multiagent_ws.cjs",
97
+ "input_routing": "node e2e/input_routing_ws.cjs",
96
98
  "background": "node e2e/background_ws.cjs",
97
99
  "icon:check": "node scripts/check_icon.cjs",
98
100
  "icons": "env -u ELECTRON_RUN_AS_NODE node_modules/electron/dist/Electron.app/Contents/MacOS/Electron --no-sandbox --disable-gpu scripts/render_icon.cjs",
@@ -107,7 +109,7 @@
107
109
  },
108
110
  "devDependencies": {
109
111
  "@electron/packager": "^20.3.0",
110
- "electron-winstaller": "^5.4.4",
112
+ "electron-builder": "^26.18.0",
111
113
  "jsdom": "^29.1.1",
112
114
  "vitest": "^2.0.0"
113
115
  }
@@ -1,13 +1,25 @@
1
1
  'use strict';
2
- // scripts/build_installer.cjs — 用 electron-winstaller(Squirrel.Windows)把
3
- // 已打包好的便携目录 dist/AI Browser-win32-x64 打成**单文件安装器** Setup.exe。
2
+ // scripts/build_installer.cjs — 把已打包好的便携目录 dist/AI Browser-win32-x64
3
+ // 打成**单文件 Windows 安装器**(NSIS,electron-builder 的 win nsis target)。
4
4
  //
5
5
  // 前提:先 `npm run build:win` 产出 dist/AI Browser-win32-x64/。
6
6
  // 产出:dist/installer/AI-Browser-<version>-win32-x64-Setup.exe
7
- // 用法:node scripts/build_installer.cjs
7
+ // 用法:node scripts/build_installer.cjs [--silent]
8
8
  //
9
- // Squirrel 安装到 %LOCALAPPDATA%\<name>,并创建开始菜单/桌面快捷方式;不写 HKLM,
10
- // 无需管理员权限。noMsi: true → 只出 Setup.exe,不额外出 .msi。
9
+ // 为什么是 NSIS 而不是 Squirrel(2026-11-06 换的):
10
+ // Squirrel 装完**不会自己建快捷方式** —— 它把新装的 app 用 `--squirrel-install`
11
+ // 拉起来,指望 app 自己调 `Update.exe --createShortcut`(官方 README 里写的就是
12
+ // 这段)。而且就算调了,Squirrel 会把开始菜单项塞进 `Programs\<CompanyName>\`
13
+ // 子文件夹(CompanyName 取自 exe 的 rcedit 元数据),用户在开始菜单顶层搜不到。
14
+ // 实测日志(%LOCALAPPDATA%\AIBrowser\Squirrel-Shortcut.log):
15
+ // Creating shortcut for AI Browser.exe =>
16
+ // ...\Start Menu\Programs\Glittering\AI Browser.lnk
17
+ // NSIS 是 Windows 上 Electron 应用的标准解(VS Code / Slack / Discord 都是),
18
+ // 安装即建开始菜单(顶层)+ 桌面快捷方式,卸载项进「应用和功能」,全程按用户
19
+ // 安装、不需要管理员权限。
20
+ //
21
+ // 装到哪:%LOCALAPPDATA%\Programs\ai-browser\(perMachine: false)
22
+ // 用户数据仍旧在 ~/.ai-browser —— 卸载不碰它(deleteAppDataOnUninstall: false)。
11
23
 
12
24
  const fs = require('node:fs');
13
25
  const path = require('node:path');
@@ -27,40 +39,99 @@ function main() {
27
39
  fs.mkdirSync(OUT_DIR, { recursive: true });
28
40
 
29
41
  const icoPath = path.join(root, 'build', 'icon.ico');
42
+ if (!fs.existsSync(icoPath)) {
43
+ // 以前这里会静默退回 Electron 默认图标;装给别人用的包不该有默认图标。
44
+ console.error(`[installer] 缺少 ${icoPath}\n 先生成: node_modules/electron/dist/electron.exe scripts/make_win_icon.cjs`);
45
+ process.exit(2);
46
+ }
47
+
30
48
  const setupExe = `AI-Browser-${pkg.version}-win32-x64-Setup.exe`;
31
49
 
32
- const { createWindowsInstaller } = require('electron-winstaller');
50
+ // electron-builder 是 CJS 包,但加载会拉起 app-builder 二进制,放在函数里 require
51
+ // 才能让「参数检查失败」先于「依赖缺失」报出来。
52
+ const { build, Platform, Arch } = require('electron-builder');
33
53
 
34
- console.log(`[installer] ${pkg.version} — Squirrel Setup.exe`);
54
+ // electron-builder 有一条硬校验:electron 只能出现在 devDependencies。
55
+ // 而本项目必须把 electron 放在 dependencies —— npm 包靠它才能真正启动浏览器。
56
+ // 所以在 dist/ 下开一个临时「构建项目」,只给它一份满足校验的最小 package.json,
57
+ // 把产物目录用 prepackaged 指过去。真实 package.json 一个字节都不动。
58
+ const staging = path.join(root, 'dist', '.nsis-project');
59
+ fs.rmSync(staging, { recursive: true, force: true });
60
+ fs.mkdirSync(staging, { recursive: true });
61
+ fs.writeFileSync(path.join(staging, 'package.json'), JSON.stringify({
62
+ name: 'ai-browser',
63
+ version: pkg.version,
64
+ description: pkg.description,
65
+ author: 'Glittering',
66
+ license: pkg.license,
67
+ devDependencies: { electron: require('electron/package.json').version },
68
+ }, null, 2));
69
+
70
+ console.log(`[installer] ${pkg.version} — NSIS Setup.exe`);
35
71
  console.log(`[installer] appDirectory: ${APP_DIR}`);
36
72
  console.log(`[installer] outputDirectory: ${OUT_DIR}`);
37
73
 
38
- return createWindowsInstaller({
39
- appDirectory: APP_DIR,
40
- outputDirectory: OUT_DIR,
41
- authors: 'Glittering',
42
- exe: EXE_NAME,
43
- // name 用作 %LOCALAPPDATA%\ 下的安装目录与包标识,用无空格名更稳
44
- name: 'AIBrowser',
45
- title: 'AI Browser',
46
- description: 'AI-native browser — semantic-tree API for agents',
47
- version: pkg.version,
48
- setupExe,
49
- noMsi: true,
50
- // 有 build/icon.ico 就用作 Setup.exe 图标;没有则用默认
51
- setupIcon: fs.existsSync(icoPath) ? icoPath : undefined,
74
+ const config = {
75
+ appId: 'com.glittering.aibrowser',
76
+ productName: 'AI Browser',
77
+ copyright: `Copyright © ${new Date().getFullYear()} Glittering`,
78
+ // 只出安装器,不去猜发布通道(仓库里有 repository 字段,不写 null 会去探 GitHub)
79
+ publish: null,
80
+ directories: {
81
+ output: OUT_DIR,
82
+ buildResources: path.join(root, 'build'),
83
+ },
84
+ // 安装器不重新打包:直接吃 build:win 的产物,asar / 图标 / 元数据都不动
85
+ win: {
86
+ target: [{ target: 'nsis', arch: ['x64'] }],
87
+ icon: icoPath,
88
+ executableName: 'AI Browser',
89
+ artifactName: setupExe,
90
+ },
91
+ nsis: {
92
+ // 向导式(不是一键装),让用户能选盘符 / 看到装到哪
93
+ oneClick: false,
94
+ // 按当前用户安装,不弹 UAC
95
+ perMachine: false,
96
+ allowElevation: false,
97
+ allowToChangeInstallationDirectory: true,
98
+ // 这两条就是这次要的:装完自动有开始菜单 + 桌面快捷方式
99
+ createDesktopShortcut: true,
100
+ createStartMenuShortcut: true,
101
+ shortcutName: 'AI Browser',
102
+ // 开始菜单放在顶层,不套「Glittering」子文件夹(Squirrel 的老毛病)
103
+ menuCategory: false,
104
+ // 装完直接启动,第一次用的人不用去找图标
105
+ runAfterFinish: true,
106
+ // 卸载保留 ~/.ai-browser:里面的 profile / 登录态是用户的东西
107
+ deleteAppDataOnUninstall: false,
108
+ uninstallDisplayName: `AI Browser ${pkg.version}`,
109
+ installerIcon: icoPath,
110
+ uninstallerIcon: icoPath,
111
+ installerHeaderIcon: icoPath,
112
+ // 中文用户在中文系统上看到中文向导
113
+ multiLanguageInstaller: true,
114
+ installerLanguages: ['zh_CN', 'en_US'],
115
+ // 差分包只对自动更新有意义,单文件分发用不上
116
+ differentialPackage: false,
117
+ },
118
+ };
119
+
120
+ return build({
121
+ // 在临时构建项目里跑,只为了绕开上面那条 electron 依赖校验
122
+ projectDir: staging,
123
+ prepackaged: APP_DIR,
124
+ targets: Platform.WINDOWS.createTarget(['nsis'], Arch.x64),
125
+ config,
52
126
  }).then(() => {
53
127
  const out = path.join(OUT_DIR, setupExe);
54
- const ok = fs.existsSync(out);
55
- if (ok) {
56
- const mb = (fs.statSync(out).size / 1024 / 1024).toFixed(1);
57
- console.log(`[installer] 完成:${out}(${mb} MB)`);
58
- } else {
59
- // electron-winstaller 有时会把 setupExe 名字改成默认,扫一下产物
128
+ if (!fs.existsSync(out)) {
60
129
  const files = fs.readdirSync(OUT_DIR).filter((n) => /Setup\.exe$/i.test(n));
61
- console.log('[installer] 预期文件名未出现,目录内 Setup.exe:', files);
62
- if (!files.length) process.exit(1);
130
+ console.error('[installer] 预期文件名未出现,目录内 Setup.exe:', files);
131
+ process.exit(1);
63
132
  }
133
+ const mb = (fs.statSync(out).size / 1024 / 1024).toFixed(1);
134
+ console.log(`[installer] 完成:${out}(${mb} MB)`);
64
135
  return out;
65
136
  });
66
137
  }
@@ -9,9 +9,10 @@
9
9
  // 产出:dist/AI Browser-win32-x64/AI Browser.exe
10
10
  // 用法:node scripts/build_win.cjs
11
11
  //
12
- // 注意:Windows 版可执行文件的图标需要 .ico(项目只有 icon.icns / icon.svg),
13
- // 未提供时会使用 Electron 默认图标;要换图标请先把 build/icon.svg 转出
14
- // build/icon.ico,再在下面的 icon 选项里指向它。
12
+ // 注意:Windows 版可执行文件的图标需要 .ico。build/icon.ico 由
13
+ // `node_modules/electron/dist/electron.exe scripts/make_win_icon.cjs` 从
14
+ // build/icon-dock.png 生成(七个尺寸,PNG 载荷);缺它时会**静默**用 Electron
15
+ // 默认图标 —— 产物看起来像"没做完的 Electron 壳",而构建日志一个字都不会提。
15
16
 
16
17
  const fs = require('node:fs');
17
18
  const os = require('node:os');
@@ -31,11 +31,35 @@
31
31
  const { spawn } = require('node:child_process');
32
32
  const net = require('node:net');
33
33
  const path = require('node:path');
34
+ const fs = require('node:fs');
35
+ const os = require('node:os');
34
36
 
35
37
  const ROOT = path.resolve(__dirname, '..');
36
38
  const DEFAULT_PORT = 9223;
37
39
  const DEFAULT_TIMEOUT = 30000;
38
40
 
41
+ /**
42
+ * 直接 spawn 时把 Electron 的 stderr 重定向到 <userData>/logs/stderr.log。
43
+ * 理由同 scripts/start.cjs:V8 native fatal 走 C 层的 fd 2,`stdio:'ignore'`
44
+ * 会让崩溃原文彻底消失。走 LaunchServices(open)那条路拿不到 stdio,只能
45
+ * 依赖 macOS 的 .ips 崩溃报告 —— 但直接 spawn 是 macOS/开发机的主路径。
46
+ * 返回 fd(子进程持有副本后父进程负责关闭),失败返回 null(退回 ignore)。
47
+ */
48
+ function openStderrFd() {
49
+ try {
50
+ const base = process.env.AI_BROWSER_USER_DATA || path.join(os.homedir(), '.ai-browser');
51
+ const dir = path.join(base, 'logs');
52
+ fs.mkdirSync(dir, { recursive: true });
53
+ const p = path.join(dir, 'stderr.log');
54
+ try {
55
+ if (fs.statSync(p).size > 5 * 1024 * 1024) fs.renameSync(p, p + '.1');
56
+ } catch { /* 文件还不存在 */ }
57
+ return fs.openSync(p, 'a');
58
+ } catch {
59
+ return null;
60
+ }
61
+ }
62
+
39
63
  /** 端口上有没有人在听。超时 500ms —— 只探本地回环,不该慢。 */
40
64
  function checkPort(port, host = '127.0.0.1') {
41
65
  return new Promise((resolve) => {
@@ -133,8 +157,14 @@ async function ensureRunning(opts = {}) {
133
157
  delete env.ELECTRON_RUN_AS_NODE; // 坑 ①
134
158
  let earlyExit = null;
135
159
  let child = null;
160
+ const errFd = openStderrFd();
136
161
  try {
137
- child = spawn(bin, [ROOT], { cwd: ROOT, detached: true, stdio: 'ignore', env }); // 坑 ②
162
+ child = spawn(bin, [ROOT], {
163
+ cwd: ROOT, detached: true,
164
+ stdio: errFd ? ['ignore', 'ignore', errFd] : 'ignore', // 坑 ②:stderr 落盘
165
+ env,
166
+ });
167
+ if (errFd) { try { fs.closeSync(errFd); } catch {} } // 子进程已持有副本
138
168
  child.unref();
139
169
  child.on('exit', (code, signal) => { earlyExit = { code, signal }; });
140
170
  child.on('error', (e) => { earlyExit = { error: e.message }; });
@@ -0,0 +1,73 @@
1
+ #!/usr/bin/env node
2
+ // scripts/make_win_icon.cjs — build/icon-dock.png(1024 母版)→ build/icon.ico(多尺寸)。
3
+ //
4
+ // 为什么需要它:Windows 的 exe / Setup.exe 图标只吃 .ico,而本项目只提交了 macOS 的
5
+ // icon.icns。缺 .ico 时 build_win / build_installer 会**静默**用 Electron 默认图标
6
+ // (两个脚本都是 `fs.existsSync(icoPath) ? icoPath : undefined`),产物看起来像
7
+ // "一个没做完的 Electron 壳",而构建日志一个字都不会提。
8
+ //
9
+ // 为什么不用 ImageMagick / sharp:本机都没有。项目本来就带着一整个 Chromium,
10
+ // 用 Electron 的 nativeImage 缩放零新增依赖,和 render_icon.cjs 的思路一致。
11
+ //
12
+ // 用法(要 Electron,不是 node):
13
+ // node_modules/electron/dist/electron.exe scripts/make_win_icon.cjs
14
+ // 产物:build/icon.ico(16/24/32/48/64/128/256 七个尺寸,PNG 压缩载荷)
15
+ 'use strict';
16
+
17
+ const fs = require('node:fs');
18
+ const path = require('node:path');
19
+ const { nativeImage, app } = require('electron');
20
+
21
+ const ROOT = path.resolve(__dirname, '..');
22
+ const SRC = path.join(ROOT, 'build', 'icon-dock.png');
23
+ const OUT = path.join(ROOT, 'build', 'icon.ico');
24
+ const SIZES = [16, 24, 32, 48, 64, 128, 256];
25
+
26
+ app.whenReady().then(() => {
27
+ if (!fs.existsSync(SRC)) {
28
+ console.error('[ico] 找不到母版:' + SRC);
29
+ app.exit(2);
30
+ return;
31
+ }
32
+ const base = nativeImage.createFromPath(SRC);
33
+ const { width, height } = base.getSize();
34
+ if (!width || !height) {
35
+ console.error('[ico] 母版读不出来:' + SRC);
36
+ app.exit(2);
37
+ return;
38
+ }
39
+ console.log(`[ico] 母版 ${width}x${height} → ${SIZES.join('/')}`);
40
+
41
+ // 每个尺寸单独存 PNG(ICO 允许 PNG 载荷,Vista 起是标准做法,体积也最小)。
42
+ const images = SIZES.map((size) => {
43
+ const buf = base.resize({ width: size, height: size, quality: 'best' }).toPNG();
44
+ console.log(`[ico] ${size}x${size} ${buf.length}B`);
45
+ return { size, buf };
46
+ });
47
+
48
+ // ICONDIR(6) + ICONDIRENTRY*n(16) + 各个 PNG
49
+ const header = Buffer.alloc(6 + 16 * images.length);
50
+ header.writeUInt16LE(0, 0); // reserved
51
+ header.writeUInt16LE(1, 2); // type = 1 (icon)
52
+ header.writeUInt16LE(images.length, 4); // count
53
+ let offset = header.length;
54
+ images.forEach((img, i) => {
55
+ const p = 6 + 16 * i;
56
+ header.writeUInt8(img.size >= 256 ? 0 : img.size, p); // 0 表示 256
57
+ header.writeUInt8(img.size >= 256 ? 0 : img.size, p + 1);
58
+ header.writeUInt8(0, p + 2); // palette
59
+ header.writeUInt8(0, p + 3); // reserved
60
+ header.writeUInt16LE(1, p + 4); // color planes
61
+ header.writeUInt16LE(32, p + 6); // bits per pixel
62
+ header.writeUInt32LE(img.buf.length, p + 8);
63
+ header.writeUInt32LE(offset, p + 12);
64
+ offset += img.buf.length;
65
+ });
66
+
67
+ fs.writeFileSync(OUT, Buffer.concat([header, ...images.map((i) => i.buf)]));
68
+ console.log('[ico] 写入 ' + OUT + ' (' + fs.statSync(OUT).size + 'B)');
69
+ app.exit(0);
70
+ }).catch((e) => {
71
+ console.error('[ico] 失败:' + (e && e.message));
72
+ app.exit(1);
73
+ });
@@ -112,8 +112,17 @@ rewrite('src/shared/version.js', (s) => s.replace(`VERSION = '${from}'`, `VERSIO
112
112
  // 但任何人 `npm install` 一次就会把它刷成新值 —— 于是工作区变脏、下一次发版的
113
113
  // 「前置检查」直接卡住(2026-10-25 就在这上面卡过一轮)。锁文件的两个 version
114
114
  // 都替换;少了任何一处,下次 install 又会漂回去。
115
+ //
116
+ // ⚠️ 必须**按结构改**,不能全局替换 `"version": "<from>"`(2026-11-06 踩过):
117
+ // 依赖里恰好有同版本号的包(当时是 @bramus/specificity 2.5.2、@noble/hashes 2.5.2),
118
+ // 全局替换会把它们的 version 改成新版本,而 resolved/integrity 还停在旧包上 ——
119
+ // lockfile 从此自相矛盾,且 `npm ci` 会失败。
115
120
  try {
116
- rewrite('package-lock.json', (s) => s.split(`"version": "${from}"`).join(`"version": "${to}"`));
121
+ const lockPath = path.join(ROOT, 'package-lock.json');
122
+ const lock = JSON.parse(fs.readFileSync(lockPath, 'utf8'));
123
+ lock.version = to;
124
+ if (lock.packages && lock.packages['']) lock.packages[''].version = to;
125
+ fs.writeFileSync(lockPath, JSON.stringify(lock, null, 2) + '\n');
117
126
  } catch (e) {
118
127
  warn('package-lock.json 版本号未同步(可能本来就漂着):' + String(e.message).split('\n')[0]);
119
128
  }