@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.
@@ -11,6 +11,9 @@ import findRefUtil from '../shared/find_ref.cjs';
11
11
  // 错误日志:RPC 层异常必须落盘(此前只回一句 JSON-RPC error,现场永久丢失),
12
12
  // 每次调用的摘要进环形缓冲,作为崩溃时的上下文。
13
13
  import { recordError, noteCall, recentErrors } from './error_log.js';
14
+ // 默认目标标签页的判据(explicit > session > active > first),理由与两条不可
15
+ // 退让的约束见 shared/tab_route.cjs 顶部(多 agent 并用时"目标被别人改掉")。
16
+ import tabRoute from '../shared/tab_route.cjs';
14
17
 
15
18
  // Each startWSServer() owns a private WebSocketServer. Keeping it local (not a
16
19
  // module global) means multiple servers can coexist — required by tests that
@@ -45,6 +48,15 @@ function findWaitTarget(tree, target) {
45
48
  // 不够稳;pid + started_at 两个一起才足以判定"是不是同一个进程"。
46
49
  const serverStartedAt = Math.floor(Date.now() / 1000);
47
50
 
51
+ // 这些方法**不碰页面**,所以"你的标签页没了"不该拦它们 —— 否则 agent 在标签页
52
+ // 被别人关掉之后,连 ui.new_tab / ui.list_tabs 这种自救动作都会被错误挡回去,
53
+ // 等于把人锁在门外。
54
+ const TABLESS_METHODS = new Set([
55
+ 'ui.new_tab', 'ui.list_tabs', 'ui.close_tab', 'ui.server_info', 'ui.errors',
56
+ 'ui.window', 'ui.window_bounds', 'ui.window_shown', 'ui.quit',
57
+ 'ui.subscribe', 'ui.unsubscribe',
58
+ ]);
59
+
48
60
  export function startWSServer(pageManager, port = config.wsPort, onQuit = null) {
49
61
  // Bind loopback only — the protocol carries no auth. ws' default (host
50
62
  // omitted) is 0.0.0.0, which would expose the browser — including all its
@@ -94,13 +106,55 @@ export function startWSServer(pageManager, port = config.wsPort, onQuit = null)
94
106
  }
95
107
 
96
108
  const { id, method, params = {} } = msg;
97
- const tabId = params.tab; // optional tab routing
109
+ // 这次调用操作哪个标签页:调用方点名 > 本连接自己的标签页 > 人眼看的那一个。
110
+ //
111
+ // 以前这里是 `const tabId = params.tab`,缺省就落到全局 activeTab —— 单 agent
112
+ // 时看不出问题,多个 agent 同时用时就是灾难:A 开一个标签页,所有人的默认
113
+ // 目标都变成它;人切一下标签页,把所有 agent 的目标一起切走。判据集中在
114
+ // shared/tab_route.cjs,这里只负责把会话维度接上去。
115
+ //
116
+ // 全程 try/catch + 能力探测:单测用的是 Mock PageManager(没有 tabs /
117
+ // sessionTabOf),路由不该因此把每个方法都打成 500。
118
+ let routed;
119
+ try {
120
+ if (typeof pageManager.resolveTargetTab === 'function') {
121
+ routed = pageManager.resolveTargetTab({ explicit: params.tab, sessionId });
122
+ } else {
123
+ const known = (pageManager.tabs && typeof pageManager.tabs.keys === 'function')
124
+ ? Array.from(pageManager.tabs.keys()) : [];
125
+ routed = tabRoute.resolveTarget({
126
+ explicit: params.tab,
127
+ session: typeof pageManager.sessionTabOf === 'function' ? pageManager.sessionTabOf(sessionId) : null,
128
+ active: pageManager.activeTab,
129
+ tabs: known,
130
+ });
131
+ // 拿不到标签页清单(单测 mock)→ 不参与路由,按调用方给的来
132
+ if (!known.length && (params.tab === undefined || params.tab === null)) {
133
+ routed = { tab: null, source: 'unknown' };
134
+ }
135
+ }
136
+ } catch (_) {
137
+ routed = { tab: params.tab === undefined ? null : params.tab, source: 'unknown' };
138
+ }
139
+ const tabId = routed.tab;
98
140
  const send = (payload) => {
99
141
  if (ws.readyState === 1) ws.send(JSON.stringify(payload));
100
142
  };
143
+ // 会话标签页没了 → 必须在这一层拦住(否则会退回到别人的页面继续执行)。
144
+ //
145
+ // 但"点名了一个不存在的 tab"**不**在这里报:那是方法自己的校验,而且各方法
146
+ // 的词汇更准(ui.repaint 报 no-such-tab、ui.diff 报 tab-mismatch,
147
+ // 后者是语义检查而不是"找不到")。在这里统一改写成 RPC error 会把
148
+ // "跨 tab 比对被拒绝"这类可诊断的结论一并抹平。
149
+ const routingError = () => {
150
+ if (!routed.error || routed.source === 'gone') return false;
151
+ send({ jsonrpc: '2.0', id, error: { code: -32001, message: routed.error, data: { source: routed.source } } });
152
+ return true;
153
+ };
101
154
 
102
155
  const t0 = Date.now();
103
156
  try {
157
+ if (!TABLESS_METHODS.has(method) && routingError()) return;
104
158
  switch (method) {
105
159
  case 'ui.get_tree': {
106
160
  // P0 probe: params.ax routes to the AX read layer (getFullAXTree);
@@ -139,6 +193,12 @@ export function startWSServer(pageManager, port = config.wsPort, onQuit = null)
139
193
  if (hoisted.hoisted.length && result && typeof result === 'object' && !result.params_hoisted) {
140
194
  result.params_hoisted = hoisted.hoisted;
141
195
  }
196
+ // 这次点击开出了新标签页(target=_blank / window.open)→ 把这个连接的
197
+ // 工作目标挪过去。注意只是**目标**:人眼前的页面由 page_manager 决定
198
+ // (opener 可见时才会真的切过去),后台任务不会被这个跟随顶到前台。
199
+ if (result && result.opened_tab && result.opened_tab.id) {
200
+ pageManager.bindSessionTab(sessionId, result.opened_tab.id);
201
+ }
142
202
  send({ jsonrpc: '2.0', id, result });
143
203
  } catch (e) {
144
204
  if (e && e.__deadline) {
@@ -274,17 +334,45 @@ export function startWSServer(pageManager, port = config.wsPort, onQuit = null)
274
334
  }
275
335
  // === Tab management ===
276
336
  case 'ui.new_tab': {
277
- const newTabId = pageManager.newTab(params.url || null);
278
- send({ jsonrpc: '2.0', id, result: { tab: newTabId } });
337
+ // show 缺省 = **不显示**:人正在看的那一页是人的东西,agent 开一个新
338
+ // 页面不该把它顶掉(多 agent 时更是如此:谁也说不清该顶掉谁)。
339
+ // 例外见 shared/tab_route.cjs 的 shouldShowNewTab:显式 show:true、
340
+ // 或者当前根本没有可见标签页(否则人打开窗口看到一片空白)。
341
+ const show = tabRoute.shouldShowNewTab({
342
+ requested: params.show === undefined ? undefined : params.show === true,
343
+ hasVisible: !!pageManager.activeTab,
344
+ // 人眼前还是启动页 = 还没有"人的页面"可保护,agent 的第一页直接顶上去
345
+ visibleIsStartup: pageManager.activeTab !== null &&
346
+ pageManager.activeTab === pageManager.startupTab,
347
+ });
348
+ const newTabId = pageManager.newTab(params.url || null, { show });
349
+ // 新标签页立刻成为**这个连接的**工作目标(不影响别的连接、也不影响人)。
350
+ if (typeof pageManager.bindSessionTab === 'function') pageManager.bindSessionTab(sessionId, newTabId);
351
+ send({ jsonrpc: '2.0', id, result: { tab: newTabId, shown: show } });
279
352
  break;
280
353
  }
281
354
  case 'ui.close_tab': {
282
- const ok = pageManager.closeTab(params.tab);
283
- send({ jsonrpc: '2.0', id, result: { ok } });
355
+ const target = params.tab !== undefined && params.tab !== null ? params.tab : tabId;
356
+ const ok = pageManager.closeTab(target);
357
+ // **只有自己关掉自己那个页**才解绑:那是一次明确的"我不用它了",
358
+ // 之后的调用照浏览器惯例落到当前可见页。
359
+ // 别人的页被关掉时绑定要留着 —— 下一次调用必须明确报"你的页没了",
360
+ // 否则 agent 会在**另一个 agent 的页面**上继续执行,回执还是 success。
361
+ if (ok && typeof pageManager.sessionTabOf === 'function' &&
362
+ pageManager.sessionTabOf(sessionId) === target) {
363
+ pageManager.bindSessionTab(sessionId, null);
364
+ }
365
+ send({ jsonrpc: '2.0', id, result: { ok, tab: target } });
284
366
  break;
285
367
  }
286
368
  case 'ui.list_tabs': {
287
369
  const tabs = pageManager.listTabs();
370
+ // mine:只在自己那一条上出现(不加的人拿不到这个字段,省 token)。
371
+ // 多 agent 时"我在哪个标签页上"必须能问出来,否则 agent 只能靠猜。
372
+ const mine = typeof pageManager.sessionTabOf === 'function' ? pageManager.sessionTabOf(sessionId) : null;
373
+ if (mine !== null && mine !== undefined) {
374
+ for (const t of tabs) if (t.id === mine) t.mine = true;
375
+ }
288
376
  send({ jsonrpc: '2.0', id, result: { tabs } });
289
377
  break;
290
378
  }
@@ -298,8 +386,49 @@ export function startWSServer(pageManager, port = config.wsPort, onQuit = null)
298
386
  break;
299
387
  }
300
388
  case 'ui.set_active_tab': {
301
- const ok = pageManager.setActive(params.tab);
302
- send({ jsonrpc: '2.0', id, result: { ok } });
389
+ // 语义:把这个会话的工作目标换成 params.tab,并(默认)把它显示出来。
390
+ // show:false = "我只想换目标,别动人眼前的页面"。
391
+ //
392
+ // tab 不存在时回 `{ok:false, error:'no-such-tab'}`(**不是** JSON-RPC error):
393
+ // 这是"这一次切换没成功",不是"这次调用本身不合法",调用方要能用同一个
394
+ // 回执通道区分它和"路由崩了"。契约由 test_ws_handlers 的 TAB-2 钉住。
395
+ const target = params.tab;
396
+ const exists = target !== undefined && target !== null &&
397
+ pageManager.tabs && typeof pageManager.tabs.has === 'function' && pageManager.tabs.has(target);
398
+ // 回执形状是 2026-10-19 那次事故的回归点(agent 曾收到 `{}`):
399
+ // 成功就回 `{ok:true}`,多余字段一个都不加 —— 只有调用方显式要
400
+ // `show:false`(新语义)时才多一个 `shown`。
401
+ if (!exists && pageManager.tabs && typeof pageManager.tabs.has === 'function') {
402
+ send({ jsonrpc: '2.0', id, result: { ok: false, error: 'no-such-tab', tab: target } });
403
+ break;
404
+ }
405
+ if (!exists) {
406
+ // 没有 tabs 能力的调用方(单测 mock):按老契约让 setActive 自己回
407
+ const okMock = typeof pageManager.setActive === 'function' ? pageManager.setActive(target) : false;
408
+ send({ jsonrpc: '2.0', id, result: okMock
409
+ ? (params.show === false ? { ok: true, shown: false } : { ok: true })
410
+ : { ok: false, error: 'no-such-tab' } });
411
+ break;
412
+ }
413
+ if (typeof pageManager.bindSessionTab === 'function') pageManager.bindSessionTab(sessionId, target);
414
+ const ok = params.show === false ? true : pageManager.setActive(target);
415
+ send({ jsonrpc: '2.0', id, result: ok
416
+ ? (params.show === false ? { ok: true, shown: false } : { ok: true })
417
+ : { ok: false, error: 'no-such-tab', tab: target } });
418
+ break;
419
+ }
420
+ // 窗口可见性 / 最小化。后台运行(无头式无人值守)的唯一开关,
421
+ // 详见 page_manager.windowState 的注释。
422
+ case 'ui.window': {
423
+ if (typeof pageManager.windowState !== 'function') {
424
+ send({ jsonrpc: '2.0', id, result: { ok: false, error: 'window control not available (no Electron window)' } });
425
+ break;
426
+ }
427
+ let r;
428
+ if (params.visible !== undefined) r = pageManager.setWindowVisible(params.visible === true, { focus: params.focus === true });
429
+ else if (params.minimized !== undefined) r = await pageManager.setWindowMinimized(params.minimized === true);
430
+ else r = pageManager.windowState();
431
+ send({ jsonrpc: '2.0', id, result: r });
303
432
  break;
304
433
  }
305
434
  // 服务端的进程身份。存在的理由(2026-10-15 实测):调用方**无法确认
@@ -320,6 +449,11 @@ export function startWSServer(pageManager, port = config.wsPort, onQuit = null)
320
449
  // 渲染路径:{gpu:true|false, reason:'default'|'env'|'fallback'}。
321
450
  // 白屏/缩放类缺陷的复现与"这条路有没有关系"都要靠它。
322
451
  ...(pageManager.renderPath ? { render_path: pageManager.renderPath } : {}),
452
+ // 窗口状态:后台运行时要能问到"现在到底是不是隐藏的",否则
453
+ // "我没看到窗口却以为它在显示"这类问题只能靠猜。
454
+ ...(pageManager.windowState ? { window: pageManager.windowState() } : {}),
455
+ // 这个连接的工作标签页(多 agent 时用来核对自己绑到了哪一页)
456
+ ...(pageManager.sessionTabOf ? { session_tab: pageManager.sessionTabOf(sessionId) } : {}),
323
457
  },
324
458
  });
