zcode-pro 1.6.1 → 1.7.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.
Files changed (42) hide show
  1. package/README.en.md +31 -21
  2. package/README.md +20 -12
  3. package/dist/inject.js +10431 -8836
  4. package/package.json +2 -1
  5. package/src/host/cdp.mjs +13 -3
  6. package/src/host/helper.mjs +1287 -488
  7. package/src/host/main.mjs +368 -30
  8. package/src/host/paths.mjs +17 -9
  9. package/src/host/pickFolder.mjs +11 -4
  10. package/src/host/settings.mjs +15 -2
  11. package/src/host/setup.mjs +54 -15
  12. package/src/host/skill-stats.mjs +6 -1
  13. package/src/host/taskIndex.mjs +464 -66
  14. package/src/host/taskOrder.mjs +128 -57
  15. package/src/host/version.mjs +15 -7
  16. package/src/host/wallpaper.mjs +76 -59
  17. package/src/host/webdav.mjs +66 -10
  18. package/src/inject/core.js +228 -103
  19. package/src/inject/features/alias-migration.js +5 -1
  20. package/src/inject/features/auto-rename.js +166 -0
  21. package/src/inject/features/file-menu.js +6 -2
  22. package/src/inject/features/idle-reclaim.js +31 -8
  23. package/src/inject/features/newtab-panels.js +11 -1
  24. package/src/inject/features/pinned-collapse.js +11 -3
  25. package/src/inject/features/plugin-card-retry.js +18 -8
  26. package/src/inject/features/plugin-updates.js +58 -0
  27. package/src/inject/features/sandbox-reclaim.js +17 -1
  28. package/src/inject/features/session-link.js +202 -0
  29. package/src/inject/features/session-switch.js +67 -30
  30. package/src/inject/features/settings-dialog.js +323 -124
  31. package/src/inject/features/status-bar.js +150 -28
  32. package/src/inject/features/subagent-icon.js +473 -0
  33. package/src/inject/features/table-copy.js +18 -2
  34. package/src/inject/features/task-order.js +47 -13
  35. package/src/inject/features/theme.js +88 -31
  36. package/src/inject/features/title-gen.js +5 -4
  37. package/src/inject/features/title-lock.js +13 -8
  38. package/src/inject/features/turn-usage.js +99 -47
  39. package/src/inject/features/ws-running.js +28 -13
  40. package/src/inject/index.js +7 -0
  41. package/src/inject/provider-fields.js +2 -2
  42. package/src/inject/ui.js +14 -0
package/src/host/main.mjs CHANGED
@@ -5,14 +5,14 @@
5
5
  // 3. 连接 CDP,向所有页面注入增强脚本(新文档自动注入 + 已加载页面立即注入)
6
6
  // 4. 启动本地辅助 HTTP 服务并常驻,CDP 断开时自动重连
7
7
  import { spawn, execSync, spawnSync } from 'node:child_process';
8
- import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, statSync } from 'node:fs';
8
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, realpathSync, renameSync, statSync } from 'node:fs';
9
9
  import { dirname, join, resolve } from 'node:path';
10
10
  import { fileURLToPath } from 'node:url';
11
11
  import { randomBytes } from 'node:crypto';
12
12
  import { resolveZcodeExecutable, resolveDataRootDir } from './paths.mjs';
13
13
  import { readZcodeVersion } from './version.mjs';
14
14
  import { CdpConnection, fetchBrowserWsUrl } from './cdp.mjs';
15
- import { startHelper } from './helper.mjs';
15
+ import * as helperModule from './helper.mjs';
16
16
  import { runSetup } from './setup.mjs';
17
17
  import { runWallpaperCli, installWallpaperDocs, removeWallpaperDocs } from './wallpaper.mjs';
18
18
 
