zcode-pro 1.7.0 → 1.8.1

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.
@@ -0,0 +1,68 @@
1
+ // dsh 的会话文件由多个 zstd frame 追加写而成。Node 自带的 zstdDecompress 只解
2
+ // 第一个 frame,这里按帧头切分后逐个解压,再按顺序拼起来。
3
+ import * as zlib from 'node:zlib';
4
+
5
+ const { zstdDecompressSync } = zlib;
6
+
7
+ const ZSTD_MAGIC = 0xfd2fb528;
8
+ const SKIPPABLE_MASK = 0xfffffff0;
9
+ const SKIPPABLE_MAGIC = 0x184d2a50;
10
+
11
+ function frameEnd(buf, off) {
12
+ if (off + 4 > buf.length) throw new Error('zstd 文件被截断');
13
+ let p = off;
14
+ const magic = buf.readUInt32LE(p);
15
+ p += 4;
16
+ if ((magic & SKIPPABLE_MASK) === SKIPPABLE_MAGIC) {
17
+ if (p + 4 > buf.length) throw new Error('zstd 跳过帧被截断');
18
+ const size = buf.readUInt32LE(p);
19
+ p += 4;
20
+ if (p + size > buf.length) throw new Error('zstd 跳过帧长度越界');
21
+ return p + size;
22
+ }
23
+ if (magic !== ZSTD_MAGIC) throw new Error('不是 zstd 文件');
24
+
25
+ if (p >= buf.length) throw new Error('zstd 帧头被截断');
26
+ const fhd = buf[p++];
27
+ const fcsFlag = fhd >> 6;
28
+ const singleSegment = (fhd >> 5) & 1;
29
+ const checksum = (fhd >> 2) & 1;
30
+ const dictFlag = fhd & 3;
31
+ if (!singleSegment) p += 1;
32
+ p += [0, 1, 2, 4][dictFlag];
33
+ p += fcsFlag === 0 ? (singleSegment ? 1 : 0) : [2, 4, 8][fcsFlag - 1];
34
+ if (p > buf.length) throw new Error('zstd 帧头长度越界');
35
+
36
+ for (;;) {
37
+ if (p + 3 > buf.length) throw new Error('zstd 块头被截断');
38
+ const head = buf[p] | (buf[p + 1] << 8) | (buf[p + 2] << 16);
39
+ p += 3;
40
+ const last = head & 1;
41
+ const type = (head >> 1) & 3;
42
+ const size = head >>> 3;
43
+ if (type === 3) throw new Error('zstd 块类型无效');
44
+ p += type === 1 ? 1 : size;
45
+ if (p > buf.length) throw new Error('zstd 块长度越界');
46
+ if (last) break;
47
+ }
48
+ if (checksum) p += 4;
49
+ if (p > buf.length) throw new Error('zstd 校验长度越界');
50
+ return p;
51
+ }
52
+
53
+ export function zstdDecompressAll(buf) {
54
+ if (typeof zstdDecompressSync !== 'function') {
55
+ const err = new Error('当前 Node 不支持 zstd 解压(需要 22.15 及以上)');
56
+ err.code = 'zstd-unavailable';
57
+ throw err;
58
+ }
59
+ const chunks = [];
60
+ let off = 0;
61
+ while (off < buf.length) {
62
+ const end = frameEnd(buf, off);
63
+ if (end <= off) throw new Error('zstd 帧长度无效');
64
+ chunks.push(zstdDecompressSync(buf.subarray(off, end)));
65
+ off = end;
66
+ }
67
+ return Buffer.concat(chunks);
68
+ }
@@ -518,6 +518,114 @@ export async function listSessionModelUsage(dataRoot, sessionId, treeTrace = '')
518
518
  }
519
519
  }
520
520
 