325
459
  break;
@@ -543,6 +677,15 @@ export function startWSServer(pageManager, port = config.wsPort, onQuit = null)
543
677
  send({ jsonrpc: '2.0', id, result: r });
544
678
  break;
545
679
  }
680
+ // === ui.download — 把当前页存进下载目录 ===
681
+ // 用于"这一页本来就是一张图片/视频/PDF,我想留下文件":
682
+ // 浏览器把它显示出来了(见 shared/media_doc.cjs),但"要文件"这条路
683
+ // 不能因此消失。工具条上那个「下载」按钮走的就是同一个实现。
684
+ case 'ui.download': {
685
+ const r = pageManager.downloadCurrent(tabId);
686
+ send({ jsonrpc: '2.0', id, result: r });
687
+ break;
688
+ }
546
689
  // === ui.errors — 读主进程错误日志(本次进程的内存记录 + 文件路径)===
547
690
  // 存在的理由:界面里弹一个"js 崩溃"的原生框,栈只活在框里,点掉就没了。
548
691
  // 让调用方能主动问"刚才报过什么错",不用靠人复述。
@@ -32,6 +32,16 @@ contextBridge.exposeInMainWorld("__ai_browser__", {
32
32
  if (op === 'open') ipcRenderer.send('ai:window_open', { token: token, url: url, name: name || '' });
33
33
  else if (op === 'nav') ipcRenderer.send('ai:window_open_nav', { token: token, url: url });
34
34
  else if (op === 'close') ipcRenderer.send('ai:window_open_close', { token: token });
35
+ },
36
+ // 我们自己的界面页(renderer/download.html)用的最小通道:
37
+ // 查这条下载的进度、打开文件、在 Finder 中显示。
38
+ // ⚠️ 但它挂在**每个**标签页的 window 上(包括站点页面),所以主进程侧必须
39
+ // 校验 sender 的 URL 是不是自家 renderer 页面 —— 见 index.js 的 isChromeSender。
40
+ // 站点页面即使调到这里,也只会拿到 {found:false}。
41
+ dl: {
42
+ record: function() { return ipcRenderer.invoke('dl:record'); },
43
+ open: function(p) { ipcRenderer.send('dl:open', p); },
44
+ reveal: function(p) { ipcRenderer.send('dl:reveal', p); }
35
45
  }
36
46
  });
