@glittering0717/ai-browser 2.3.0 → 2.4.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.
@@ -43,6 +43,7 @@ import { MediaInline } from './media_inline.js';
43
43
  // 切到人眼前"的策略。见 shared/tab_route.cjs 顶部(多 agent 并用的三条事故)。
44
44
  import tabRoute, { shouldShowChildTab } from '../shared/tab_route.cjs';
45
45
  import tabGroup from '../shared/tab_group.cjs';
46
+ import placeholder from '../shared/placeholder.cjs';
46
47
  import { probeCapabilities } from './capability_probe.js';
47
48
  import valueContract from '../shared/value_contract.cjs';
48
49
  // 输入成功与否的判定口径(纯函数,独立模块便于单测)。详见文件内注释:
@@ -424,7 +425,26 @@ class PageManager {
424
425
  if (!token) return;
425
426
  const sourceTabId = this._tabIdForContents(_event.sender);
426
427
  const url = typeof p.url === 'string' ? p.url : '';
427
- const childId = this.newTab(url && url !== 'about:blank' ? url : null);
428
+ // Bug 1 修复:setWindowOpenHandler 那条路(v2.3.0 已补 group + show)之后,
429
+ // window.open 的真正生效路径是这条 IPC(垫片主 world -> bridge -> IPC),
430
+ // 这边此前漏掉 opts。现在两条路必须行为一致:
431
+ // - group:派生 tab 跟 opening 者走(agent 后台页弹窗仍进 agent 组,而不是人组)
432
+ // - show:opener 是后台页时不显示(登录/预览/下载弹窗不抢视野)
433
+ const parentGroup = sourceTabId !== null ? this.groupOfTab(sourceTabId) : tabGroup.HUMAN_GROUP;
434
+ const show = shouldShowChildTab({ openerIsVisible: sourceTabId !== null && sourceTabId === this.activeTab });
435
+ // 弹窗把组撑满时不能拒绝(站点的脚本在等这个窗口),只能牺牲一页:
436
+ // 最久没用、不在人眼前、没有挂着对话框的那一页。
437
+ if (!this.canOpenInGroup(parentGroup).allowed) {
438
+ const victim = this.pickEvictableInGroup(parentGroup, sourceTabId);
439
+ if (victim !== null) {
440
+ const deadUrl = (this._getView(victim) || {}).webContents
441
+ ? this._getView(victim).webContents.getURL() : '';
442
+ this.evictions.push({ tab: victim, url: deadUrl, at: Date.now(), reason: 'group-full' });
443
+ if (this.evictions.length > 20) this.evictions.shift();
444
+ this.closeTab(victim);
445
+ }
446
+ }
447
+ const childId = this.newTab(url && url !== 'about:blank' ? url : null, { show, group: parentGroup });
428
448
  this._windowOpenTokens.set(token, { tabId: childId, sourceTabId });
429
449
  // 与 setWindowOpenHandler 路径共用 _openedTabs:executeAction 的
430
450
  // auto-follow(点击后 Agent 视角跟到新 tab)对两种打开方式一致。
@@ -878,15 +898,18 @@ class PageManager {
878
898
  showDownloadResult(tabId, rec) {
879
899
  const view = this.tabs.get(tabId);
880
900
  if (!view || view.webContents.isDestroyed()) return false;
881
- const q = new URLSearchParams();
882
- q.set('id', rec.id || '');
883
- q.set('name', rec.filename || 'download');
884
- q.set('path', rec.path || '');
885
- q.set('mime', rec.mime || '');
886
- q.set('size', String(rec.total_bytes || 0));
887
- q.set('url', rec.url || '');
888
901
  const pagePath = path.join(__dirname, '../renderer/download.html');
889
- const target = 'file://' + pagePath + '?' + q.toString();
902
+ // 一律走 shared/placeholder.cjs 的构造器:手拼 'file://' + path 在打包后
903
+ // (/Applications/AI Browser.app 含空格)加载不出来。
904
+ const target = placeholder.fileUrlWithQuery(pagePath, {
905
+ id: rec.id || '',
906
+ name: rec.filename || 'download',
907
+ path: rec.path || '',
908
+ mime: rec.mime || '',
909
+ size: String(rec.total_bytes || 0),
910
+ url: rec.url || '',
911
+ });
912
+ if (!target) return false;
890
913
  view.webContents.loadURL(target).catch(() => {});
891
914
  return true;
892
915
  }
@@ -1827,6 +1850,28 @@ class PageManager {
1827
1850
  // 动作前先拍一张。为什么拍在 withDeadline 外面:deadline 只应该盖住动作
1828
1851
  // 本身,探针有它自己的 1.5s 上限,混进同一个预算会让"动作超时"和
1829
1852
  // "探针慢"两种完全不同的故障共用一个错误码。
1853
+ // canvas 页要先量一次"空闲时画布在不在动、动的时候内容一样不一样"。
1854
+ //
1855
+ // 采**三个**样本(仍在 IDLE_WINDOW_MS 附近,不是三倍等待),因为只看指纹差
1856
+ // 分不清两件事:页面在画**同一个**画面(稳定的动画循环),还是在画**不同**的
1857
+ // 画面(时钟指针、协作光标、直播)。前者用完整帧哈希照样能判"变了没有",
1858
+ // 后者只能老实说"不可判"。判据在 page_probe.canvasVerdict 里,输入就是这三个样本。
1859
+ //
1860
+ // 代价只在有 canvas 指纹的页面上发生(普通页面一次都不多等):这一层存在的
1861
+ // 意义是**不把"点了没反应"变成永远为真**——那是 page_probe 的原始动机。
1862
+ let idleSamples = [];
1863
+ if (pageProbe.shouldProbe(action)) {
1864
+ const first = await this._pageProbe(tid, action);
1865
+ if (first && typeof first.c === 'string') {
1866
+ idleSamples = [first];
1867
+ const gap = Math.max(20, Math.round(pageProbe.IDLE_WINDOW_MS / 3));
1868
+ for (let i = 0; i < 2; i++) {
1869
+ await new Promise((r) => setTimeout(r, gap));
1870
+ const one = await this._pageProbe(tid, action);
1871
+ if (one) idleSamples.push(one);
1872
+ }
1873
+ }
1874
+ }
1830
1875
  const probeBefore = await this._pageProbe(tid, action);
1831
1876
  try {
1832
1877
  const res = await withDeadline(
@@ -1841,7 +1886,17 @@ class PageManager {
1841
1886
  if (probeBefore) {
1842
1887
  await new Promise((r) => setTimeout(r, pageProbe.settleMs(action)));
1843
1888
  const probeAfter = await this._pageProbe(tid, action);
1844
- out = pageProbe.applyProbe(out, probeBefore, probeAfter, action);
1889
+ // 动作之后再采一次。画面在动作结束后还在自己变 → 这一页会自漂,画布的
1890
+ // 变化不能归因给我的动作。为什么必须补这一刀:动作前的空闲窗口可能正好
1891
+ // 落在页面被后台节流冻住的时刻(Chromium 对不可见标签页把 rAF 降到 ~1fps),
1892
+ // 那时"空闲期没动"不代表"它不会动",而动作本身会唤醒页面。
1893
+ // 只有画布页付这 150ms;其它页面的 probeAfter.c 是 null,直接跳过。
1894
+ let postBaseline = null;
1895
+ if (probeAfter && typeof probeAfter.c === 'string') {
1896
+ await new Promise((r) => setTimeout(r, pageProbe.IDLE_WINDOW_MS));
1897
+ postBaseline = await this._pageProbe(tid, action);
1898
+ }
1899
+ out = pageProbe.applyProbe(out, probeBefore, probeAfter, action, { idleSamples, postBaseline });
1845
1900
  }
1846
1901
  const dlg = this._dialogSince(tid, startedAt);
1847
1902
  if (dlg) out = { ...out, dialog: dlg };
@@ -3778,13 +3833,10 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
3778
3833
  // 等它终于 resolve,下面这行 loadURL(启动页) 又把页面盖回去 ——
3779
3834
  // 表现是"打开的是目标页,下一刻自己跳回首页",读到的树也成了首页的。
3780
3835
  // 判据只看一句:现在还在占位页上吗?不在就什么都不做。
3781
- // 判据要宽松:空 / about:blank 都还算"还没开始",只有**明确导航
3782
- // 到别处**(另一个 http/file 地址)才放弃 —— 收紧成"必须等于占位页"
3783
- // 会在占位页刚发起、getURL() 还返回 about:blank 的那一瞬误判,
3784
- // 结果是新标签页永远停在占位页(wrapper 套件当场 red)。
3785
- const cur = wc0.getURL();
3786
- const stillMine = !cur || cur === 'about:blank' || cur === placeholderUrl;
3787
- if (!stillMine) return;
3836
+ // 注意判据在 shared/placeholder.cjs 里(按文件名,不按字符串相等)——
3837
+ // 这里踩过两次:收紧成"必须等于占位页"会让新标签页永远卡住,
3838
+ // 而字符串相等在打包路径含空格时恒为 false。
3839
+ if (!placeholder.isPlaceholderUrl(wc0.getURL())) return;
3788
3840
  // 让"正在加载"可被观测:白屏最贵的地方不是慢,是慢得无法和
3789
3841
  // "开错了"区分(见 listTabs 的 state 字段)。
3790
3842
  this._tabNavState.set(tabId, 'loading');
@@ -3897,13 +3949,14 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
3897
3949
  pagePath = path.join(__dirname, '../renderer/error_page.html');
3898
3950
  } catch (_) { return; }
3899
3951
 
3900
- const q = new URLSearchParams({
3952
+ const target = placeholder.fileUrlWithQuery(pagePath, {
3901
3953
  url: String(validatedURL || ''),
3902
3954
  code: String(errorCode),
3903
3955
  text: String(errorDescription || ''),
3904
3956
  });
3905
3957
  try {
3906
- view.webContents.loadURL('file://' + pagePath + '?' + q.toString());
3958
+ if (!target) throw new Error('bad page path');
3959
+ view.webContents.loadURL(target);
3907
3960
  } catch (e) {
3908
3961
  console.error('[page_manager] error page load failed:', e.message);
3909
3962
  this._failureGuard.delete(tabId);
@@ -5346,14 +5399,11 @@ return {ok:true,name:file.name,size:file.size,via:via,host_sel:hostSel,clicked:c
5346
5399
  // "正在打开 <url>"),无目标地址时保持 about:blank(window.open("") 的
5347
5400
  // 占位 tab 要停在这里等站点赋 location,不能显示成"正在打开")。
5348
5401
  _loadingPlaceholderUrl(targetUrl) {
5349
- if (!targetUrl) return 'about:blank';
5350
- try {
5351
- const pagePath = path.join(__dirname, '../renderer/loading.html');
5352
- const q = new URLSearchParams({ url: String(targetUrl) });
5353
- return 'file://' + pagePath + '?' + q.toString();
5354
- } catch (_e) {
5355
- return 'about:blank';
5356
- }
5402
+ // 用 pathToFileURL 而不是 'file://' + path:打包后的路径含空格
5403
+ // (/Applications/AI Browser.app/...),手拼出来的 URL 与 Chromium 报回来的
5404
+ // 一个是字面空格、一个是 %20,任何"字符串相等"的判据都会失效。详见
5405
+ // shared/placeholder.cjs 顶部(v2.3.0 的事故)。
5406
+ return placeholder.placeholderUrlFor(path.join(__dirname, '../renderer/loading.html'), targetUrl);
5357
5407
  }
5358
5408
 
5359
5409
  _ensureWindowOpenShim(tabId, view) {
@@ -263,6 +263,20 @@ export function safeByteLength(value) {
263
263
  * Reading is strictly read-only: `loadGraphData` is a LOADER and is never
264
264
  * called, and a throwing `serialize()` or a circular `_nodes` is caught and
265
265
  * simply yields no fingerprint.
266
+ *
267
+ * 5. THE CANVAS DRAW SEQUENCE IS FINGERPRINTED TOO (property 4 only covers
268
+ * apps that HANG A MODEL OFF WINDOW).
269
+ * Measured 2026-10-29 on Excalidraw: a whiteboard whose entire document is
270
+ * canvas-drawn and whose window exposes no model at all. Dragging out a
271
+ * rectangle changed zero DOM bytes, so a model-less canvas app fell straight
272
+ * through every signal above and `ui.diff` answered "unchanged" to a write
273
+ * that visibly happened. The canvas hook already records every draw call, so
274
+ * it also maintains a per-frame sequence hash (see canvas_hook_source.js
275
+ * `push`) and exposes it as `window.__aiCanvasFp`. Reading it costs ~110
276
+ * chars here and gives the diff its only view into a model-less canvas.
277
+ * `on:0` / absent means the hook is not installed (it is only installed
278
+ * after first load, and can be switched off) — absent is reported as
279
+ * "no canvas signal", never as "canvas unchanged".
266
280
  */
267
281
  export const DEFAULT_SNAPSHOT_JS = `(function(){
268
282
  try {
@@ -364,6 +378,7 @@ export const DEFAULT_SNAPSHOT_JS = `(function(){
364
378
  out.model = { global: p.k, kind: p.f.kind, count: p.f.count, fp: p.f.fp };
365
379
  }
366
380
  } catch (_) {}
381
+ try { var cfp = window.__aiCanvasFp; if (typeof cfp === 'function') { var cv = cfp(); if (cv) out.canvas = cv.fp; } } catch (_) {}
367
382
  return out;
368
383
  } catch (e) {
369
384
  return { __error: String(e && e.message || e) };
@@ -590,6 +590,11 @@ export function startWSServer(pageManager, port = config.wsPort, onQuit = null)
590
590
  // 窗口状态:后台运行时要能问到"现在到底是不是隐藏的",否则
591
591
  // "我没看到窗口却以为它在显示"这类问题只能靠猜。
592
592
  ...(pageManager.windowState ? { window: pageManager.windowState() } : {}),
593
+ // 应用图标:source 表明这次 Dock 图标来自 bundle 的 icns 还是运行时
594
+ // dock.setIcon(源码启动)。content_ratio 是实际设进去那张图的内容
595
+ // 占比 —— macOS 的图标网格约 0.867;两条路径不一致就会"一会大一会
596
+ // 小",所以这里要能直接判定,而不是靠肉眼比。
597
+ ...(pageManager.appIcon ? { icon: pageManager.appIcon } : {}),
593
598
  // 这个连接的工作标签页(多 agent 时用来核对自己绑到了哪一页)
594
599
  ...(pageManager.sessionTabOf ? { session_tab: pageManager.sessionTabOf(sessionId) } : {}),
595
600
  },
@@ -40,6 +40,16 @@
40
40
  // 最该抓的场景(点了没反应)全丢掉。实测于 2026-10-22 的 fixture 回归。
41
41
  // n = DOM 元素总数(粗粒度结构变化:弹窗、列表插入)
42
42
  // u = location.href(SPA 路由跳转)
43
+ // c = canvas 帧指纹 "fp:n:frames",来自页面里的 canvas hook(canvas_hook_source.js
44
+ // 暴露的 window.__aiCanvasFp)。null = 这个页面没装 hook / hook 关着。
45
+ //
46
+ // 为什么必须加 c:上面四个信号全部只看 DOM,而**纯 canvas 应用的写入在 DOM 上
47
+ // 常常是零字节**。实测(2026-10-29,Excalidraw):在白板上拖出一个矩形,DOM 节点
48
+ // 数与文本哈希都不变(画布是 <canvas>,图元不是 DOM 节点),于是 page_changed
49
+ // 只能靠"选中图元后右侧属性面板出现"这种副作用偶然为真;一旦动作不产生面板
50
+ // 变化(移动已存在的图元、在画布空白处涂色、连续调参),就会报 false,并附上一句
51
+ // "payload 很可能没落地" —— 把一次成功的写入说成失败,比不报更糟。
52
+ // 同一个指纹也进了 DEFAULT_SNAPSHOT_JS,所以 ui.diff 对画布写入同样能报 changed。
43
53
  export const PAGE_PROBE_JS = `(function(){
44
54
  try{
45
55
  var b=document.body||document.documentElement;
@@ -59,7 +69,12 @@ export const PAGE_PROBE_JS = `(function(){
59
69
  }catch(_e){}
60
70
  var n=0;
61
71
  try{ n=document.getElementsByTagName('*').length; }catch(_e){}
62
- return {t:t.length,h:(h>>>0).toString(36),d:(dv||'').replace(/\\s+/g,'').length,n:n,u:String(location.href)};
72
+ var cf=null,cn=null;
73
+ var cl=null;
74
+ try{ var fpFn=window.__aiCanvasFp; if(typeof fpFn==='function'){var v=fpFn(); if(v){cf=String(v.fp);cn=v.n;cl=(v.last==null?null:v.last);}} }catch(_e){}
75
+ var vis='';
76
+ try{ vis=String(document.visibilityState||''); }catch(_e){}
77
+ return {t:t.length,h:(h>>>0).toString(36),d:(dv||'').replace(/\\s+/g,'').length,n:n,u:String(location.href),c:cf,k:cn,v:vis,l:cl};
63
78
  }catch(e){ return {__err:String((e&&e.message)||e)}; }
64
79
  })()`;
65
80
 
@@ -101,24 +116,161 @@ const HINT_CLICK =
101
116
  + 'expected inside an out-of-process iframe, this probe cannot see it — verify with '
102
117
  + 'get_tree/screenshot instead.';
103
118
 
119
+ // canvas 侧的证据分两种,措辞必须分开 —— 它们的下一步动作完全相反。
120
+ //
121
+ // 可归因(动作前 150ms 空闲窗口里指纹没动过):这就是 canvas 应用上"写入成功"
122
+ // 的**常态**外观,图元不是 DOM 节点,画一笔只会让 <canvas> 重绘一次。
123
+ // 而调用方最容易犯的错恰恰是"为了确认再画一次",于是画布上多了一个形状。
124
+ const HINT_CANVAS =
125
+ 'page_changed=true by canvas only: the DOM is byte-identical and the canvas draw sequence '
126
+ + 'changed — the normal shape of a successful write on a canvas surface (shapes are not DOM '
127
+ + 'nodes). Do NOT redo the action to "make sure": a second drag/paste duplicates the result. '
128
+ + 'Read content back via the route in ui.capabilities, not ui.canvas_read — full-frame '
129
+ + 'renderers (Excalidraw-class) log no fillText, so an empty texts[] does NOT mean empty canvas.';
130
+
131
+ // 不可归因(空闲窗口里指纹自己在动):这一页会自己重绘(时钟、光标、动画、直播)。
132
+ // 此时"画布变了"什么都证明不了。把它算进 page_changed 尤其危险 —— 那会把
133
+ // page_probe 最初要抓的那件事(点了没反应)重新变回**永远为真**。
134
+ const HINT_CANVAS_NOISY =
135
+ 'canvas signal unusable on this page: the canvas repainted during a 150ms idle window before '
136
+ + 'the action, so a canvas change cannot be attributed to your action. page_changed reflects '
137
+ + 'the DOM only here. If you need certainty, call ui.snapshot twice with NO action in between '
138
+ + 'and compare snapshot.canvas yourself — if it moves on its own, trust the app\'s own state '
139
+ + 'route (ui.capabilities) instead of the canvas.';
140
+
141
+ // **判不了**(证据不足):页面可能被后台节流冻住、也可能是拿不到完整帧的增量渲染器。
142
+ // 此时"画布没变"这句话不能说 —— 我们并没有真的看见它没变。这是最容易被误读成
143
+ // "什么都没发生"的一种状态,必须明说"这个信号在当页不可用"。
144
+ const HINT_CANVAS_UNKNOWN =
145
+ 'canvas signal unusable on this page: not enough evidence to tell whether the canvas changed '
146
+ + '(the page was hidden/throttled during the idle check, or it repaints without whole frames). '
147
+ + 'page_changed reflects the DOM only here. If you need certainty, call ui.snapshot twice with '
148
+ + 'NO action in between and compare snapshot.canvas yourself; if it moves on its own, trust the '
149
+ + 'app state route in ui.capabilities instead of the canvas.';
150
+
151
+ // 动作前用于标定"这一页画布会不会自己动"的空闲窗口。150ms 覆盖 60fps 下 9 帧,
152
+ // 足够看出持续重绘;再长就会让 canvas 页上每次动作都多等一截。只在页面确实有
153
+ // canvas 指纹时才等(见 page_manager.executeAction)。
154
+ export const IDLE_WINDOW_MS = 150;
155
+
156
+ /**
157
+ * 这一页的画布处于哪种状态 —— 决定了"画布变了"能不能当成证据。
158
+ *
159
+ * 四种,各有各的判据(**不要**拿一个量去回答两个问题):
160
+ *
161
+ * static 空闲窗口里一次都没画过。用**前缀哈希 fp** 判变化:静态页只画一帧,
162
+ * 下一帧边界永远不来,所以只有 fp 是即时的。
163
+ * repeat 在画,但每次画的**完整帧**一样(稳定的动画循环 / 同内容重绘)。
164
+ * 用**完整帧哈希 last** 判变化:它与采样相位无关,因此这一页终于可判了。
165
+ * drift 在画,且完整帧每帧都不同(时钟指针、协作光标、视频)。
166
+ * 此时"画布变了"无法归因给动作 —— 只能回答"不可判"。
167
+ * unknown 证据不足:空闲窗口一个样本都没有、拿不到完整帧(增量渲染器)、
168
+ * 或页面在后台被节流(那时"没画"不等于"不会画")。
169
+ *
170
+ * 为什么不能用"空闲期采到几个不同的指纹"来区分 repeat 与 drift:稳定重绘的页面
171
+ * 也会因为采样落在帧内不同位置而给出几个不同的**前缀**哈希。实测踩过这个坑,
172
+ * 于是改成"数帧而不是数相位"——完整帧哈希只有内容变了才会变。
173
+ */
174
+ function canvasVerdict(before, after, opts) {
175
+ const num = (v) => Number(v) || 0;
176
+ const samples = Array.isArray(opts.idleSamples)
177
+ ? opts.idleSamples.filter((x) => x && typeof x.c === 'string')
178
+ : [];
179
+ // 没做标定(调用方没给样本):退回"只看指纹差",与加这套判据之前完全一致。
180
+ // 生产路径上不会走到这里 —— page_manager 见到 canvas 指纹就会采三份。
181
+ if (!samples.length) return { mode: 'static', active: false };
182
+
183
+ const idleDrew = num(before.k) - num(samples[0].k);
184
+ // 指纹在空闲窗口里变过 = 这一页**确实画过**(c 只在真有绘制时变)。这与计数器
185
+ // 是两条独立证据:慢速动画(1fps)可能一次计数差都攒不够,但指纹已经变了。
186
+ //
187
+ // 端点必须含 before:窗口是从**第一个**样本到**动作前那一刻**,只比样本之间会漏掉
188
+ // 最后一段(实测只有一个样本时这条恒为 false,自漂页当场被当成静止页)。
189
+ const cbNow = typeof before.c === 'string' ? before.c : null;
190
+ const idleVaried = samples.some((x) => x.c !== samples[0].c)
191
+ || (cbNow !== null && samples[samples.length - 1].c !== cbNow);
192
+ const post = opts.postBaseline;
193
+ const postBusy = !!(post && typeof post.c === 'string'
194
+ && (post.c !== after.c || num(post.k) > num(after.k)));
195
+ const active = idleDrew >= 2 || idleVaried || postBusy;
196
+
197
+ if (!active) {
198
+ // 空闲期真的没画。但后台标签页被 Chromium 把 rAF 降到约 1fps 甚至暂停,
199
+ // 那时"没画"不是"不会画"的证据 —— 隐藏页上只能给 unknown。
200
+ const m2 = String(before.v || '') === 'visible' ? 'static' : 'unknown';
201
+ return { mode: m2, active: false };
202
+ }
203
+ // 在画。能不能判,取决于拿不拿得到**完整帧**(与采样相位无关的那个值)。
204
+ const lasts = new Set();
205
+ for (const s2 of samples) if (s2.l !== null && s2.l !== undefined) lasts.add(String(s2.l));
206
+ if (lasts.size > 1) return { mode: 'drift', active: true }; // 每帧内容都不同 → 不可归因
207
+ if (lasts.size === 1 && samples.length >= 2) return { mode: 'repeat', active: true }; // 每帧一样 → 可判
208
+ return { mode: 'unknown', active: true }; // 在画但没有完整帧(增量渲染器)
209
+ }
210
+
104
211
  /**
105
212
  * 比较前后两次探针。纯函数,无 Electron 依赖,可直接单测。
106
- * @returns {{changed: boolean|null, delta: object|null}}
107
- * changed=null 表示数据不可比(某次探针失败),调用方应忽略而不是当成 false。
213
+ *
214
+ * @param {object[]} opts.idleSamples 动作之前连续采的几次(≥2 才能判 repeat)。
215
+ * @param {object} opts.postBaseline 动作之后再隔 IDLE_WINDOW_MS 采的一次。
216
+ * @returns {{changed, delta, domChanged, canvasChanged, canvasIdle, canvasRepeat, mode, hasCanvas}}
217
+ * canvasChanged: true=变了 / false=没变 / null=不可判(drift、unknown)
218
+ * canvasIdle: true=静止 / false=自己在画 / null=不可判
219
+ * canvasRepeat: 这一页在重绘但每帧内容相同(此时 canvasChanged 仍然可信)
220
+ * hasCanvas: 两次采样里有没有指纹(决定回执要不要带这四个字段)
108
221
  */
109
- export function diffProbe(before, after) {
222
+ export function diffProbe(before, after, opts = {}) {
110
223
  const ok = (p) => p && typeof p === 'object' && !p.__err && typeof p.h === 'string';
111
- if (!ok(before) || !ok(after)) return { changed: null, delta: null };
224
+ const empty = {
225
+ changed: null, delta: null, domChanged: false,
226
+ canvasChanged: null, canvasIdle: null, canvasRepeat: false, mode: 'unknown', hasCanvas: false,
227
+ };
228
+ if (!ok(before) || !ok(after)) return empty;
229
+
112
230
  const delta = {
113
231
  text_chars: (Number(after.t) || 0) - (Number(before.t) || 0),
114
232
  dom_nodes: (Number(after.n) || 0) - (Number(before.n) || 0),
115
233
  focused_chars: (Number(after.d) || 0) - (Number(before.d) || 0),
116
234
  };
117
- const changed = before.h !== after.h
235
+ const domChanged = before.h !== after.h
118
236
  || (Number(before.n) || 0) !== (Number(after.n) || 0)
119
237
  || (Number(before.d) || 0) !== (Number(after.d) || 0)
120
238
  || before.u !== after.u;
121
- return { changed, delta };
239
+
240
+ // 只比**帧指纹本身**,绝不比它周围的计数器。
241
+ //
242
+ // 这里踩过一次,代价很大:接入时把探针字段写成 `fp:n:frames` 的拼接串,而 n 与
243
+ // frames 是单调递增的计数器 —— 于是"内容一模一样地重绘了一遍"(时钟、光标、
244
+ // ECharts 动画区间、canvas 视频)也会让字符串变化,page_changed 变成**永远为真**,
245
+ // 恰好把 page_probe 存在的意义(抓"点了没反应")反过来废掉。
246
+ // 教训:**单测证明了 A,产品用的是 A 的包装 B** —— 两边各自都"对",合起来是错的。
247
+ const cb = typeof before.c === 'string' ? before.c : null;
248
+ const ca = typeof after.c === 'string' ? after.c : null;
249
+ const hasCanvas = !!(cb && ca);
250
+
251
+ const verdict = hasCanvas ? canvasVerdict(before, after, opts) : { mode: 'unknown', active: false };
252
+ const mode = verdict.mode;
253
+ let canvasChanged = null;
254
+ if (hasCanvas) {
255
+ if (mode === 'static') {
256
+ canvasChanged = cb !== ca;
257
+ } else if (mode === 'repeat') {
258
+ const lb = before.l == null ? null : String(before.l);
259
+ const la = after.l == null ? null : String(after.l);
260
+ canvasChanged = (lb !== null && la !== null) ? lb !== la : null;
261
+ }
262
+ // drift / unknown:变化**不可归因**,给 null 而不是 true —— 一个"可能是我干的"
263
+ // 结论比"我不知道"更容易被误用。
264
+ }
265
+ // canvas_idle: true=静止 / false=自己在画 / null=判不了。'unknown' 既可能是
266
+ // "在画但拿不到完整帧",也可能是"根本没证据"(隐藏页),所以下面按 active 给值 ——
267
+ // 让一个 50% 把握的结论长得像 100% 把握的结论,是这类字段最常见的坏法。
268
+ const canvasIdle = mode === 'static' ? true : (verdict.active ? false : null);
269
+ const canvasRepeat = mode === 'repeat';
270
+ return {
271
+ changed: domChanged || canvasChanged === true,
272
+ delta, domChanged, canvasChanged, canvasIdle, canvasRepeat, mode, hasCanvas,
273
+ };
122
274
  }
123
275
 
124
276
  /**
@@ -126,24 +278,41 @@ export function diffProbe(before, after) {
126
278
  *
127
279
  * 只在 changed === false 时附加 page_delta 和 effect_hint:
128
280
  * 正常路径(changed:true)不多说一个字,避免每步回执都多两行噪音。
281
+ * 例外是"仅 canvas 变化"(成功写入的样子,调用方看不出落点)与"信号不可用"
282
+ * (必须说清不是"没变化",而是"这里判不了")。
129
283
  */
130
- export function applyProbe(res, before, after, action) {
284
+ export function applyProbe(res, before, after, action, opts = {}) {
131
285
  if (!res || typeof res !== 'object') return res;
132
- const d = diffProbe(before, after);
286
+ const d = diffProbe(before, after, opts);
133
287
  if (d.changed === null) return res;
134
288
  const out = { ...res, page_changed: d.changed };
135
- if (d.changed) return out;
289
+
290
+ // canvas 字段**只要页面确实有指纹**就发,哪怕结论是"不可判"。曾经只在 true 时写,
291
+ // 于是"没变""不可判""没有画布"三种情况在回执里长得一模一样 —— 一个读不出含义
292
+ // 的字段比没有这个字段更糟。没有画布的页面继续不给字段,与加这个信号之前逐字节一致。
293
+ if (d.hasCanvas) {
294
+ out.canvas_changed = d.canvasChanged;
295
+ out.dom_changed = d.domChanged;
296
+ out.canvas_idle = d.canvasIdle;
297
+ out.canvas_repeat = d.canvasRepeat;
298
+ }
299
+
300
+ if (d.changed) {
301
+ if (d.canvasChanged === true && !d.domChanged && !out.effect_hint) {
302
+ out.effect_hint = HINT_CANVAS;
303
+ }
304
+ return out;
305
+ }
306
+
136
307
  out.page_delta = d.delta;
137
308
  const isWrite = MUST_HAVE_EFFECT.has(String(action || ''));
138
309
  if (!out.effect_hint) {
139
- out.effect_hint = isWrite ? HINT_WRITE : HINT_CLICK;
310
+ if (d.mode === 'drift') out.effect_hint = HINT_CANVAS_NOISY;
311
+ else if (d.mode === 'unknown' && d.hasCanvas) out.effect_hint = HINT_CANVAS_UNKNOWN;
312
+ else out.effect_hint = isWrite ? HINT_WRITE : HINT_CLICK;
140
313
  }
141
- // 写类动作 + 主文档零变化 = 内容很可能没落地。把 effect_state 从 committed
142
- // 降回 unknown,否则回执是自相矛盾的:success:true + effect_state:committed
143
- // 等于告诉 agent"这一手已经生效,别重试",而观测说它没生效。
144
- //
145
- // 为什么是 unknown 而不是 none:探针只看主文档,OOPIF 子帧里的编辑器
146
- // (B站 read-editor)变化它看不见。unknown + verify_first 是唯一诚实的选择。
314
+ // 写类动作"什么都没变":工具无法证明它落地了,只能降级成"先验证"。
315
+ // 它看不见的东西(OOPIF、原生弹窗、跨进程编辑)太多,unknown + verify_first 是唯一诚实的选择。
147
316
  if (isWrite && out.success === true) {
148
317
  out.effect_state = 'unknown';
149
318
  out.retry = 'verify_first';
@@ -151,4 +320,13 @@ export function applyProbe(res, before, after, action) {
151
320
  return out;
152
321
  }
153
322
 
154
- export default { PAGE_PROBE_JS, shouldProbe, settleMs, diffProbe, applyProbe };
323
+ // 默认导出是**另一个对象**,不是命名空间本身。page_manager 用的是
324
+ // `import pageProbe from ...`,于是这里少列一个名字,调用方拿到的就是 undefined
325
+ // 而不会报错 —— IDLE_WINDOW_MS 就漏过一次:`setTimeout(r, undefined)` 等于 0ms,
326
+ // "空闲标定"退化成"立刻再采一次",两次采样的计数完全相同,页面被误判成静止,
327
+ // 于是动画页上的"画布变了"被算成动作生效。症状在很远的地方(回执里 canvas_idle
328
+ // 恒为 true),根因在这里。
329
+ // 由 tests/test_page_probe.js 的 PP-30 逐键核对,不再靠人记得。
330
+ export default {
331
+ PAGE_PROBE_JS, shouldProbe, settleMs, diffProbe, applyProbe, IDLE_WINDOW_MS,
332
+ };
@@ -0,0 +1,70 @@
1
+ // shared/placeholder.cjs — 新标签页的"占位页"地址与判定。
2
+ //
3
+ // 为什么单独一个模块:这段逻辑出过一个只在打包后暴露的事故(2026-10-28)。
4
+ // 占位页 URL 用字符串拼 `'file://' + path`,而打包后的路径是
5
+ // `/Applications/AI Browser.app/...`(有空格)—— 拼出来的 URL 带一个字面空格,
6
+ // Chromium 报回来的是 `%20`。判据写成 `getURL() === placeholderUrl` 就永远不成立,
7
+ // 于是"垫片装好后去加载真正目标"的那一步被当成"这一页已经被导航走了"而跳过,
8
+ // 新标签页永久停在占位页。开发树上跑得通(路径没空格),打包后必然挂。
9
+ //
10
+ // 两条教训固化成代码:
11
+ // 1. **不要手拼 file:// URL**,用 pathToFileURL(它会正确转义)。
12
+ // 2. **不要用 URL 字符串相等判断"是不是同一页"**,按文件名判据。
13
+ 'use strict';
14
+
15
+ const path = require('node:path');
16
+ const { pathToFileURL } = require('node:url');
17
+
18
+ /** 占位页文件名。改文件名时这里和 renderer/ 目录要一起改。 */
19
+ const PLACEHOLDER_FILE = 'loading.html';
20
+
21
+ /**
22
+ * 把本地页面 + query 拼成合法的 file:// URL。
23
+ *
24
+ * 全项目**只有这一处**允许拼 file URL:手拼 `'file://' + path` 在打包后必炸
25
+ * (路径含空格 → Chromium 报 %20,任何字符串比较都会失效)。错误页、下载结果页
26
+ * 一度也是手拼的,它们在 /Applications 里同样加载不出来。
27
+ */
28
+ function fileUrlWithQuery(pagePath, params) {
29
+ try {
30
+ const q = new URLSearchParams(params || {});
31
+ const base = pathToFileURL(String(pagePath)).href;
32
+ const qs = q.toString();
33
+ return qs ? base + '?' + qs : base;
34
+ } catch (_e) {
35
+ return null;
36
+ }
37
+ }
38
+
39
+ /**
40
+ * 造占位页 URL。`targetUrl` 为空时返回 about:blank(window.open("") 的老站模式
41
+ * 本来就要停在空白页等站点赋 location)。
42
+ */
43
+ function placeholderUrlFor(pagePath, targetUrl) {
44
+ if (!targetUrl) return 'about:blank';
45
+ // pathToFileURL 会处理空格、中文、#、? 等一切需要在 URL 里转义的字符。
46
+ return fileUrlWithQuery(pagePath, { url: String(targetUrl) }) || 'about:blank';
47
+ }
48
+
49
+ /**
50
+ * 这个地址还是不是"我的占位页"。
51
+ *
52
+ * 空 / about:blank 也算 —— 占位页刚发起的那一瞬 getURL() 还是空,把它判成
53
+ * "已经导航走了"会让新标签页永远卡住(这条也踩过)。
54
+ */
55
+ function isPlaceholderUrl(url) {
56
+ const u = String(url || '');
57
+ if (!u || u === 'about:blank') return true;
58
+ // 网络页面一律不是占位页 —— 否则一个恰好叫 loading.html 的站点页面会被
59
+ // 当成"还没开始导航",真正的目标就再也加载不出来了。
60
+ if (/^https?:/i.test(u)) return false;
61
+ try {
62
+ // 去掉 query 看文件名,不要拿整串比:编码、尾斜杠、query 顺序都不可控。
63
+ const bare = u.split('?')[0].split('#')[0];
64
+ return path.posix.basename(decodeURIComponent(bare)) === PLACEHOLDER_FILE;
65
+ } catch (_e) {
66
+ return /\/loading\.html(\?|$)/.test(u);
67
+ }
68
+ }
69
+
70
+ module.exports = { PLACEHOLDER_FILE, fileUrlWithQuery, placeholderUrlFor, isPlaceholderUrl };
@@ -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.3.0';
5
+ export const VERSION = '2.4.0';
@@ -0,0 +1,82 @@
1
+ // shared/window_show.js — 窗口"显示那一刻"的自述口径。
2
+ //
3
+ // 为什么单独一个模块:这里连续出过两次同一类问题,都是**记录比事实好看**。
4
+ //
5
+ // 第一次(2026-10-14):`waited_for_dom` 恒为 true —— 3s 兜底显示时也报 true,
6
+ // 于是"等到了 dom-ready"和"我们主动选择先显示"混成同一种结果,白屏缺陷从
7
+ // 记录里看不出来。修法是把"为什么现在显示"记成 show_reason。
8
+ //
9
+ // 第二次(2026-10-29,就是本模块):那次修复只区分了 timeout,**漏掉了占位页**。
10
+ // 2026-10-24 起新标签页先加载 `loading.html`(把白屏变成"正在打开 <url>"),
11
+ // 而这个占位页自己会发 dom-ready —— 于是 `show_reason: 'dom-ready'` +
12
+ // `waited_for_dom: true` 照旧成立,只不过等到的 DOM 是**我们自己的**占位页。
13
+ // 实测:起始页是 baidu,外网不通时窗口照样报"等到了 dom-ready",而此刻页面
14
+ // 是我们的占位页(body 578 字符),1.5s 后仍是 578。
15
+ //
16
+ // 所以口径必须按"谁的 DOM"来分:
17
+ // dom-ready / renderer-ready + 目标文档 → 真等到了,waited_for_dom = true
18
+ // dom-ready / renderer-ready + 占位页 → show_reason = 'placeholder',
19
+ // waited_for_dom = false(我们没等到目标页)
20
+ // timeout → false
21
+ // fail-load → false(目标文档**失败**了,随后由自绘错误页接手)
22
+ //
23
+ // ⚠️ 这个模块**不改显示时机**。占位页一就绪就显示,是 2026-10-24 的决定
24
+ // (人先看到"正在打开 <url>"比看到白屏好)。这里只负责把那一刻记录成事实。
25
+ // 本文件是 ESM(主进程直接 import),占位页判定复用 CJS 模块。
26
+ import placeholder from './placeholder.cjs';
27
+
28
+ /**
29
+ * 调用方(showOnce)能传进来的**事件名**。与输出枚举分开:
30
+ * 'placeholder' 是**折算出来的结论**,不是事件 —— 把它混进输入侧会让"输出在枚举内"
31
+ * 这条不变量变成自证(输入什么就输出什么)。
32
+ */
33
+ export const SHOW_EVENT_REASONS = ['dom-ready', 'renderer-ready', 'fail-load', 'timeout'];
34
+
35
+ /** show_reason 的合法取值(输出侧)。新增一个必须同时改这里和 NV-A3b 的枚举断言。 */
36
+ export const SHOW_REASONS = [
37
+ 'dom-ready', 'renderer-ready', 'fail-load', 'timeout', 'placeholder',
38
+ // 归因不明时保留原样(调用方传了奇怪的字符串)—— 留在枚举里是为了让
39
+ // "输出一定是枚举之一"这条不变量成立,而不是让读的人去猜。
40
+ 'unknown',
41
+ ];
42
+
43
+ /** 这两个原因字面上是"文档就绪",但只有 url 不是占位页时才作数。 */
44
+ const READY_REASONS = new Set(['dom-ready', 'renderer-ready']);
45
+
46
+ /**
47
+ * 把"触发显示的事件 + 当时 webContents 的 URL"折算成可对外播报的自述。
48
+ *
49
+ * 纯函数,无 Electron 依赖 —— 这一层必须能被单测钉死,因为它回答的是
50
+ * "我们说的话算不算数",而这类错误在 e2e 里只会表现为一个莫名其妙的红。
51
+ *
52
+ * @param {string} reason 触发显示的事件名:dom-ready / renderer-ready / fail-load / timeout
53
+ * @param {string} url 那一刻 webContents.getURL()(可能为空串)
54
+ * @returns {{show_reason: string, waited_for_dom: boolean, on_placeholder: boolean}}
55
+ */
56
+ export function classifyShowReason(reason, url) {
57
+ const r = String(reason || 'unknown');
58
+ const ready = READY_REASONS.has(r);
59
+ // 空串也算占位页(导航刚发起时 getURL() 还是空,见 placeholder.cjs 的说明)。
60
+ // 网络页面一律不算 —— 一个恰好叫 loading.html 的站点页面不该被误判。
61
+ let onPlaceholder = false;
62
+ try {
63
+ onPlaceholder = placeholder.isPlaceholderUrl(url);
64
+ } catch (_e) {
65
+ onPlaceholder = false;
66
+ }
67
+ if (ready && onPlaceholder) {
68
+ return { show_reason: 'placeholder', waited_for_dom: false, on_placeholder: true };
69
+ }
70
+ return { show_reason: r, waited_for_dom: ready, on_placeholder: onPlaceholder };
71
+ }
72
+
73
+ /**
74
+ * 记录里额外要带的那句"我当时看到的是哪一页"。
75
+ *
76
+ * 只留 origin+路径太长(占位页 URL 里带着目标地址,那正是最有用的一半),
77
+ * 所以整串保留但截断 —— 一条记录被撑到几千字符会让日志无法目视。
78
+ */
79
+ export function describeShowUrl(url, max = 300) {
80
+ const s = String(url || '');
81
+ return s.length > max ? s.slice(0, max) + '…' : s;
82
+ }