521
+ // 每轮官方汇总(turn_usage):一轮里的多个模型请求、工具循环、重试都算在同一轮,
522
+ // 比按 model_usage 行 + 可见回答行分桶稳定。返回 null = 当前 ZCode 版本没有这张表
523
+ // (调用方回退到按 model_usage 行分桶的旧算法)。
524
+ export async function listSessionTurnUsage(dataRoot, sessionId) {
525
+ const sid = String(sessionId || '');
526
+ if (!sid) return null;
527
+ const dbFile = join(dataRoot, 'cli', 'db', 'db.sqlite');
528
+ if (!existsSync(dbFile)) return null;
529
+ const driver = await loadDriver();
530
+ if (!driver) return null;
531
+ const esc = (v) => "'" + String(v).replace(/'/g, "''") + "'";
532
+ const tableSql = "SELECT name FROM sqlite_master WHERE type='table' AND name='turn_usage'";
533
+ const turnSql = `SELECT turn_id, started_at, completed_at, duration_ms, time_to_first_token_ms,`
534
+ + ` input_tokens, output_tokens, reasoning_tokens, cache_read_input_tokens, cache_creation_input_tokens, computed_total_tokens`
535
+ + ` FROM turn_usage WHERE session_id = ${esc(sid)} AND status = 'completed' AND completed_at IS NOT NULL`
536
+ + ` AND (coalesce(input_tokens, 0) + coalesce(output_tokens, 0)) > 0 ORDER BY started_at ASC`;
537
+ const useSql = `SELECT completed_at, duration_ms, time_to_first_token_ms, input_tokens, output_tokens, cache_read_input_tokens`
538
+ + ` FROM model_usage WHERE session_id = ${esc(sid)} AND query_source = 'main_turn'`
539
+ + ` AND status = 'completed' AND completed_at IS NOT NULL ORDER BY completed_at ASC`;
540
+ try {
541
+ let turns;
542
+ let usages;
543
+ if (driver.kind === 'node') {
544
+ const db = new driver.DatabaseSync(dbFile, { readOnly: true });
545
+ try {
546
+ if (!db.prepare(tableSql).all().length) return null;
547
+ turns = db.prepare(turnSql).all();
548
+ usages = db.prepare(useSql).all();
549
+ } finally { db.close(); }
550
+ } else {
551
+ if (!runCli(dbFile, tableSql + ';').stdout.trim()) return null;
552
+ turns = JSON.parse(runCli(dbFile,
553
+ `SELECT coalesce(json_group_array(json_object('turn_id', turn_id, 'started_at', started_at,`
554
+ + ` 'completed_at', completed_at, 'duration_ms', duration_ms, 'time_to_first_token_ms', time_to_first_token_ms,`
555
+ + ` 'input_tokens', input_tokens, 'output_tokens', output_tokens, 'reasoning_tokens', reasoning_tokens,`
556
+ + ` 'cache_read_input_tokens', cache_read_input_tokens, 'cache_creation_input_tokens', cache_creation_input_tokens,`
557
+ + ` 'computed_total_tokens', computed_total_tokens)), '[]') FROM (${turnSql});`).stdout.trim() || '[]');
558
+ usages = JSON.parse(runCli(dbFile,
559
+ `SELECT coalesce(json_group_array(json_object('completed_at', completed_at, 'duration_ms', duration_ms,`
560
+ + ` 'time_to_first_token_ms', time_to_first_token_ms, 'input_tokens', input_tokens, 'output_tokens', output_tokens,`
561
+ + ` 'cache_read_input_tokens', cache_read_input_tokens)), '[]') FROM (${useSql});`
562
+ ).stdout.trim() || '[]');
563
+ }
564
+ if (!turns.length) return null;
565
+ const num = (v) => Number(v) || 0;
566
+ const genMsOf = (dur, ttft) => (dur > 0 ? (ttft > 0 && ttft < dur * 0.8 ? dur - ttft : dur) : null);
567
+ const rounds = turns.map((t, i) => {
568
+ const inp = num(t.input_tokens);
569
+ const cacheRead = num(t.cache_read_input_tokens);
570
+ return {
571
+ idx: i + 1,
572
+ startAt: num(t.started_at) || num(t.completed_at),
573
+ at: num(t.completed_at),
574
+ in: inp,
575
+ out: num(t.output_tokens),
576
+ total: num(t.computed_total_tokens),
577
+ reasoning: num(t.reasoning_tokens),
578
+ cacheRead,
579
+ cacheWrite: num(t.cache_creation_input_tokens),
580
+ hitRate: inp > 0 ? cacheRead / inp : null,
581
+ genMs: 0,
582
+ tps: null,
583
+ };
584
+ });
585
+ // 一轮的生成时长按落在该轮起止时间内的 model_usage 行累加:包含工具循环的
586
+ // 轮次也能算净生成速率,且与旧算法同一公式。
587
+ let ti = 0;
588
+ for (const u of usages) {
589
+ const at = num(u.completed_at);
590
+ while (ti < rounds.length && at > rounds[ti].at) ti += 1;
591
+ const turn = rounds[ti];
592
+ if (!turn || at < turn.startAt || at > turn.at) continue;
593
+ const genMs = genMsOf(num(u.duration_ms), num(u.time_to_first_token_ms));
594
+ if (genMs) turn.genMs += genMs;
595
+ }
596
+ for (const turn of rounds) {
597
+ turn.tps = turn.genMs > 0 ? turn.out / (turn.genMs / 1000) : null;
598
+ }
599
+ const summary = { requests: rounds.length, totalIn: 0, totalOut: 0, totalCacheRead: 0, hitRate: null, tps: null };
600
+ for (const r of rounds) {
601
+ summary.totalIn += r.in;
602
+ summary.totalOut += r.out;
603
+ summary.totalCacheRead += r.cacheRead;
604
+ }
605
+ summary.hitRate = summary.totalIn > 0 ? summary.totalCacheRead / summary.totalIn : null;
606
+ // 进行中的轮次还没有 turn_usage 行:把最后一条已完成轮次之后的 model_usage
607
+ // 行作为 live 返回,注入层挂到最新一条可见回答上,长回合也能实时看到用量。
608
+ const lastAt = rounds.length ? rounds[rounds.length - 1].at : 0;
609
+ const live = [];
610
+ for (const u of usages) {
611
+ const at = num(u.completed_at);
612
+ if (at <= lastAt) continue;
613
+ const genMs = genMsOf(num(u.duration_ms), num(u.time_to_first_token_ms));
614
+ live.push({
615
+ at,
616
+ in: num(u.input_tokens),
617
+ out: num(u.output_tokens),
618
+ cacheRead: num(u.cache_read_input_tokens),
619
+ genMs: genMs || 0,
620
+ tpsOut: genMs ? num(u.output_tokens) : 0,
621
+ });
622
+ }
623
+ return { rounds, summary, turnMode: true, live };
624
+ } catch {
625
+ return null;
626
+ }
627
+ }
628
+
521
629
  // 项目里"真未读"的任务数(未读但排除错误态):项目行蓝色未读徽标的判据——
522
630
  // 错误态任务行显示的是红色错误点(应用图标优先级 错误>未读),它的未读不该再
523
631
  // 把项目徽标点亮成蓝色(subagent-icon.js)
@@ -32,6 +32,7 @@ function usage() {
32
32
  pauseOnHidden=true 窗口最小化暂停 pauseOnBlur=false 窗口失焦暂停
33
33
  pauseOnBattery=false 电池供电暂停
34
34
  dialogFrost=true 设置弹窗磨砂透出壁纸
35
+ cardVeil=0.2 插件卡片遮罩 0-1
35
36
  wallpaper upload [--select] <文件路径>... 把本机图片/视频复制进图库(--select 顺手设为壁纸)
36
37
  wallpaper delete <图库文件名> 从图库删除
37
38
  `;
@@ -282,7 +283,7 @@ zcode-pro(ZCode 桌面版增强工具)内置壁纸引擎:图片、视频
282
283
  | \`zcode-pro wallpaper list\` | 看当前配置和图库文件 |
283
284
  | \`zcode-pro wallpaper set none\\|library <文件>\\|folder <目录>\\|url <地址>\\|web <地址>\` | 切换壁纸来源 |
284
285
  | \`zcode-pro wallpaper rotate <分钟> [--random\\|--sequential]\` | 文件夹轮换/网址刷新间隔(0 = 不轮换/不刷新) |
285
- | \`zcode-pro wallpaper params <键=值>...\` | 调画面(遮罩/模糊/面板/缩放)、转场、播放(音量/倍速/帧率)、暂停条件、弹窗磨砂 |
286
+ | \`zcode-pro wallpaper params <键=值>...\` | 调画面(遮罩/模糊/面板/缩放/插件卡片遮罩)、转场、播放(音量/倍速/帧率)、暂停条件、弹窗磨砂 |
286
287
  | \`zcode-pro wallpaper upload [--select] <文件路径>...\` | 把本机图片/视频复制进图库(--select 顺手设为当前壁纸) |
287
288
  | \`zcode-pro wallpaper delete <图库文件名>\` | 从图库删文件 |
288
289
 
@@ -310,6 +311,7 @@ zcode-pro(ZCode 桌面版增强工具)内置壁纸引擎:图片、视频
310
311
  | videoVolume / playbackRate | 音量 0-1 / 倍速 0.5-2 | 数值 |
311
312
  | pauseOnHidden / pauseOnBlur / pauseOnBattery | 最小化/失焦/电池暂停 | true/false |
312
313
  | dialogFrost | 设置弹窗磨砂透出壁纸(false = 恢复不透明底) | true/false |
314
+ | cardVeil | 插件卡片遮罩:插件卡片透出壁纸时垫在卡片底下的主题色遮罩 | 0-1,默认 0.2 |
313
315
  | regions.left / center / right | 分区背景,每区可独立缩放/遮罩(null = 跟随全局;仅静态图,mode 取 library/folder/url,文件夹轮换复用全局间隔与顺序) | {mode,file,folder,url,fit,maskOpacity} |
314
316
  `;
315
317
 
@@ -189,7 +189,34 @@ const zh = {
189
189
  proxyScopeSync: '同步',
190
190
  proxyScopeSyncDesc: 'WebDAV 上传与下载走代理。',
191
191
  tabSync: '同步',
192
+ tabImport: '导入会话',
192
193
  tabDebug: '调试',
194
+ importDesc: '把 Codex、Claude Code、dsh、pi 的历史会话复制成 ZCode 任务。导入是快照,之后源会话的变化不会再同步。',
195
+ importSearch: '搜索标题或目录',
196
+ importRefresh: '刷新',
197
+ importShowAll: '显示全部',
198
+ importShowAllTip: '显示子代理会话、pi 里从 Codex 导入的副本,以及没有真实对话的 Claude 会话;已归档始终显示',
199
+ importOnlyProject: '只看所选项目',
200
+ importSelectAll: '全选',
201
+ importSelected: '导入所选({n})',
202
+ importImporting: '导入中…',
203
+ importLoading: '加载中…',
204
+ importNoSessions: '没有可导入的会话',
205
+ importNoSource: '没有找到该工具的会话目录',
206
+ importSourceMissing: '没有检测到会话目录',
207
+ importAlready: '已导入',
208
+ importAlreadyArchived: '已导入(任务已归档)',
209
+ importArchivedTaskTip: '导入的任务已归档;取消归档或删除后才能重新导入',
210
+ importArchived: '已归档',
211
+ importSubagent: '子代理',
212
+ importCodexCopy: 'Codex 副本',
213
+ importLarge: '大文件',
214
+ importCwdMissing: '原目录不存在',
215
+ importProjectNone: '不选项目(归到“任务”)',
216
+ importProjectHint: '项目只决定侧边栏归类,不改变会话原来的工作目录',
217
+ importConfirmLarge: '所选会话里有超过 20MB 的大文件,导入可能需要一些时间,继续吗?',
218
+ importDone: '导入完成:成功 {ok},跳过 {skip},失败 {fail}',
219
+ importFailed: '导入失败',
193
220
  testNoSessionHint: '选择“跟随当前会话[当前模型]”时,选择上次会话中使用的供应商[模型]',
194
221
  syncDesc: '手动把 ZCode Pro 设置与模型设置备份到 WebDAV,或在新电脑上恢复。两项各自独立成文件,可只上传或只覆盖其中一项;每次上传会额外保留一份带时间戳的历史版本(保留多少个见“历史版本”一行,上传后自动删除超出的最旧版本),下载时任选一个版本恢复;仅在点击按钮时传输,不做自动同步。',
195
222
  syncUrlPlaceholder: 'https://dav.jianguoyun.com/dav/',
@@ -426,6 +453,8 @@ const zh = {
426
453
  themeBgBlur: '画面模糊',
427
454
  themeBgPanel: '面板不透明度',
428
455
  themeBgDialogFrost: '设置弹窗磨砂',
456
+ themeBgCardVeil: '插件卡片遮罩',
457
+ themeBgCardVeilHint: '壁纸开着时垫在插件卡片底下的主题色遮罩:0 不遮(壁纸原样透出),越大卡片越实在、越暗。',
429
458
  themeBgMisc: '其他',
430
459
  themeBgFollowGlobal: '跟随全局',
431
460
  themeBgRegionsHint: '来源选“默认(全局壁纸)”即该区不单独设置、直接显示全局壁纸;每行的缩放、遮罩可单独设置,选“跟随全局”即跟随“画面”的值;模糊、转场、播放仅作用于全局壁纸(分区只能铺图,不能播视频)。分区用文件夹时,轮换间隔与随机顺序沿用全局设置。',
@@ -509,6 +538,8 @@ const zh = {
509
538
  featureSessionLink: '会话 ID 显示为任务名链接',
510
539
  featureSessionLinkDesc: '提问与回答里的会话 ID(sess_ / session_ 开头)显示为任务名,点击切换到该会话,悬停可看原始 ID。',
511
540
  featureComposerProviderDesc: '模型名前显示供应商名(如 BigModel-Max1 / glm-5.3),区分同名模型。',
541
+ featureSessionImport: '导入会话',
542
+ featureSessionImportDesc: '在设置弹窗里把 Codex、Claude Code、dsh、pi 的历史会话导入成 ZCode 任务。',
512
543
  imageCopy: '复制图片',
513
544
  imageCopied: '图片已复制到剪贴板',
514
545
  imageCopyFailed: '复制图片失败',
@@ -791,7 +822,34 @@ const en = {
791
822
  proxyScopeSync: 'Sync',
792
823
  proxyScopeSyncDesc: 'WebDAV upload and download go through the proxy.',
793
824
  tabSync: 'Sync',
825
+ tabImport: 'Session import',
794
826
  tabDebug: 'Debug',
827
+ importDesc: 'Copy sessions from Codex, Claude Code, dsh and pi into ZCode tasks. The copy is a snapshot; later changes in the source session are not synced.',
828
+ importSearch: 'Search title or folder',
829
+ importRefresh: 'Refresh',
830
+ importShowAll: 'Show all',
831
+ importShowAllTip: 'Show subagent sessions, pi copies imported from Codex, and Claude sessions without real conversation; archived sessions are always shown',
832
+ importOnlyProject: 'Only the selected project',
833
+ importSelectAll: 'Select all',
834
+ importSelected: 'Import selected ({n})',
835
+ importImporting: 'Importing…',
836
+ importLoading: 'Loading…',
837
+ importNoSessions: 'No sessions to import',
838
+ importNoSource: 'The session folder for this tool was not found',
839
+ importSourceMissing: 'No session folder detected',
840
+ importAlready: 'Imported',
841
+ importAlreadyArchived: 'Imported (task archived)',
842
+ importArchivedTaskTip: 'The imported task is archived; unarchive or delete it before importing again',
843
+ importArchived: 'Archived',
844
+ importSubagent: 'Subagent',
845
+ importCodexCopy: 'Codex copy',
846
+ importLarge: 'Large',
847
+ importCwdMissing: 'Original folder missing',
848
+ importProjectNone: 'No project (Tasks section)',
849
+ importProjectHint: 'The project only controls the sidebar group; the session keeps its original working folder',
850
+ importConfirmLarge: 'The selection includes files larger than 20MB. Importing may take a while. Continue?',
851
+ importDone: 'Import finished: {ok} imported, {skip} skipped, {fail} failed',
852
+ importFailed: 'Import failed',
795
853
  testNoSessionHint: 'With "Follow current session" selected, the provider and model of the last session are used (the label shows the model name in brackets).',
796
854
  syncDesc: 'Manually back up ZCode Pro settings and model settings to WebDAV, or restore them on a new computer. The two items are stored as separate files, so you can upload or overwrite either one alone; every upload also keeps a timestamped history version (how many to keep is set in the "History" row; older ones are removed automatically after upload) and download lets you pick any of them. Data moves only when you click, never automatically.',
797
855
  syncUrlPlaceholder: 'https://dav.example.com/dav/',
@@ -1027,6 +1085,8 @@ const en = {
1027
1085
  themeBgBlur: 'Wallpaper blur',
1028
1086
  themeBgPanel: 'Panel opacity',
1029
1087
  themeBgDialogFrost: 'Frosted settings window',
1088
+ themeBgCardVeil: 'Plugin card veil',
1089
+ themeBgCardVeilHint: 'Theme-colored veil behind plugin cards while a wallpaper is on: 0 shows the wallpaper as-is; higher makes cards more solid and darker.',
1030
1090
  themeBgMisc: 'Other',
1031
1091
  themeBgFollowGlobal: 'Follow global',
1032
1092
  themeBgRegionsHint: '"Default (global)" means the region is not set on its own and just shows the global wallpaper. Fit and mask can be set per row; "Follow global" uses the Display values. Blur, transition and playback apply only to the global wallpaper (regions are static images, no video). Region folders reuse the global rotation interval and order settings.',
@@ -1110,6 +1170,8 @@ const en = {
1110
1170
  featureSessionLink: 'Session ID links',
1111
1171
  featureSessionLinkDesc: 'Shows session IDs (sess_ / session_) in chat as task names; click to switch to that session, hover for the raw ID.',
1112
1172
  featureComposerProviderDesc: 'Shows the provider before the model name (e.g. BigModel-Max1 / glm-5.3).',
1173
+ featureSessionImport: 'Session import',
1174
+ featureSessionImportDesc: 'Import sessions from Codex, Claude Code, dsh and pi as ZCode tasks from the settings dialog.',
1113
1175
  imageCopy: 'Copy image',
1114
1176
  imageCopied: 'Image copied to the clipboard.',
1115
1177
  imageCopyFailed: 'Failed to copy the image.',
@@ -1390,6 +1452,17 @@ const errEn = {
1390
1452
  'index-remap-failed': 'Failed to update the task index (config changes rolled back)',
1391
1453
  'index-error': 'Task index error',
1392
1454
  'index-busy': 'The task index is busy. Please retry shortly.',
1455
+ 'bad-source': 'Unknown session source',
1456
+ 'source-unavailable': 'No session folder found for this tool',
1457
+ 'bad-request': 'Invalid import request',
1458
+ 'too-many-items': 'At most 1000 sessions per import; split the selection',
1459
+ 'project-not-found': 'Project not found or has no folder',
1460
+ 'bad-source-path': 'The session file is outside the source folder or no longer exists',
1461
+ 'session-mismatch': 'The session id does not match the file content',
1462
+ 'empty-session': 'No messages to import',
1463
+ 'db-missing': 'The ZCode session database or task index is missing',
1464
+ 'import-failed': 'Import failed',
1465
+ 'zstd-unavailable': 'This Node build cannot read dsh sessions (zstd support is missing)',
1393
1466
  'vision-invalid': 'Invalid vision config',
1394
1467
  'vision-read': 'Failed to read zcode-vision.json',
1395
1468
  'vision-write': 'Failed to write zcode-vision.json',
@@ -93,6 +93,32 @@ async function tryReclaim(ws, cooldownMs) {
93
93
  blockUntil.set(ws, Date.now() + cooldownMs);
94
94
  }
95
95
 
96
+ // 挑出本轮到点的工作区并顺带维护空闲计时:启动扫(不等空闲时长)+ 空闲时长
97
+ // 到点的入列(入列即扣表,等调用方扫完后台命令后决定回收或重新累计)。
98
+ // busy 的清表、没起表的起表、冷却中的不动表只跳过(冷却过后到点即重试,与
99
+ // 原先每轮全量扫的节奏一致)
100
+ function dueForReclaim(workspaces, busy, idleSince, blockUntil, now, threshold, startupDue) {
101
+ const due = [];
102
+ const seen = new Set();
103
+ const add = (ws) => { if (!seen.has(ws)) { seen.add(ws); due.push(ws); } };
104
+ if (startupDue) {
105
+ for (const ws of workspaces) {
106
+ if (busy.has(ws) || (blockUntil.get(ws) || 0) > now) continue;
107
+ add(ws);
108
+ }
109
+ }
110
+ for (const ws of workspaces) {
111
+ if (busy.has(ws)) { idleSince.delete(ws); continue; }
112
+ if (!idleSince.has(ws)) { idleSince.set(ws, now); continue; }
113
+ if (now - idleSince.get(ws) < threshold) continue;
114
+ if ((blockUntil.get(ws) || 0) > now) continue;
115
+ if (seen.has(ws)) continue; // 启动扫已入列:不动表,回收失败后到点再试
116
+ idleSince.delete(ws);
117
+ add(ws);
118
+ }
119
+ return due;
120
+ }
121
+
96
122
  async function tick() {
97
123
  if (!enabled) {
98
124
  idleSince.clear();
@@ -125,39 +151,38 @@ async function tick() {
125
151
  if (!workspaces.has(ws)) { idleSince.delete(ws); blockUntil.delete(ws); }
126
152
  }
127
153
 
128
- const candidates = [...workspaces].filter((ws) => !busy.has(normP(ws)));
129
- const res = candidates.length
130
- ? await rpc('/idle-busy', { method: 'POST', body: { paths: candidates } })
131
- : { ok: true, scan: true, busy: [] };
154
+ const now = Date.now();
155
+ // 启动一次性回收:应用启动会为每个恢复的项目预热会话进程,这次回收不等空闲
156
+ // 时长,到点把当时符合条件的项目一次收掉(0 = 启动后尽快回收一次;当前项目
157
+ // 定位不到时顺延到下一周期)。之后回归常规空闲计时
158
+ const startupDue = !startupSweepDone && now - bootAt >= startupMinutes * 60_000;
159
+ const due = dueForReclaim(workspaces, busy, idleSince, blockUntil, now, threshold, startupDue);
160
+ if (!due.length) {
161
+ if (startupDue) startupSweepDone = true;
162
+ return;
163
+ }
164
+ // 后台命令扫描(/idle-busy,Windows 上是 PowerShell 全进程枚举)只对本轮到点
165
+ // 的工作区做一次,不随巡检每轮全量扫——每 30 秒扫全部候选是常驻卡顿源。
166
+ // 有后台命令在跑的工作区跳过回收、重新累计空闲时长;回收前照样确认没有
167
+ // 用户命令在跑,回收语义不变
168
+ const res = await rpc('/idle-busy', { method: 'POST', body: { paths: due } });
132
169
  if (!res.ok || res.scan === false) {
133
170
  // 无法确认后台命令状态(系统工具缺失 / helper 旧版):整体停用
134
171
  if (!scanDisabledLogged) {
135
172
  scanDisabledLogged = true;
136
173
  console.info('[zcodepro] idle-reclaim: 后台命令扫描不可用,空闲回收停用');
137
174
  }
175
+ // 启动扫不因失败反复重试:否则每个巡检周期(30 秒)都重新扫——扫描不可用
176
+ // 还每 30 秒拉一次 PowerShell 全进程枚举,正是要消除的常驻开销。下一次
177
+ // 尝试回到空闲阈值节奏(默认 30 分钟),扫描恢复后仍能自动接上
178
+ if (startupDue) startupSweepDone = true;
138
179
  idleSince.clear();
139
180
  return;
140
181
  }
182
+ if (startupDue) startupSweepDone = true;
141
183
  const procBusy = new Set(res.busy || []);
142
- const idleCandidates = candidates.filter((ws) => !procBusy.has(ws));
143
-
144
- const now = Date.now();
145
- // 启动一次性回收:应用启动会为每个恢复的项目预热会话进程,这次回收不等空闲
146
- // 时长,到点把当时符合条件的项目一次收掉(0 = 启动后尽快回收一次;当前项目
147
- // 定位不到时顺延到下一周期)。之后回归常规空闲计时
148
- if (!startupSweepDone && now - bootAt >= startupMinutes * 60_000) {
149
- startupSweepDone = true;
150
- for (const ws of idleCandidates) {
151
- if ((blockUntil.get(ws) || 0) > now) continue;
152
- await tryReclaim(ws, threshold);
153
- }
154
- }
155
- for (const ws of workspaces) {
156
- if (busy.has(ws) || procBusy.has(ws)) { idleSince.delete(ws); continue; }
157
- if (!idleSince.has(ws)) { idleSince.set(ws, now); continue; }
158
- if (now - idleSince.get(ws) < threshold) continue;
159
- if ((blockUntil.get(ws) || 0) > now) continue;
160
- idleSince.delete(ws);
184
+ for (const ws of due) {
185
+ if (procBusy.has(ws)) { idleSince.delete(ws); continue; }
161
186
  await tryReclaim(ws, threshold);
162
187
  }
163
188
  }