37
47
 
@@ -0,0 +1,217 @@
1
+ <!DOCTYPE html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <title>下载</title>
6
+ <!--
7
+ download.html — 「下载结果」页。
8
+
9
+ 为什么需要它(2026-10-27,沧州教师继续教育网"证书下载"):
10
+
11
+ 站点用新标签打开一个 `Content-Disposition: attachment` 的地址(zip/dmg/exe,
12
+ 或者带 download 属性的图片)。这种导航**永远不会提交** —— 那个标签页于是
13
+ 停在 loading.html 上,只剩一句「正在打开…」和一坨 URL,永远不动。
14
+ 下载其实成功了,但落在 ~/.ai-browser/downloads/<tab>/ 里,界面上零回执。
15
+
16
+ 所以:这个 tab 没有真页面可丢(它从没加载成功过),就把它换成本页 ——
17
+ 文件名、大小、保存位置,以及「打开」「在 Finder 中显示」。
18
+ 下载还在进行时这里显示进度,完成后自动变成按钮(轮询 dl:record)。
19
+
20
+ 这里调用的 `__ai_browser__.dl` 只在**我们自己的界面页**上被主进程受理,
21
+ 见 main/index.js 的 isChromeSender(站点页面调用会被直接忽略)。
22
+ -->
23
+ <style>
24
+ * { margin: 0; padding: 0; box-sizing: border-box; }
25
+ html, body { height: 100%; }
26
+ body {
27
+ background: #1e1e1e;
28
+ color: #d4d4d4;
29
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', sans-serif;
30
+ font-size: 13px;
31
+ display: flex; align-items: center; justify-content: center;
32
+ padding: 40px 24px;
33
+ }
34
+ .card {
35
+ display: flex; gap: 20px; align-items: flex-start;
36
+ max-width: 760px; width: 100%;
37
+ }
38
+ .thumb {
39
+ flex: none; width: 132px; height: 132px; border-radius: 8px;
40
+ background: #252526; border: 1px solid #3a3a3a;
41
+ display: flex; align-items: center; justify-content: center;
42
+ overflow: hidden; position: relative;
43
+ }
44
+ .thumb img { width: 100%; height: 100%; object-fit: cover; display: block; }
45
+ .thumb .glyph { font-size: 34px; font-weight: 700; color: #6b6b6b; letter-spacing: 0.5px; }
46
+ .body { flex: 1; min-width: 0; }
47
+ h1 { font-size: 15px; font-weight: 600; color: #e8e8e8; margin-bottom: 6px; }
48
+ h1 .state { color: #4ec9b0; font-weight: 500; }
49
+ .name {
50
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
51
+ font-size: 12px; color: #9cdcfd; word-break: break-all;
52
+ margin-bottom: 10px; line-height: 1.5;
53
+ }
54
+ .meta { color: #858585; font-size: 12px; line-height: 1.9; margin-bottom: 16px; }
55
+ .meta code {
56
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
57
+ color: #b5b5b5; word-break: break-all;
58
+ }
59
+ .bar {
60
+ height: 4px; background: #333; border-radius: 2px; overflow: hidden;
61
+ margin-bottom: 14px; display: none;
62
+ }
63
+ .bar.on { display: block; }
64
+ .bar > i { display: block; height: 100%; width: 0; background: #0e639c; transition: width .2s; }
65
+ .row { display: flex; gap: 8px; flex-wrap: wrap; }
66
+ button {
67
+ background: #0e639c; color: #fff; border: none; border-radius: 4px;
68
+ padding: 7px 16px; font-size: 12px; cursor: pointer; font-family: inherit;
69
+ }
70
+ button:hover { background: #1177bb; }
71
+ button.ghost { background: #3a3d41; }
72
+ button.ghost:hover { background: #4a4d51; }
73
+ .url {
74
+ margin-top: 16px; color: #6a6a6a; font-size: 11px; line-height: 1.6;
75
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
76
+ word-break: break-all; max-height: 34px; overflow: hidden;
77
+ }
78
+ </style>
79
+ </head>
80
+ <body>
81
+ <div class="card">
82
+ <div class="thumb" id="thumb"><span class="glyph" id="glyph">?</span></div>
83
+ <div class="body">
84
+ <h1 id="head">已下载 <span class="state" id="state"></span></h1>
85
+ <div class="name" id="name">…</div>
86
+ <div class="meta" id="meta"></div>
87
+ <div class="bar" id="bar"><i id="barfill"></i></div>
88
+ <div class="row">
89
+ <button id="open">打开</button>
90
+ <button id="reveal" class="ghost">在 Finder 中显示</button>
91
+ <button id="copy" class="ghost">复制路径</button>
92
+ </div>
93
+ <div class="url" id="url"></div>
94
+ </div>
95
+ </div>
96
+ <script>
97
+ (function () {
98
+ var q = new URLSearchParams(location.search);
99
+ var rec = {
100
+ name: q.get('name') || 'download',
101
+ path: q.get('path') || '',
102
+ mime: q.get('mime') || '',
103
+ total: Number(q.get('size') || 0),
104
+ received: 0,
105
+ state: 'progressing'
106
+ };
107
+ var KIND_LABEL = { image: '图片', video: '视频', audio: '音频', pdf: 'PDF', file: '文件' };
108
+ var KIND_GLYPH = { image: 'IMG', video: 'VID', audio: 'AUD', pdf: 'PDF', file: 'FILE' };
109
+ var EXT_GLYPH = function (name) {
110
+ var m = String(name || '').match(/\.([a-z0-9]{1,5})$/i);
111
+ return m ? m[1].toUpperCase() : 'FILE';
112
+ };
113
+
114
+ var $ = function (id) { return document.getElementById(id); };
115
+ var api = null;
116
+ try { api = (window.__ai_browser__ && window.__ai_browser__.dl) || null; } catch (e) { api = null; }
117
+
118
+ function kindOf(mime) {
119
+ var m = String(mime || '').toLowerCase();
120
+ if (m.indexOf('image/') === 0) return 'image';
121
+ if (m.indexOf('video/') === 0) return 'video';
122
+ if (m.indexOf('audio/') === 0) return 'audio';
123
+ if (m === 'application/pdf') return 'pdf';
124
+ return 'file';
125
+ }
126
+ function humanSize(n) {
127
+ n = Number(n);
128
+ if (!isFinite(n) || n <= 0) return '大小未知';
129
+ var u = ['B', 'KB', 'MB', 'GB', 'TB'], v = n, i = 0;
130
+ while (v >= 1024 && i < u.length - 1) { v /= 1024; i++; }
131
+ return (i === 0 ? Math.round(v) : (v >= 100 ? v.toFixed(0) : v.toFixed(1))) + u[i];
132
+ }
133
+ function ext(mime) {
134
+ mime = String(mime || '').toLowerCase();
135
+ if (mime === 'application/pdf') return 'PDF 文档';
136
+ if (mime.indexOf('image/') === 0) return '图片';
137
+ if (mime.indexOf('video/') === 0) return '视频';
138
+ if (mime.indexOf('audio/') === 0) return '音频';
139
+ if (/zip|compressed/.test(mime)) return '压缩包';
140
+ if (/dmg|diskimage/.test(mime)) return '磁盘映像';
141
+ if (/msdownload|octet-stream|exe/.test(mime)) return '安装包 / 二进制';
142
+ if (/word|document/.test(mime)) return '文档';
143
+ if (/sheet|excel/.test(mime)) return '表格';
144
+ return mime ? '文件' : '未知类型';
145
+ }
146
+
147
+ function paint() {
148
+ var kind = kindOf(rec.mime);
149
+ $('name').textContent = rec.name;
150
+ $('url').textContent = q.get('url') || '';
151
+ var done = rec.state === 'completed';
152
+ $('head').firstChild.nodeValue = done ? '已下载 ' : (rec.state === 'interrupted' ? '下载中断 ' : '正在下载 ');
153
+ $('state').textContent = done ? '' : (rec.state === 'interrupted' ? '(可重试)' : '');
154
+ $('meta').innerHTML =
155
+ '类型:' + ext(rec.mime) + (rec.mime ? '(' + rec.mime + ')' : '') +
156
+ ' &nbsp;·&nbsp; 大小:' + humanSize(rec.total || rec.received) +
157
+ (rec.path ? '<br>位置:<code>' + rec.path.replace(/&/g, '&amp;').replace(/</g, '&lt;') + '</code>' : '');
158
+ var glyph = $('glyph');
159
+ if (!glyph.dataset.set) {
160
+ glyph.textContent = kind === 'file' ? EXT_GLYPH(rec.name) : (KIND_GLYPH[kind] || 'FILE');
161
+ glyph.dataset.set = '1';
162
+ }
163
+ // 进度条:只有"还没完"才显示,完成后不该在结果页上留一条满格绿线
164
+ var pct = rec.total > 0 ? Math.min(100, Math.round((rec.received / rec.total) * 100)) : 0;
165
+ $('bar').className = done ? 'bar' : 'bar on';
166
+ $('barfill').style.width = (rec.total > 0 ? pct : 4) + '%';
167
+
168
+ if (rec.thumb) {
169
+ var img = document.createElement('img');
170
+ img.src = rec.thumb;
171
+ $('thumb').innerHTML = '';
172
+ $('thumb').appendChild(img);
173
+ }
174
+ }
175
+
176
+ // 轮询:进度、完成、缩略图都从主进程取(页面里没有别的通道)。
177
+ function poll() {
178
+ if (!api) { paint(); return; }
179
+ api.record().then(function (r) {
180
+ if (r && r.found) {
181
+ rec.state = r.state || rec.state;
182
+ rec.received = r.received || 0;
183
+ if (r.total) rec.total = r.total;
184
+ if (r.path) rec.path = r.path;
185
+ if (r.filename) rec.name = r.filename;
186
+ if (r.mime) rec.mime = r.mime;
187
+ if (r.thumb) rec.thumb = r.thumb;
188
+ }
189
+ paint();
190
+ if (rec.state === 'progressing') setTimeout(poll, 500);
191
+ }).catch(function () { paint(); });
192
+ }
193
+
194
+ $('open').addEventListener('click', function () {
195
+ if (!api || !rec.path) return;
196
+ if (rec.state !== 'completed') return;
197
+ api.open(rec.path);
198
+ });
199
+ $('reveal').addEventListener('click', function () {
200
+ if (!api || !rec.path) return;
201
+ api.reveal(rec.path);
202
+ });
203
+ $('copy').addEventListener('click', function () {
204
+ var t = rec.path || '';
205
+ var self = this;
206
+ var flash = function () { self.textContent = '已复制'; setTimeout(function () { self.textContent = '复制路径'; }, 1200); };
207
+ try {
208
+ navigator.clipboard.writeText(t).then(flash, function () {});
209
+ } catch (e) { /* 剪贴板被禁就安静失败,按钮文字不变 */ }
210
+ });
211
+
212
+ paint();
213
+ poll();
214
+ })();
215
+ </script>
216
+ </body>
217
+ </html>
@@ -88,6 +88,17 @@
88
88
  overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
89
89
  }
90
90
  #status.busy { color: #e0a33e; }
91
+ /* 「已下载 xxx」回执:页面里发起的下载(点导出、点附件)完成后出现在这里。
92
+ 没有它的年代,文件悄悄落到下载目录,界面上零回执 —— 人只能认为"没反应"。 */
93
+ #receipt {
94
+ display: none; align-items: center; gap: 6px;
95
+ height: 26px; padding: 0 9px; border-radius: 4px; flex: none;
96
+ background: #24361f; color: #a8d58c; font-size: 11px;
97
+ max-width: 240px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
98
+ cursor: pointer; -webkit-app-region: no-drag;
99
+ }
100
+ #receipt.on { display: flex; }
101
+ #receipt:hover { background: #2f4629; }
91
102
  </style>
92
103
  </head>
93
104
  <body>
@@ -102,6 +113,9 @@
102
113
  <button class="nav-btn" id="reload" title="刷新">&#8635;</button>
103
114
  <button class="nav-btn" id="stop" title="停止加载" disabled>&times;</button>
104
115
  <input id="addr" type="text" placeholder="输入网址,回车打开" spellcheck="false" autocomplete="off">
116
+ <!-- 当前页是一份"本来会被下载、被救回来显示"的文档(图片/视频/音频/PDF)时才出现 -->
117
+ <button class="nav-btn" id="dl" title="下载" style="display:none">&#8595;</button>
118
+ <span id="receipt" title="点击在 Finder 中显示"></span>
105
119
  <span id="status"></span>
106
120
  </div>
107
121
 
@@ -119,6 +133,8 @@ function invoke(ch, payload) {
119
133
  const $ = (id) => document.getElementById(id);
120
134
  const tabsEl = $('tabs'), addrEl = $('addr'), statusEl = $('status');
121
135
  const backBtn = $('back'), fwdBtn = $('forward'), reloadBtn = $('reload'), stopBtn = $('stop');
136
+ const dlBtn = $('dl'), receiptEl = $('receipt');
137
+ const KIND_LABEL = { image: '图片', video: '视频', audio: '音频', pdf: 'PDF', file: '文件' };
122
138
 
123
139
  // ---- tab 条(原有逻辑,保持可用)----
124
140
  // 主进程通过 window.__onNavState 推送地址栏状态(push 模式)。
@@ -136,6 +152,30 @@ function applyNavState(s) {
136
152
  statusEl.textContent = s.status || '';
137
153
  statusEl.className = s.loading ? 'busy' : '';
138
154
  addrEl.style.borderColor = s.loading ? '#e0a33e' : '';
155
+
156
+ // 当前页是可显示的图片/视频/PDF → 给一个「下载」入口。
157
+ // 这类文档本来是"服务端要求下载"的,我们把它按内容类型显示了出来,
158
+ // 所以必须同时保留"要文件"的那条路,否则等于把功能拿掉了。
159
+ const media = s.media_doc;
160
+ dlBtn.style.display = media ? '' : 'none';
161
+ if (media) dlBtn.title = '下载这个' + (KIND_LABEL[media.kind] || '文件') + '(' + (media.mime || '') + ')';
162
+
163
+ // 页面里发起的下载完成的回执(8 秒)。点一下在 Finder 中显示。
164
+ const dl = s.download;
165
+ receiptEl.classList.toggle('on', !!dl);
166
+ if (dl) {
167
+ receiptEl.textContent = '\u2193 已下载 ' + shortName(dl.name);
168
+ receiptEl.dataset.path = dl.path || '';
169
+ receiptEl.title = (dl.path || '') + '\n点击在 Finder 中显示';
170
+ } else {
171
+ receiptEl.dataset.path = '';
172
+ }
173
+ }
174
+
175
+ /** 证书类下载的文件名常是一长串 uuid,标签位只放得下前 18 个字。 */
176
+ function shortName(name) {
177
+ const s = String(name || '文件');
178
+ return s.length > 18 ? s.slice(0, 12) + '…' + s.slice(-5) : s;
139
179
  }
140
180
 
141
181
  let lastIds = ''; // 上次渲染的 tab id 序列 —— 只有它变了才重建 DOM
@@ -250,6 +290,11 @@ backBtn.addEventListener('click', () => send('nav:back'));
250
290
  fwdBtn.addEventListener('click', () => send('nav:forward'));
251
291
  reloadBtn.addEventListener('click', () => send('nav:reload'));
252
292
  stopBtn.addEventListener('click', () => send('nav:stop'));
293
+ dlBtn.addEventListener('click', () => send('nav:download'));
294
+ receiptEl.addEventListener('click', () => {
295
+ const p = receiptEl.dataset.path;
296
+ if (p) send('dl:reveal', p);
297
+ });
253
298
 
254
299
  addrEl.addEventListener('keydown', (e) => {
255
300
  if (e.key !== 'Enter') return;