@@ -44,7 +44,8 @@ function usage() {
44
44
  --helper-port <端口> 本地辅助服务端口 (默认 47889)
45
45
  --zcode-path <路径> ZCode 可执行文件路径
46
46
  --inject-only 只注入已运行的实例(要求其带调试端口),不启动新实例
47
- --verbose 输出详细日志
47
+ --no-launch 同 --inject-only
48
+ --verbose, -v 输出详细日志
48
49
  -h, --help 显示帮助
49
50
 
50
51
  子命令:
@@ -58,15 +59,26 @@ function usage() {
58
59
  ZCODEPRO_CDP_PORT CDP 端口
59
60
  ZCODEPRO_HELPER_PORT 辅助服务端口
60
61
  ZCODE_DATA_BASE_DIR ZCode 数据根目录(与 ZCode 自身语义一致)
62
+ ZCODEPRO_DEV 设为 1 开启开发模式(设置弹窗出现“调试”标签页)
63
+ RTK_DIR rtk 插件状态目录(默认 ~/.zcode-rtk)
61
64
  `;
62
65
  }
63
66
 
64
67
  function parseArgs(argv) {
65
- const out = { cdpPort: 0, helperPort: 0, zcodePath: '', injectOnly: false, verbose: false, help: false };
68
+ const out = { cdpPort: 0, helperPort: 0, zcodePath: '', injectOnly: false, verbose: false, help: false, bad: false };
69
+ const portArg = (name, raw) => {
70
+ const n = Number(raw);
71
+ if (!raw || !Number.isInteger(n) || n < 1 || n > 65535) {
72
+ console.error(`${name} 需要 1-65535 的端口数字,收到: ${raw}`);
73
+ out.bad = true;
74
+ return 0;
75
+ }
76
+ return n;
77
+ };
66
78
  for (let i = 0; i < argv.length; i++) {
67
79
  const a = argv[i];
68
- if (a === '--cdp-port') out.cdpPort = Number(argv[++i]);
69
- else if (a === '--helper-port') out.helperPort = Number(argv[++i]);
80
+ if (a === '--cdp-port') out.cdpPort = portArg('--cdp-port', argv[++i]);
81
+ else if (a === '--helper-port') out.helperPort = portArg('--helper-port', argv[++i]);
70
82
  else if (a === '--zcode-path') out.zcodePath = argv[++i];
71
83
  else if (a === '--inject-only' || a === '--no-launch') out.injectOnly = true;
72
84
  else if (a === '--verbose' || a === '-v') out.verbose = true;
@@ -74,7 +86,7 @@ function parseArgs(argv) {
74
86
  else if (a === 'setup') out.setup = true;
75
87
  else if (a === '--uninstall') out.setupUninstall = true;
76
88
  else if (a === '--desktop') out.setupDesktop = true;
77
- else { console.error('未知参数: ' + a); out.help = true; }
89
+ else { console.error('未知参数: ' + a); out.help = true; out.bad = true; }
78
90
  }
79
91
  out.cdpPort = out.cdpPort || Number(process.env.ZCODEPRO_CDP_PORT) || 9333;
80
92
  out.helperPort = out.helperPort || Number(process.env.ZCODEPRO_HELPER_PORT) || 47889;
@@ -108,7 +120,8 @@ function winLog(line) {
108
120
  if (existsSync(file) && statSync(file).size > 512 * 1024) renameSync(file, `${file}.old`);
109
121
  } catch { /* ignore */ }
110
122
  }
111
- appendFileSync(file, `[${new Date().toISOString()}] ${line}\n`);
123
+ // 行尾 \r\n:Windows 记事本对纯 \n 的老日志显示成一行(winLog 只在 win32 写文件)
124
+ appendFileSync(file, `[${new Date().toISOString()}] ${line}\r\n`);
112
125
  } catch { /* ignore */ }
113
126
  }
114
127
 
@@ -122,8 +135,13 @@ async function cdpAlive(port) {
122
135
  function zcodeAppProcessExists() {
123
136
  try {
124
137
  if (process.platform === 'win32') {
125
- execSync('tasklist /FI "IMAGENAME eq ZCode.exe" /NH | find /I "ZCode.exe"', { stdio: 'ignore' });
126
- return true;
138
+ // 不用 find 管道只看命中:要拿到 PID 列才能排除自己(启动器以 ELECTRON_RUN_AS_NODE
139
+ // 跑在 ZCode.exe 镜像下时进程名同为 ZCode.exe,不排除会恒判“已在运行”)
140
+ const out = execSync('tasklist /FI "IMAGENAME eq ZCode.exe" /NH', { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
141
+ return out.split(/\r?\n/).some((line) => {
142
+ const m = /^\S+\s+(\d+)/.exec(line.trim());
143
+ return !!m && Number(m[1]) !== process.pid;
144
+ });
127
145
  }
128
146
  const out = execSync('pgrep -x zcode 2>/dev/null || true', { encoding: 'utf8' });
129
147
  const pids = out.split('\n').map((s) => s.trim()).filter((s) => /^\d+$/.test(s));
@@ -144,6 +162,11 @@ function launchZcode(exe, cdpPort, verbose) {
144
162
  stdio: 'ignore',
145
163
  env,
146
164
  });
165
+ // spawn 失败(可执行文件损坏/无权限等)走 error 事件:不监听会变成未处理错误把启动器炸掉
166
+ child.on('error', (err) => {
167
+ winLog('启动 ZCode 失败: ' + err.message);
168
+ console.error('[zcodepro] 启动 ZCode 失败: ' + err.message);
169
+ });
147
170
  child.unref();
148
171
  if (verbose) console.log(`[zcodepro] 已启动 ZCode (pid=${child.pid}),调试端口 ${cdpPort}`);
149
172
  }
@@ -166,18 +189,135 @@ const SANDBOX_STYLE_SCRIPT = `(() => {
166
189
  (document.head || document.documentElement).append(s);
167
190
  })();`;
168
191
 
169
- async function buildInjectSource(token, helperPort, features, zcodeVersion) {
192
+ // file:// 页面的注入范围:只放行 ZCode 安装目录下的页面,防止含 helper token 的
193
+ // 引导脚本进任意本地 HTML。允许的前缀有三个来源:启动 exe 所在目录;exe 真实
194
+ // 路径所在目录(经符号链接启动时应用 UI 走真实路径);macOS 应用包的
195
+ // Contents/Resources(exe 在 Contents/MacOS 里、UI 在 Resources 里,不同目录)。
196
+ // 前缀归一成 file URL 的 pathname 形式做比较(盘符路径补前导 /、反斜杠换 /),
197
+ // exe 路径带盘符(Windows)时大小写不敏感。
198
+ // 取舍:从源码目录直接跑的 ZCode(dev 布局)不在这些前缀下会失去注入,届时再加配置。
199
+ function installDirFromExe(exePath) {
200
+ const prefixes = [];
201
+ const add = (dir) => {
202
+ const norm = /^[A-Za-z]:[\\/]/.test(dir) ? '/' + dir.replace(/\\/g, '/') : dir;
203
+ if (!prefixes.includes(norm)) prefixes.push(norm);
204
+ };
205
+ const dir = dirname(resolve(exePath));
206
+ add(dir);
207
+ try { add(dirname(realpathSync(exePath))); } catch { /* 路径不可解析就只用字面前缀 */ }
208
+ for (let d = dir, i = 0; i < 4; i++) {
209
+ if (/\.app$/i.test(d)) { add(join(d, 'Contents', 'Resources')); break; }
210
+ const up = dirname(d);
211
+ if (up === d) break;
212
+ d = up;
213
+ }
214
+ // macOS 的 APFS 默认大小写不敏感,前缀比较同样放宽大小写
215
+ return { prefixes, ci: process.platform === 'darwin' || prefixes.some((p) => /^\/[A-Za-z]:/.test(p)) };
216
+ }
217
+
218
+ // file:// 路径归一(宿主侧与页面侧护栏同一算法):decodeURI 不解码 %2f/%5c,
219
+ // 也不折叠 .. 段,先把 %2f/%5c(大小写不敏感)与字面反斜杠统一成 /,再做词法段
220
+ // 折叠(消掉 . 与 .. 段,等价 path.posix.normalize;页面侧是注入字符串,用原生
221
+ // JS 实现同一套,不引依赖),否则 ..%5c..%5c 之类编码分隔符能绕过前缀匹配
222
+ function normFileUrlPath(p) {
223
+ const s = String(p).replace(/%2f/gi, '/').replace(/%5c/gi, '/').replace(/\\/g, '/');
224
+ const abs = s.startsWith('/');
225
+ const out = [];
226
+ for (const seg of s.split('/')) {
227
+ if (!seg || seg === '.') continue;
228
+ if (seg === '..') {
229
+ if (out.length && out[out.length - 1] !== '..') out.pop();
230
+ else if (!abs) out.push('..'); // 相对路径回溯段保留,语义同 path.posix.normalize
231
+ continue;
232
+ }
233
+ out.push(seg);
234
+ }
235
+ return (abs ? '/' : '') + out.join('/');
236
+ }
237
+
238
+ // file:// URL 是否落在任一安装目录前缀下:与页面侧护栏同款比较,比较前先解码
239
+ // URL 路径(页面侧是 decodeURI(location.pathname))并按 normFileUrlPath 归一。
240
+ // URL 解析失败按不放行处理;
241
+ // 路径里孤立的 % 会让 decodeURI 抛错,这时退回原始路径比较——前缀不含 % 时仍能匹配
242
+ function fileUrlUnderInstall(fileUrl, installDir) {
243
+ let p;
244
+ try {
245
+ const raw = new URL(fileUrl).pathname;
246
+ try { p = decodeURI(raw); } catch { p = raw; }
247
+ } catch { return false; }
248
+ p = normFileUrlPath(p);
249
+ if (installDir.ci) p = p.toLowerCase();
250
+ return installDir.prefixes.some((raw) => {
251
+ const pre = installDir.ci ? raw.toLowerCase() : raw;
252
+ return p === pre || p.indexOf(pre.endsWith('/') ? pre : pre + '/') === 0;
253
+ });
254
+ }
255
+
256
+ // 可注入判定:引导脚本内含 helper 鉴权 token,只能进 ZCode 应用自身的页面。
257
+ // 规则:http(s) 只放行本机回环地址;file:// 只放行 ZCode 安装目录下的页面
258
+ //(应用 UI 在 <安装目录>/resources/app.asar/ 里);拦截外部网页与
259
+ // data/blob/view-source/about 子文档,沙箱页同样不带 token;应用自有协议
260
+ // 维持放行。refreshInjectScripts 重注册时目标可能已导航离开应用页,需重跑同款判定
261
+ export function isInjectableAppPage(url, installDir) {
262
+ const u = String(url || '');
263
+ if (/^zcode-sandbox:\/\//i.test(u)) return false;
264
+ if (/^https?:\/\//i.test(u) && !/^https?:\/\/(127\.0\.0\.1|localhost)(:\d+)?(\/|$|\?|#)/i.test(u)) return false;
265
+ if (/^(data|blob|view-source|about):/i.test(u)) return false;
266
+ // file: 不带双斜杠的形态(file:/etc/…)也要过前缀校验,别落到末尾的放行
267
+ if (/^file:/i.test(u)) return fileUrlUnderInstall(u, installDir);
268
+ return true;
269
+ }
270
+
271
+ // token 护栏做成运行时自检:attach 时判定 URL 挡不住“空白初页 → 导航去沙箱/外网”
272
+ // 的目标(引导脚本会随 addScript 落进该会话之后的每个文档)。每文档执行时看真实
273
+ // href,沙箱/外链页面整段跳过,token 不出应用页;空白文档也跳过(真应用文档会
274
+ // 以自己的 URL 再触发一次钩子)。file:// 只放行 ZCode 安装目录下的页面(应用 UI
275
+ // 在 <安装目录>/resources/app.asar/ 里,必须继续放行),否则含 token 的引导脚本
276
+ // 会进任意本地 HTML。护栏是注入进页面的字符串,安装目录前缀(含符号链接真实
277
+ // 路径与 macOS 应用包 Resources,见 installDirFromExe)在宿主侧构造时写进下面的
278
+ // 字符串;页面侧比较前先 decodeURI(location.pathname) 并按 normFileUrlPath 同款
279
+ // 算法归一(编码分隔符与 .. 段折叠,两侧行为必须一致),exe 路径带盘符
280
+ //(Windows)时大小写不敏感
281
+ export function buildGuard(installDir) {
282
+ return `if ((function () {
283
+ var h = location.href;
284
+ if (/^(zcode-sandbox|about|data|blob|view-source):/i.test(h)) return false;
285
+ if (/^https?:\\/\\//i.test(h)) return /^https?:\\/\\/(127\\.0\\.0\\.1|localhost)(:\\d+)?(\\/|$|\\?|#)/i.test(h);
286
+ if (/^file:\\/\\//i.test(h)) {
287
+ var raw = location.pathname, p;
288
+ try { p = decodeURI(raw); } catch (e) { p = raw; }
289
+ p = p.replace(/%2f/gi, '/').replace(/%5c/gi, '/').replace(/\\\\/g, '/');
290
+ var abs = p.charAt(0) === '/', segs = p.split('/'), out = [], j, seg;
291
+ for (j = 0; j < segs.length; j++) {
292
+ seg = segs[j];
293
+ if (seg === '' || seg === '.') continue;
294
+ if (seg === '..') {
295
+ if (out.length && out[out.length - 1] !== '..') out.pop();
296
+ else if (!abs) out.push('..');
297
+ continue;
298
+ }
299
+ out.push(seg);
300
+ }
301
+ p = (abs ? '/' : '') + out.join('/');
302
+ var pres = ${JSON.stringify(installDir.prefixes)};
303
+ ${installDir.ci ? 'p = p.toLowerCase();' : ''}
304
+ for (var i = 0; i < pres.length; i++) {
305
+ var pre = ${installDir.ci ? 'pres[i].toLowerCase()' : 'pres[i]'};
306
+ if (p === pre || p.indexOf(pre.endsWith('/') ? pre : pre + '/') === 0) return true;
307
+ }
308
+ return false;
309
+ }
310
+ return true;
311
+ })()) {`;
312
+ }
313
+
314
+ async function buildInjectSource(token, helperPort, features, zcodeVersion, installDir) {
170
315
  if (!existsSync(INJECT_BUNDLE)) {
171
316
  throw new Error('缺少注入脚本 dist/inject.js,请先运行 npm run build');
172
317
  }
173
318
  const bundle = readFileSync(INJECT_BUNDLE, 'utf8');
174
319
  const bootstrap = `window.__ZCODEPRO__={helperUrl:'http://127.0.0.1:${helperPort}',token:${JSON.stringify(token)},features:${JSON.stringify(features)},zcodeVersion:${JSON.stringify(zcodeVersion || '')}};`;
175
- // token 护栏做成运行时自检:attach 时判定 URL 挡不住“空白初页 → 导航去沙箱/外网”
176
- // 的目标(引导脚本会随 addScript 落进该会话之后的每个文档)。每文档执行时看真实
177
- // href,沙箱/外链页面整段跳过,token 不出应用页;空白文档也跳过(真应用文档会
178
- // 以自己的 URL 再触发一次钩子)
179
- const guard = 'if (!/^(zcode-sandbox|about|data|blob|view-source):/i.test(location.href) && !(/^https?:\\/\\//i.test(location.href) && !/^https?:\\/\\/(127\\.0\\.0\\.1|localhost)(:\\d+)?(\\/|$|\\?|#)/i.test(location.href))) {';
180
- return guard + bootstrap + '\n' + bundle + '\n}';
320
+ return buildGuard(installDir) + bootstrap + '\n' + bundle + '\n}';
181
321
  }
182
322
 
183
323
  export async function run(argv) {
@@ -187,12 +327,14 @@ export async function run(argv) {
187
327
  return;
188
328
  }
189
329
  const args = parseArgs(argv);
190
- if (args.help) { console.log(usage()); return; }
330
+ // 参数错误按失败退出(脚本调用方靠退出码判断);单纯 --help 仍退出码 0
331
+ if (args.help) { console.log(usage()); process.exitCode = args.bad ? 1 : 0; return; }
191
332
  // setup 不依赖 ZCode 运行(装快捷方式等本机集成),先于 ZCode 定位处理
192
333
  if (args.setup || args.setupUninstall || args.setupDesktop) {
193
334
  if (!args.setup && (args.setupUninstall || args.setupDesktop)) {
194
335
  console.error('未知用法: --uninstall / --desktop 仅可与 setup 连用');
195
336
  console.log(usage());
337
+ process.exitCode = 1;
196
338
  return;
197
339
  }
198
340
  await runSetup({ uninstall: args.setupUninstall, desktop: args.setupDesktop });
@@ -211,6 +353,7 @@ export async function run(argv) {
211
353
  }
212
354
  throw err;
213
355
  }
356
+ const installDir = installDirFromExe(exe); // file:// 页面注入范围(见 installDirFromExe 注释)
214
357
  winLog(`启动: ZCode=${exe}, CDP 端口 ${args.cdpPort}`);
215
358
  const zcodeVersion = readZcodeVersion(exe);
216
359
  if (args.verbose) console.log(`[zcodepro] ZCode 版本: ${zcodeVersion || '未知(app.asar 读取失败)'}`);
@@ -246,11 +389,28 @@ export async function run(argv) {
246
389
  }
247
390
 
248
391
  // 2. 启动辅助服务
249
- const server = await startHelper({ port: args.helperPort, token, dataRoot, state, zcodeVersion });
392
+ const helperArgs = { port: args.helperPort, token, dataRoot, state, zcodeVersion };
393
+ let helperMod = helperModule; // 当前在服的 helper 模块实例(热替换后指新实例)
394
+ let server = await helperModule.startHelper(helperArgs);
250
395
  console.log(`[zcodepro] 辅助服务已就绪: http://127.0.0.1:${args.helperPort} (数据目录 ${dataRoot})`);
251
396
 
252
397
  // 3. 连接 CDP 并注入(断线自动重连)
253
398
  const injectedTargets = new Map(); // targetId -> sessionId
399
+ const scriptIds = new Map(); // targetId -> 新文档脚本 identifier 集合(含没删掉的旧注册)
400
+ // identifier 记录逐个增删(追加去重,删除只动命中的那个):同一 target 一轮
401
+ // 连接内可能二次 attached(跨进程导航、渲染进程切换),refresh 的 remove/add
402
+ // 之间 handleAttach 也可能合进新注册——整组覆盖会把没删掉或刚合进来的
403
+ // identifier 冲掉,那份注册就永远删不掉,页面每次刷新多跑一份注入包
404
+ const noteScriptId = (targetId, id) => {
405
+ const ids = scriptIds.get(targetId) || new Set();
406
+ ids.add(id);
407
+ scriptIds.set(targetId, ids);
408
+ };
409
+ let registeredSource = ''; // 已注册的注入包(内容没变不重复注册)
410
+ let refreshPending = false; // 有页面重注册失败待重试:期间 handleAttach 不推进已注册标记
411
+ let lastRefreshError = ''; // 重注册错误日志按内容去重
412
+ let refreshSkip = 0; // 失败后的退避周期数:单页持续失败时别每 3 秒全量重试
413
+ let lastTriedSource = null; // 上次尝试重注册的包:包又变了就立即重试,不受退避限制
254
414
  let stopping = false;
255
415
 
256
416
  let healthRes;
@@ -262,12 +422,40 @@ export async function run(argv) {
262
422
  server.close();
263
423
  process.exit(1);
264
424
  }
265
- const source = await buildInjectSource(token, args.helperPort, healthRes.features || {}, zcodeVersion);
425
+ // 注入包按 mtime+size 缓存:npm run build 之后不用重启启动器——已打开页面
426
+ // 下次“调试-重新加载”、新页面首次注入都直接吃新构建的包。
427
+ // shortcut: 同一毫秒内改写成相同字节数的内容检测不到,构建产物几乎不会出现,
428
+ // 如真遇到可把缓存键换成内容哈希
429
+ const injectCache = { mtime: 0, size: 0, source: '' };
430
+ async function getInjectSource() {
431
+ let mtime = -1;
432
+ let size = -1;
433
+ try { const st = statSync(INJECT_BUNDLE); mtime = st.mtimeMs; size = st.size; } catch { /* 缺失/读失败:沿用旧包 */ }
434
+ // 包内容没变直接用缓存(mtime+size 双键防粗粒度文件系统漏检);
435
+ // 构建间隙文件暂时缺失也沿用旧包
436
+ if (injectCache.source && (mtime < 0 || (mtime === injectCache.mtime && size === injectCache.size))) return injectCache.source;
437
+ const built = await buildInjectSource(token, args.helperPort, healthRes.features || {}, zcodeVersion, installDir);
438
+ // 读取前后各 stat 一次对比:esbuild 正在写文件时可能读到半截包,
439
+ // 半截内容不能进缓存(会一直被 mtime+size 命中),沿用旧包等下一轮
440
+ let torn = true;
441
+ try { const st2 = statSync(INJECT_BUNDLE); torn = st2.mtimeMs !== mtime || st2.size !== size; } catch { /* 读取中被删也算撕裂 */ }
442
+ if (torn) {
443
+ if (injectCache.source) return injectCache.source;
444
+ throw new Error('dist/inject.js 正在写入,本轮跳过');
445
+ }
446
+ injectCache.source = built;
447
+ injectCache.mtime = mtime;
448
+ injectCache.size = size;
449
+ return injectCache.source;
450
+ }
451
+ await getInjectSource(); // 启动即构建一次:缺 dist/inject.js 尽早报错
266
452
 
267
453
  async function attachConnection() {
268
454
  const conn = new CdpConnection(await fetchBrowserWsUrl(args.cdpPort));
269
455
  await conn.connect();
270
456
  injectedTargets.clear();
457
+ scriptIds.clear();
458
+ refreshPending = false; // 失败待重试的页面随旧会话消亡,重连后 handleAttach 全量注册
271
459
 
272
460
  const handleAttach = async (sessionId, targetInfo) => {
273
461
  const targetId = targetInfo?.targetId;
@@ -297,26 +485,36 @@ export async function run(argv) {
297
485
  return;
298
486
  }
299
487
  if (targetInfo?.type !== 'page') return;
300
- // 安全护栏:引导脚本内含 helper 鉴权 token,只能注入 ZCode 应用自身的页面。
301
- // 外部网站若以内嵌浏览器/网页形式成为 page target,拿到 token 即可调用本地
302
- // helper(改写增强配置/别名表等)。规则:放行非 http(s)(file://、应用自有协议)与
303
- // 本机回环地址,拦截其余外部网页。代价是 http(s) 非 localhost 的自有页面不注入。
304
- const isExternalWeb = (/^https?:\/\//i.test(pageUrl) && !/^https?:\/\/(127\.0\.0\.1|localhost)(:\d+)?(\/|$|\?|#)/i.test(pageUrl))
305
- || /^(data|blob|view-source|about):/i.test(pageUrl); // 非 http 协议的子文档也能拿 token,一并跳过
306
- if (isExternalWeb) {
488
+ // 安全护栏:只注入应用自身页面(判定规则集中在 isInjectableAppPage,
489
+ // 重注册时会再跑一遍)
490
+ if (!isInjectableAppPage(pageUrl, installDir)) {
307
491
  log('跳过外部页面注入(防止 token 泄露): ' + pageUrl.slice(0, 120));
308
492
  return;
309
493
  }
494
+ // 取包失败(构建写入中、杀软锁文件)回退上一份包:旧包比没包好,
495
+ // 下轮 refreshInjectScripts 自然换成新包
496
+ let source = injectCache.source;
497
+ try {
498
+ source = await getInjectSource();
499
+ } catch (err) {
500
+ if (!source) { log('注入包读取失败且无缓存,跳过本页: ' + err.message); return; }
501
+ }
310
502
  try {
311
503
  await conn.send('Page.enable', {}, sessionId);
312
- await conn.send('Page.addScriptToEvaluateOnNewDocument', { source, runImmediately: true }, sessionId);
504
+ const added = await conn.send('Page.addScriptToEvaluateOnNewDocument', { source, runImmediately: true }, sessionId);
505
+ if (added && added.identifier) noteScriptId(targetId, added.identifier);
313
506
  const res = await conn.send('Runtime.evaluate', { expression: source, silent: true }, sessionId);
314
507
  if (res?.exceptionDetails) log('注入执行异常: ' + String(res.exceptionDetails.exception?.description || '').slice(0, 200));
508
+ // 只有首个页面(没有旧页面挂着旧包)、拿到的仍是当前包、且没有待重试的
509
+ // 重注册才记已注册标记:其余情况由 refreshInjectScripts 统一推进,
510
+ // 避免新页面注入把标记推到新包、旧页面却永远停在旧包
511
+ if (!refreshPending && source === injectCache.source && injectedTargets.size === 0) registeredSource = source;
315
512
  injectedTargets.set(targetId, sessionId);
316
513
  state.injectedPages = injectedTargets.size;
317
514
  conn.onSession(sessionId, (m) => {
318
515
  if (m.type === 'detached') {
319
516
  injectedTargets.delete(targetId);
517
+ scriptIds.delete(targetId);
320
518
  state.injectedPages = injectedTargets.size;
321
519
  }
322
520
  });
@@ -353,17 +551,157 @@ export async function run(argv) {
353
551
  console.log('[zcodepro] 已连接 CDP 并开始注入。保持本进程运行以维持增强;Ctrl+C 退出(不影响 ZCode)。');
354
552
  winLog('已连接 CDP 并开始注入');
355
553
 
356
- process.on('SIGINT', () => { stopping = true; try { conn.close(); } catch {} server.close(); process.exit(0); });
357
- process.on('SIGTERM', () => { stopping = true; try { conn.close(); } catch {} server.close(); process.exit(0); });
554
+ process.on('SIGINT', () => { stopping = true; try { conn.close(); } catch {} try { helperMod.dispose?.(); } catch {} server.close(); process.exit(0); });
555
+ process.on('SIGTERM', () => { stopping = true; try { conn.close(); } catch {} try { helperMod.dispose?.(); } catch {} server.close(); process.exit(0); });
556
+
557
+ // dist/inject.js 变更后把各页面的新文档脚本换成新包:已打开页面不打断,
558
+ // 下次“调试-重新加载”即跑新代码(新页面首次注入本来就是新包)
559
+ async function refreshInjectScripts() {
560
+ if (!conn || conn.closed) return; // 断连时注册会失败、日志也记不准,跳过;重连后 handleAttach 全量注册
561
+ let source;
562
+ try {
563
+ source = await getInjectSource();
564
+ } catch (err) {
565
+ // 读失败也按内容去重:构建产物损坏又没有新 mtime 时别每 3 秒刷一行
566
+ const msg = '注入包读取失败: ' + err.message;
567
+ if (msg !== lastRefreshError) { lastRefreshError = msg; console.error('[zcodepro] ' + msg); winLog(msg); }
568
+ return;
569
+ }
570
+ if (source === registeredSource) return; // 包内容没变就不重新注册
571
+ if (refreshSkip > 0 && source === lastTriedSource) { refreshSkip--; return; }
572
+ lastTriedSource = source;
573
+ let want = 0;
574
+ let ok = 0;
575
+ let done = true;
576
+ // 整轮时间预算:多页半死(每次 send 各带 30 秒超时)时别把重连检测拖后几十秒
577
+ const deadline = Date.now() + 20_000;
578
+ for (const [targetId, sessionId] of injectedTargets) {
579
+ if (Date.now() > deadline) { done = false; break; } // 没轮到的页面留在旧包,下轮续
580
+ // 目标可能在注入后导航去外部页面/沙箱:重注册前重跑同款可注入判定,
581
+ // 否则含 token 的脚本串会注册进外部页面的会话(执行层虽有护栏兜底)
582
+ try {
583
+ const href = await conn.send('Runtime.evaluate', { expression: 'location.href', returnByValue: true, silent: true }, sessionId);
584
+ if (!isInjectableAppPage(String((href && href.result && href.result.value) || ''), installDir)) {
585
+ // 踢出前尽力移除已注册脚本:别把带 token 的注册留在外部页面的会话里
586
+ for (const id of scriptIds.get(targetId) || []) {
587
+ try { await conn.send('Page.removeScriptToEvaluateOnNewDocument', { identifier: id }, sessionId); } catch { /* ignore */ }
588
+ }
589
+ injectedTargets.delete(targetId);
590
+ scriptIds.delete(targetId);
591
+ state.injectedPages = injectedTargets.size;
592
+ continue;
593
+ }
594
+ } catch {
595
+ // 取不到当前 URL 就不注册(宁可少注入,不把 token 注给未知页面),但要
596
+ // 计入 want 让重试机制接管:否则全卡在这条时空集“全部成功”会误推进标记
597
+ want++;
598
+ continue;
599
+ }
600
+ want++;
601
+ // 旧注册逐个移除:只把移除成功的 identifier 从记录里删掉,没删掉的留下轮
602
+ // 继续删。遍历的是快照——remove/add 之间的 await 里 handleAttach 可能合进
603
+ // 新注册,新注册不能当旧的删。删失败不能连累 add,否则该页没有新文档脚本,
604
+ // 增强静默消失
605
+ const oldIds = [...(scriptIds.get(targetId) || [])];
606
+ for (const id of oldIds) {
607
+ try {
608
+ await conn.send('Page.removeScriptToEvaluateOnNewDocument', { identifier: id }, sessionId);
609
+ scriptIds.get(targetId)?.delete(id);
610
+ } catch { /* 删失败留记录,下轮继续删 */ }
611
+ }
612
+ try {
613
+ // runImmediately: false——只对下次新文档生效,不碰当前页面(用户按需刷新)
614
+ const added = await conn.send('Page.addScriptToEvaluateOnNewDocument', { source, runImmediately: false }, sessionId);
615
+ if (added && added.identifier) noteScriptId(targetId, added.identifier);
616
+ ok++;
617
+ } catch { /* 页面已关闭/会话失效:重连后 handleAttach 会重新注册 */ }
618
+ }
619
+ // 全部成功才推进已注册标记:有失败或中途超预算就保留旧值,下一轮继续重试
620
+ if (done && ok === want) {
621
+ registeredSource = source;
622
+ refreshPending = false;
623
+ lastRefreshError = '';
624
+ refreshSkip = 0;
625
+ if (ok) console.log(`[zcodepro] 注入包已更新,${ok} 个页面下次“调试-重新加载”时生效`);
626
+ } else {
627
+ refreshPending = true;
628
+ refreshSkip = 2; // 约 9 秒后再试;期间构建了新包会立即重试
629
+ // 错误按内容去重:单页永久失败时别每 3 秒刷一行
630
+ const msg = `注入包重注册部分失败(成功 ${ok}/${want}),下轮重试`;
631
+ if (msg !== lastRefreshError) { lastRefreshError = msg; console.error('[zcodepro] ' + msg); winLog(msg); }
632
+ }
633
+ }
634
+
635
+ // helper.mjs 变更时热替换辅助服务:先导入新模块(语法错在这里抛出、旧服务
636
+ // 不动),再关旧起新。每次热替换都是全新模块实例,helper 模块级状态
637
+ //(rollout 解析缓存等)从零开始。shortcut: 只覆盖 helper.mjs
638
+ // 自身,它的依赖(settings.mjs、taskIndex.mjs 等)与 main.mjs 的改动仍需重启启动器
639
+ const helperStamp = () => {
640
+ try { const st = statSync(join(here, 'helper.mjs')); return st.mtimeMs + ':' + st.size; } catch { return ''; }
641
+ };
642
+ let helperTriedSig = helperStamp(); // 上次尝试过的文件签名(mtime+size 双键):
643
+ // 同一份代码只试一次,失败等保存出新签名再试——别每 3 秒掐一次服务重试同一份坏代码
644
+ const swapRetry = { sig: '', n: 0 }; // 服务起不来时同一份代码的重试次数(上限 3)
645
+ let swapLastError = '';
646
+ async function maybeSwapHelper() {
647
+ const sig = helperStamp();
648
+ if (!sig || sig === helperTriedSig) return;
649
+ // 有后台任务在跑就延后换:新模块实例不继承任务锁,会跟旧实例拉起的
650
+ // 子进程(插件更新/转码等)并发;不记 triedSig,任务完成自动再试
651
+ if (helperMod && typeof helperMod.busyJobs === 'function' && helperMod.busyJobs()) return;
652
+ try {
653
+ const mod = await import('./helper.mjs?mtime=' + sig);
654
+ if (typeof mod.startHelper !== 'function') throw new Error('helper.mjs 没有导出 startHelper');
655
+ // import 让出过事件循环,期间旧服务可能刚接到请求起了后台任务(转码等):
656
+ // 关旧服务前补查一次。检查与关闭之间没有 await,不会再有新任务挤进来
657
+ if (helperMod && typeof helperMod.busyJobs === 'function' && helperMod.busyJobs()) return;
658
+ try { helperMod.dispose?.(); } catch { /* ignore */ } // 旧实例被 ESM 缓存持有,清大块缓存省内存
659
+ // 不等优雅关闭:渲染进程的 keep-alive/在途请求(每 2 秒轮询)会让 close
660
+ // 回调迟迟不来,直接掐掉存量连接。热替换是开发场景,容忍个别请求中断
661
+ //(前端轮询失败会保旧值,下个周期自动恢复)
662
+ server.close();
663
+ server.closeAllConnections();
664
+ // listenTries 传小值:端口被占别把主循环卡在 startHelper 的重试里
665
+ server = await mod.startHelper({ ...helperArgs, listenTries: 6 });
666
+ helperMod = mod;
667
+ helperTriedSig = sig;
668
+ swapLastError = '';
669
+ console.log('[zcodepro] helper.mjs 有改动,辅助服务已热替换(无需重启启动器)');
670
+ } catch (err) {
671
+ helperTriedSig = sig; // 失败也记签名
672
+ // 同一错误只报一次:连续多次保存出同一个错时别刷屏
673
+ if (err.message !== swapLastError) {
674
+ swapLastError = err.message;
675
+ const stateText = server.listening ? '保持旧服务,改好保存后自动重试' : '服务已中断,尝试拉回旧版';
676
+ console.error(`[zcodepro] helper 热替换失败(${stateText}): ` + err.message);
677
+ winLog('helper 热替换失败: ' + err.message);
678
+ }
679
+ if (!server.listening) {
680
+ // 新服务没起来(端口被占、启动抛错):用上一个在服的模块实例把服务拉回来
681
+ let recovered = false;
682
+ try { server = await helperMod.startHelper({ ...helperArgs, listenTries: 6 }); recovered = true; } catch { /* 旧的也起不来 */ }
683
+ // 没服务或端口瞬时占用才清签名下轮重试;代码本身的错等文件再变
684
+ if (!recovered || /EADDRINUSE/.test(String(err.message))) {
685
+ // 服务不在或端口瞬时占用才重试,同一份代码最多 3 次:每次重试都占
686
+ // 一段 listen 重试窗口,无限重试会把主循环拖慢
687
+ if (swapRetry.sig !== sig) { swapRetry.sig = sig; swapRetry.n = 0; }
688
+ if (swapRetry.n < 3) { swapRetry.n += 1; helperTriedSig = ''; }
689
+ }
690
+ }
691
+ }
692
+ }
358
693
 
359
694
  while (!stopping) {
360
695
  await sleep(3000);
361
696
  if (stopping) break;
697
+ await refreshInjectScripts();
698
+ await maybeSwapHelper();
362
699
  if (!conn.closed) continue;
363
700
  // 连接断开:ZCode 退出则一并退出,否则重连
364
701
  if (!(await cdpAlive(args.cdpPort))) {
365
702
  console.log('[zcodepro] ZCode 已退出,zcodepro 一并退出。');
366
703
  winLog('ZCode 已退出,zcodepro 一并退出');
704
+ try { helperMod.dispose?.(); } catch { /* ignore */ } // 收掉残留 ffmpeg 子进程
367
705
  server.close();
368
706
  process.exit(0);
369
707
  }
@@ -1,18 +1,20 @@
1
1
  // 跨平台定位 ZCode 桌面版可执行文件。
2
2
  // 优先级:--zcode-path 参数 > ZCODEPRO_ZCODE_PATH 环境变量(进程 > 用户注册表) >
3
3
  // 平台默认候选路径 > 注册表 App Paths/卸载表(Windows) > PATH 上的 zcode。
4
- import { existsSync } from 'node:fs';
4
+ import { accessSync, constants as fsConstants, statSync } from 'node:fs';
5
5
  import { join } from 'node:path';
6
- import { arch, homedir, platform } from 'node:os';
6
+ import { homedir, platform } from 'node:os';
7
7
  import { execFileSync } from 'node:child_process';
8
8
 
9
- // reg 输出按行取 REG_SZ 后的值,容忍引号与 ",0" 图标序号后缀。
9
+ // reg 输出按行取 REG_SZ / REG_EXPAND_SZ 后的值,容忍引号与 ",0" 图标序号后缀;
10
+ // REG_EXPAND_SZ 的 %VAR% 按当前环境变量展开(cmd 入口的同款兜底也认这种形态)
10
11
  const reg = (args) => {
11
12
  try {
12
13
  return execFileSync('reg', args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
13
14
  } catch { return ''; }
14
15
  };
15
- const valueAfter = (out) => (out.split(/REG_SZ\s+/)[1] || '').trim();
16
+ const valueAfter = (out) => (out.split(/REG_(?:EXPAND_)?SZ\s+/)[1] || '').trim()
17
+ .replace(/%([^%]+)%/g, (m, name) => process.env[name] || m);
16
18
 
17
19
  // 安装脚本 -ZCodePath 持久化的用户级环境变量(HKCU\Environment):写入后不会传播
18
20
  // 到已运行的资源管理器,进程环境变量读不到时从这里兜底,免注销/重启(issue #1)。
@@ -36,6 +38,7 @@ function windowsRegistryCandidates() {
36
38
  seen.add(p.toLowerCase());
37
39
  winRegistryCandidates.push(p);
38
40
  }
41
+ return p;
39
42
  };
40
43
  // App Paths:安装器注册的可执行文件全路径(ShellExecute 同款查找)
41
44
  for (const root of ['HKLM', 'HKCU']) {
@@ -54,10 +57,12 @@ function windowsRegistryCandidates() {
54
57
  ]) {
55
58
  const out = reg(['query', key, '/s', '/v', 'DisplayIcon']);
56
59
  for (const line of out.split(/\r?\n/)) {
57
- const seg = (line.split(/REG_SZ\s+/)[1] || '').trim();
60
+ const seg = (line.split(/REG_(?:EXPAND_)?SZ\s+/)[1] || '').trim();
58
61
  if (seg && /zcode/i.test(seg)) {
59
- push(seg);
60
- const dir = seg.replace(/[^\\\/]+$/, '');
62
+ // 目录推导要用去引号去 ",0" 的干净路径:带引号的 DisplayIcon
63
+ //(Inno 类安装器常见 "...\app.exe",0)不然推出的候选带多余引号
64
+ const clean = push(seg);
65
+ const dir = clean.replace(/[^\\\/]+$/, '');
61
66
  if (dir) {
62
67
  push(join(dir, 'ZCode.exe'));
63
68
  push(join(dir, 'zcode.exe'));
@@ -97,7 +102,6 @@ function candidates() {
97
102
  '/usr/local/ZCode/zcode',
98
103
  join(home, '.local', 'share', 'zcode', 'zcode'),
99
104
  ];
100
- if (arch() === 'arm64') list.unshift('/opt/ZCode/zcode'); // AUR aarch64 同路径
101
105
  return list;
102
106
  }
103
107
 
@@ -107,7 +111,11 @@ export function resolveZcodeExecutable(explicit) {
107
111
  if (!p) return null;
108
112
  tried.push(p);
109
113
  try {
110
- if (existsSync(p)) return p;
114
+ // 只认可执行的普通文件:名为 ZCode.exe 的目录会被 existsSync 误判成命中
115
+ const st = statSync(p);
116
+ if (!st.isFile()) return null;
117
+ if (platform() !== 'win32') accessSync(p, fsConstants.X_OK); // POSIX 上还要可执行
118
+ return p;
111
119
  } catch { /* ignore */ }
112
120
  return null;
113
121
  };
@@ -4,7 +4,7 @@
4
4
 
5
5
  import { spawn, spawnSync } from 'node:child_process';
6
6
  import { existsSync, statSync } from 'node:fs';
7
- import { dirname } from 'node:path';
7
+ import { dirname, isAbsolute } from 'node:path';
8
8
 
9
9
  // kdialog(KDE 原生):起始目录参数可靠生效。
10
10
  // xdg-desktop-portal-kde 不读 current_folder 选项(二进制中无该字符串),
@@ -126,7 +126,9 @@ function portalPickFolder(startDir, title, timeoutMs) {
126
126
  const call = spawnSync('gdbus', ['call', '--session', '--dest', 'org.freedesktop.portal.Desktop',
127
127
  '--object-path', '/org/freedesktop/portal/desktop',
128
128
  '--method', 'org.freedesktop.portal.FileChooser.OpenFile', '', title, opts], { encoding: 'utf8' });
129
- if (call.status !== 0 || !/object path/i.test((call.stdout || '') + (call.stderr || ''))) finish(undefined);
129
+ // gdbus 的 GVariant 文本输出写作 objectpath(无空格),旧版按 "object path"
130
+ // 匹配永远判失败;两种写法都认
131
+ if (call.status !== 0 || !/object ?path/i.test((call.stdout || '') + (call.stderr || ''))) finish(undefined);
130
132
  });
131
133
 
132
134
  timer = setTimeout(() => finish(null), timeoutMs);
@@ -175,13 +177,18 @@ function powershellPickFolder(startDir, title, timeoutMs = 600000) {
175
177
 
176
178
  export async function pickFolderSystem(startDir, title, timeoutMs = 180000) {
177
179
  const dialogTitle = title || '选择文件夹';
180
+ // 起始目录只接受绝对路径:相对路径(尤其以 -- 开头的)会被 kdialog 当成命令行
181
+ // 选项;不合法就不作起始目录——Windows 忽略预选(对话框自行落到默认位置),
182
+ // Linux 退回默认目录
183
+ const rawStart = String(startDir || '');
184
+ const startArg = rawStart && isAbsolute(rawStart) ? rawStart : '';
178
185
  if (process.platform === 'win32') {
179
- const r = await powershellPickFolder(String(startDir || ''), dialogTitle, timeoutMs);
186
+ const r = await powershellPickFolder(startArg, dialogTitle, timeoutMs);
180
187
  if (r !== undefined) return { path: r };
181
188
  return { unavailable: true };
182
189
  }
183
190
  if (process.platform !== 'linux') return { unavailable: true };
184
- const start = firstExistingDir(String(startDir || '/'));
191
+ const start = firstExistingDir(startArg || '/');
185
192
  if (kdialogAvailable()) {
186
193
  const r = await kdialogPickFolder(start, dialogTitle);
187
194
  if (r !== undefined) return { path: r };