zcode-pro 1.6.1 → 1.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +31 -21
- package/README.md +20 -12
- package/dist/inject.js +9624 -8634
- package/package.json +2 -1
- package/src/host/cdp.mjs +13 -3
- package/src/host/helper.mjs +982 -464
- package/src/host/main.mjs +368 -30
- package/src/host/paths.mjs +17 -9
- package/src/host/pickFolder.mjs +11 -4
- package/src/host/settings.mjs +15 -2
- package/src/host/setup.mjs +54 -15
- package/src/host/skill-stats.mjs +6 -1
- package/src/host/taskIndex.mjs +198 -66
- package/src/host/taskOrder.mjs +128 -57
- package/src/host/version.mjs +15 -7
- package/src/host/wallpaper.mjs +76 -59
- package/src/host/webdav.mjs +66 -10
- package/src/inject/core.js +184 -95
- package/src/inject/features/alias-migration.js +5 -1
- package/src/inject/features/auto-rename.js +166 -0
- package/src/inject/features/file-menu.js +6 -2
- package/src/inject/features/idle-reclaim.js +31 -8
- package/src/inject/features/newtab-panels.js +11 -1
- package/src/inject/features/pinned-collapse.js +11 -3
- package/src/inject/features/plugin-card-retry.js +18 -8
- package/src/inject/features/sandbox-reclaim.js +17 -1
- package/src/inject/features/session-link.js +200 -0
- package/src/inject/features/session-switch.js +57 -23
- package/src/inject/features/settings-dialog.js +242 -110
- package/src/inject/features/status-bar.js +126 -24
- package/src/inject/features/table-copy.js +18 -2
- package/src/inject/features/task-order.js +47 -13
- package/src/inject/features/theme.js +88 -31
- package/src/inject/features/title-gen.js +5 -4
- package/src/inject/features/title-lock.js +13 -8
- package/src/inject/features/turn-usage.js +69 -29
- package/src/inject/features/ws-running.js +26 -11
- package/src/inject/index.js +5 -0
- package/src/inject/provider-fields.js +2 -2
- package/src/inject/ui.js +6 -0
package/src/host/helper.mjs
CHANGED
|
@@ -4,18 +4,18 @@
|
|
|
4
4
|
|
|
5
5
|
import { createServer } from 'node:http';
|
|
6
6
|
import { execFile, spawn, spawnSync } from 'node:child_process';
|
|
7
|
-
import { createDecipheriv, createHash } from 'node:crypto';
|
|
7
|
+
import { createDecipheriv, createHash, randomBytes } from 'node:crypto';
|
|
8
8
|
import { appendFileSync, chmodSync, closeSync, copyFileSync, createReadStream, createWriteStream, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readlinkSync, readSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
9
9
|
import { mkdtemp } from 'node:fs/promises'; // 注意:fs 的 mkdtemp 是回调版,await 它会把 undefined 当回调
|
|
10
10
|
import { basename, delimiter, dirname, isAbsolute, join, resolve, sep } from 'node:path';
|
|
11
11
|
import { homedir, tmpdir, userInfo } from 'node:os';
|
|
12
12
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
13
|
-
import { readSettings,
|
|
14
|
-
import { taskIndexPath, probeTaskIndexWritable, remapTaskIndexPaths, taskIndexDriverAvailable, listOverriddenTitles, listTaskWorkspaceMap, listTaskStatuses, setTaskTitleIfNotOverridden, setCustomSessionTitle, isTaskTitleOverridden, reconcileCustomTitles, getTaskProviderModel, listVirtualProjects, countTasks } from './taskIndex.mjs';
|
|
13
|
+
import { readSettings, remapSettingsPathsAtomic, isProjectOpenInTabs } from './settings.mjs';
|
|
14
|
+
import { taskIndexPath, probeTaskIndexWritable, remapTaskIndexPaths, taskIndexDriverAvailable, listOverriddenTitles, listTaskWorkspaceMap, listTaskStatuses, setTaskTitleIfNotOverridden, setCustomSessionTitle, isTaskTitleOverridden, reconcileCustomTitles, getTaskProviderModel, listVirtualProjects, countTasks, readRecentQa } from './taskIndex.mjs';
|
|
15
15
|
import { pickFolderSystem } from './pickFolder.mjs';
|
|
16
|
-
import {
|
|
16
|
+
import { reorderTasks } from './taskOrder.mjs';
|
|
17
17
|
import { webdavRequest, webdavPutWithMkcol, webdavHttpText, parseWebdavListing, findCurl } from './webdav.mjs';
|
|
18
|
-
import { resolveZcodeExecutable } from './paths.mjs';
|
|
18
|
+
import { resolveZcodeExecutable, resolveDataRootDir } from './paths.mjs';
|
|
19
19
|
import { skillStats, DEFAULT_METADATA_BUDGET } from './skill-stats.mjs';
|
|
20
20
|
|
|
21
21
|
const VERSION = '1.5.1';
|
|
@@ -37,7 +37,7 @@ function defaultRtkDir() {
|
|
|
37
37
|
}
|
|
38
38
|
|
|
39
39
|
// 主题功能的壁纸图库:用户上传的图片/视频都存这里,helper 以 /bg/file/<name> 提供,
|
|
40
|
-
// 注入层直接引用该 URL(媒体元素/CSS url()
|
|
40
|
+
// 注入层直接引用该 URL(媒体元素/CSS url() 带不了鉴权请求头,URL 带 ?t= token,见下)
|
|
41
41
|
const BG_DIR_NAME = 'backgrounds';
|
|
42
42
|
export function backgroundsDir(dataRoot) {
|
|
43
43
|
return join(dataRoot, BG_DIR_NAME);
|
|
@@ -122,7 +122,10 @@ export function renameOrReplace(tmp, dst) {
|
|
|
122
122
|
export function sweepDeferredBg(dir) {
|
|
123
123
|
try {
|
|
124
124
|
for (const n of readdirSync(dir)) {
|
|
125
|
-
|
|
125
|
+
// .deleted-* 是延迟删除的残留;结尾 .tmp 是上传中断留下的半截文件(正常
|
|
126
|
+
// 流程会即时改名或删掉)。都只清超过 24 小时的,避免误伤进行中的操作;
|
|
127
|
+
// 媒体文件扩展名有白名单,正常文件不会以 .tmp 结尾
|
|
128
|
+
if (!n.includes('.deleted-') && !n.endsWith('.tmp')) continue;
|
|
126
129
|
const f = join(dir, n);
|
|
127
130
|
try {
|
|
128
131
|
if (Date.now() - statSync(f).mtimeMs > 24 * 3600 * 1000) unlinkSync(f);
|
|
@@ -142,9 +145,18 @@ export function listBgFiles(dataRoot) {
|
|
|
142
145
|
} catch { return []; } // 目录不存在 = 空图库
|
|
143
146
|
}
|
|
144
147
|
|
|
148
|
+
// ?dir= 只认用户配置过的目录(全局文件夹 + 各分区目录)——仅凭 URL 上的 token
|
|
149
|
+
// 还不够,别让持 token 的调用列出/读取任意目录的文件。取文件与列目录两条路由共用这一个判定
|
|
150
|
+
function bgFolderDirAllowed(bgCfg, qDir) {
|
|
151
|
+
if (!qDir || qDir.length > 4096 || !isAbsolute(qDir)) return false;
|
|
152
|
+
const allowed = [bgCfg.folder,
|
|
153
|
+
bgCfg.regions?.left?.folder, bgCfg.regions?.center?.folder, bgCfg.regions?.right?.folder].filter(Boolean);
|
|
154
|
+
return allowed.includes(qDir);
|
|
155
|
+
}
|
|
156
|
+
|
|
145
157
|
// 视频壁纸帧率上限:ffmpeg 一次性转码出抽帧版存缓存目录,注入层先播原片、
|
|
146
158
|
// 转码完成再换。没有 ffmpeg 时接口直接报缺依赖,注入层保持原片播放
|
|
147
|
-
export const TRANSCODE_FPS = new Set([15, 30, 60]);
|
|
159
|
+
export const TRANSCODE_FPS = new Set([15, 30, 60, 90, 120]);
|
|
148
160
|
let ffmpegOk = null; // 三态:null 未探测 / true / false
|
|
149
161
|
function hasFfmpeg() {
|
|
150
162
|
if (ffmpegOk === null) {
|
|
@@ -157,6 +169,7 @@ export function transcodeDir(dataRoot) {
|
|
|
157
169
|
return join(dataRoot, 'cache', 'transcode');
|
|
158
170
|
}
|
|
159
171
|
const transcodeJobs = new Set(); // 正在转码的 key,防同一文件重复起 ffmpeg
|
|
172
|
+
const transcodeChildren = new Set(); // 在跑的 ffmpeg 子进程:退出/交接时统一收掉,防孤儿进程
|
|
160
173
|
const TRANSCODE_MAX_CONCURRENCY = 2; // 同时最多 2 个 ffmpeg,防批量请求打满 CPU/磁盘
|
|
161
174
|
// URL 路径段解码:非法 % 序列回 null(调用方回 400),不让 URIError 落成 500
|
|
162
175
|
let folderCfgCache = { at: 0, dir: '' };
|
|
@@ -166,14 +179,14 @@ function decodeName(raw) {
|
|
|
166
179
|
|
|
167
180
|
// 主题配置(设置 → 外观 → 主题/壁纸):skin 为皮肤 id(default = 不覆盖,
|
|
168
181
|
// custom = 用 custom 锚点色现算色阶);bg.mode 选壁纸来源——none 无壁纸 /
|
|
169
|
-
// library 本地图库(file
|
|
182
|
+
// library 本地图库(file 为当前文件,单选一张,轮换归文件夹)/ folder 文件夹
|
|
170
183
|
// (定时轮换,folderRandom 随机或顺序)/ url 图片网址(intervalMin 定时刷新)/
|
|
171
184
|
// web 网页(url 为页面地址,iframe 铺在界面后方);
|
|
172
185
|
// maskOpacity 遮罩不透明度 0-0.99(越高画面越向主题背景色淡化,文字对比越
|
|
173
186
|
// 清晰,默认 0.82)、blurPx 画面模糊 0-24px(默认 0)、panelOpacity 面板
|
|
174
187
|
// 不透明度 0-1(侧栏/面板/标签栏,越低透出画面越多,默认 0.3);
|
|
175
|
-
// transition 换壁纸转场(cut
|
|
176
|
-
// (0 原始,其余 15/30/60,需 ffmpeg 抽帧转码)、videoVolume 音量 0-1(默认 0
|
|
188
|
+
// transition 换壁纸转场(cut 直接切换 / fade 淡入淡出)、fpsCap 视频帧率上限
|
|
189
|
+
// (0 原始,其余 15/30/60/90/120,需 ffmpeg 抽帧转码)、videoVolume 音量 0-1(默认 0
|
|
177
190
|
// 静音)、playbackRate 倍速 0.5-2(默认 1);pauseOnHidden/pauseOnBlur/
|
|
178
191
|
// pauseOnBattery 三个暂停条件(默认开/关/关)
|
|
179
192
|
const THEME_SKINS = new Set(['default', 'dracula', 'nord', 'tokyonight', 'catppuccin', 'gruvbox', 'onedark', 'solarized', 'rosepine', 'everforest', 'nightowl', 'kanagawa', 'custom']);
|
|
@@ -204,11 +217,16 @@ function mergeBgRegion(src) {
|
|
|
204
217
|
file: mode === 'library' ? (str(src.file, 200) || '') : '',
|
|
205
218
|
folder: mode === 'folder' ? (str(src.folder, 4096) || '') : '',
|
|
206
219
|
url: mode === 'url' ? (str(src.url, 2000) || '').trim() : '',
|
|
220
|
+
// 分区独立缩放/遮罩:null = 跟随全局(只有分区行的控件会写这两项)
|
|
221
|
+
fit: BG_FITS.has(src.fit) ? src.fit : null,
|
|
222
|
+
maskOpacity: src.maskOpacity != null && src.maskOpacity !== '' && Number.isFinite(Number(src.maskOpacity))
|
|
223
|
+
? Math.min(0.99, Math.max(0, Number(src.maskOpacity))) : null,
|
|
207
224
|
};
|
|
208
225
|
}
|
|
209
226
|
export function mergeThemeConfig(saved) {
|
|
210
227
|
const t = saved && typeof saved === 'object' ? saved : {};
|
|
211
228
|
const bg = t.bg && typeof t.bg === 'object' ? t.bg : {};
|
|
229
|
+
const bgUrl = (str(bg.url, 2000) || '').trim();
|
|
212
230
|
const cfg = {
|
|
213
231
|
skin: THEME_SKINS.has(t.skin) ? t.skin : 'default',
|
|
214
232
|
custom: mergeCustomSkin(t.custom),
|
|
@@ -217,17 +235,18 @@ export function mergeThemeConfig(saved) {
|
|
|
217
235
|
file: str(bg.file, 200) || '',
|
|
218
236
|
folder: str(bg.folder, 4096) || '',
|
|
219
237
|
folderRandom: bg.folderRandom !== false,
|
|
220
|
-
url: (
|
|
238
|
+
url: /^https?:\/\//i.test(bgUrl) ? bgUrl : '', // 网页壁纸只收 http(s)(与 wallpaper CLI 校验一致)
|
|
221
239
|
// Number() 容错与相邻数值字段一致:外部写入方(手改配置/壁纸控制插件)写数字字符串也能生效
|
|
222
240
|
intervalMin: bg.intervalMin != null && Number.isFinite(Number(bg.intervalMin)) ? Math.min(1440, Math.max(0, Math.round(Number(bg.intervalMin)))) : 0,
|
|
223
241
|
fit: BG_FITS.has(bg.fit) ? bg.fit : 'cover',
|
|
224
242
|
// null/undefined/非数值都落默认(Number(null)=0 是有限数,须先排除 null)
|
|
225
|
-
maskOpacity: bg.maskOpacity != null && Number.isFinite(Number(bg.maskOpacity))
|
|
243
|
+
maskOpacity: bg.maskOpacity != null && bg.maskOpacity !== '' && Number.isFinite(Number(bg.maskOpacity))
|
|
226
244
|
? Math.min(0.99, Math.max(0, Number(bg.maskOpacity))) : 0.82,
|
|
227
245
|
blurPx: bg.blurPx != null && Number.isFinite(Number(bg.blurPx)) ? Math.min(24, Math.max(0, Math.round(bg.blurPx))) : 0,
|
|
228
|
-
panelOpacity: bg.panelOpacity != null && Number.isFinite(Number(bg.panelOpacity)) ? Math.min(1, Math.max(0, Number(bg.panelOpacity))) : 0.3,
|
|
246
|
+
panelOpacity: bg.panelOpacity != null && bg.panelOpacity !== '' && Number.isFinite(Number(bg.panelOpacity)) ? Math.min(1, Math.max(0, Number(bg.panelOpacity))) : 0.3,
|
|
229
247
|
transition: bg.transition === 'fade' ? 'fade' : 'cut',
|
|
230
248
|
fpsCap: TRANSCODE_FPS.has(Number(bg.fpsCap)) ? Number(bg.fpsCap) : 0,
|
|
249
|
+
dialogFrost: bg.dialogFrost !== false,
|
|
231
250
|
videoVolume: bg.videoVolume != null && Number.isFinite(Number(bg.videoVolume))
|
|
232
251
|
? Math.min(1, Math.max(0, Number(bg.videoVolume))) : 0,
|
|
233
252
|
playbackRate: bg.playbackRate != null && Number.isFinite(Number(bg.playbackRate))
|
|
@@ -252,7 +271,7 @@ export function mergeThemeConfig(saved) {
|
|
|
252
271
|
// mergeThemeConfig(clamp + 默认值)
|
|
253
272
|
export const BG_PARAM_KEYS = {
|
|
254
273
|
maskOpacity: 'number', blurPx: 'number', panelOpacity: 'number', videoVolume: 'number', playbackRate: 'number',
|
|
255
|
-
pauseOnHidden: 'boolean', pauseOnBlur: 'boolean', pauseOnBattery: 'boolean',
|
|
274
|
+
pauseOnHidden: 'boolean', pauseOnBlur: 'boolean', pauseOnBattery: 'boolean', dialogFrost: 'boolean',
|
|
256
275
|
fit: BG_FITS, transition: new Set(['cut', 'fade']), fpsCap: new Set([0, ...TRANSCODE_FPS]),
|
|
257
276
|
};
|
|
258
277
|
|
|
@@ -267,7 +286,8 @@ const ZCODE_PLUGINS_MARKETPLACE = 'duanluan-zcode-plugins';
|
|
|
267
286
|
const ZCODE_PLUGINS_MARKETPLACE_SOURCE = 'duanluan/zcode-plugins';
|
|
268
287
|
|
|
269
288
|
function cliPluginsDir() {
|
|
270
|
-
|
|
289
|
+
// 官方 CLI 数据目录跟 ZCODE_DATA_BASE_DIR 迁移(rollout/v2 同款),别固定 HOME
|
|
290
|
+
return join(resolveDataRootDir(), 'cli', 'plugins');
|
|
271
291
|
}
|
|
272
292
|
|
|
273
293
|
export function defaultConfig() {
|
|
@@ -285,6 +305,7 @@ export function defaultConfig() {
|
|
|
285
305
|
toolbarIcons: true, // 侧栏菜单并入顶栏:新建任务/搜索/自动化/插件市场收成顶栏图标按钮(原菜单隐藏,点击转发)
|
|
286
306
|
pinnedCollapse: true, // 已置顶分区可折叠:标题可点折叠/展开任务列表(状态记 localStorage)
|
|
287
307
|
tableCopy: true, // 表格工具条"复制表格"按钮:富文本剪贴板,粘贴即表格(table-copy.js)
|
|
308
|
+
sessionLink: true, // 会话 ID 显示为任务名链接:聊天里的 sess_/session_ 显示为任务名,点击切换(session-link.js)
|
|
288
309
|
composerProvider: true, // 输入框模型名前显示供应商名(composer-provider.js)
|
|
289
310
|
},
|
|
290
311
|
// 空闲项目内存回收的判定时长(分钟,1–1440):项目无运行中会话、无后台命令
|
|
@@ -318,13 +339,16 @@ export function defaultConfig() {
|
|
|
318
339
|
// headroom 启用开关的记忆(供应商 id → { proxy, direct }):关闭时把走 headroom 的
|
|
319
340
|
// 供应商地址切回直连并记录下来,再次开启时按记录把地址切回代理
|
|
320
341
|
headroomRoutes: {},
|
|
321
|
-
//
|
|
322
|
-
//
|
|
342
|
+
// 自动重命名(原“任务名提示词”):新会话开始作答后按可配置的供应商与
|
|
343
|
+
// 提示词生成标题,并按“手动重命名”写入任务索引。默认关闭。provider:
|
|
323
344
|
// 'session' = 跟随当前会话(调用时从任务索引解析该会话的供应商,默认)、
|
|
324
345
|
// '' = 不跟随(自填 baseUrl/apiKey/format)、其余 = 供应商 id(保存时同步
|
|
325
346
|
// 解析一份 baseUrl/apiKey/format 副本,供应商日后被删仍可直连);
|
|
326
347
|
// model 默认 glm-5.3-flash(起名用快模型即可),跟随会话时可留空
|
|
327
|
-
//(用会话当前模型);prompt 留空 =
|
|
348
|
+
//(用会话当前模型);prompt 留空 = 内置默认提示词。
|
|
349
|
+
// 手动“自动重命名”(任务行悬浮按钮 / 右键菜单入口,取会话最近 recentQa
|
|
350
|
+
// 轮问答起名、已重命名也覆盖)不受 enabled 限制,入口各有开关:
|
|
351
|
+
// hoverBtn 任务行按钮、menuEntry 右键菜单项
|
|
328
352
|
titleGen: {
|
|
329
353
|
enabled: false,
|
|
330
354
|
customWritten: {},
|
|
@@ -334,6 +358,9 @@ export function defaultConfig() {
|
|
|
334
358
|
baseUrl: '',
|
|
335
359
|
apiKey: '',
|
|
336
360
|
format: '',
|
|
361
|
+
recentQa: 3,
|
|
362
|
+
hoverBtn: true,
|
|
363
|
+
menuEntry: true,
|
|
337
364
|
},
|
|
338
365
|
// HTTP 代理(http(s)://host:port):helper 发起的网络访问走它——插件市场更新/安装
|
|
339
366
|
// (zcode CLI → git)、headroom/rtk 的安装与升级(pip/GitHub)。空 = 不用代理。
|
|
@@ -418,21 +445,118 @@ function readFileSyncText(p) {
|
|
|
418
445
|
// 原子写任意 JSON 文件:先写临时文件再改名,避免崩溃留下半截 JSON
|
|
419
446
|
function writeJsonAtomic(file, obj) {
|
|
420
447
|
const tmp = `${file}.${process.pid}.${Date.now().toString(36)}.tmp`; // 防多写者共用同一 .tmp 撕裂
|
|
421
|
-
|
|
448
|
+
try { mkdirSync(dirname(file), { recursive: true }); } catch { /* 目录已存在 */ } // 数据目录缺失时先建,别让写入直接抛
|
|
449
|
+
writeFileSync(tmp, JSON.stringify(obj, null, 2), { encoding: 'utf8', mode: 0o600 }); // 配置含凭据,限制本人读写
|
|
422
450
|
renameSync(tmp, file);
|
|
423
451
|
}
|
|
424
452
|
|
|
453
|
+
// 读改写必须同步完成(loadConfig→改→saveConfig 中间不能加 await):
|
|
454
|
+
// HTTP 处理器靠单线程的同步原子性保证并发保存不互相覆盖字段
|
|
425
455
|
export function saveConfig(configFile, config) {
|
|
426
456
|
// 配置"存在但损坏"时拒绝写回:否则 title-gen/同步/别名等写路径会把默认值
|
|
427
457
|
// 整份覆盖上去(WebDAV 账号、样式、主题全丢且不可恢复)。POST /config 另有
|
|
428
458
|
// 显式报错,这里兜住其余调用方;修好文件后 loadConfig 会复位标记恢复可写。
|
|
429
459
|
// 保护只针对 zcodepro.json:写别的文件(/zcode-config 写 cli/config.json)
|
|
430
|
-
// 直接用 writeJsonAtomic
|
|
460
|
+
// 直接用 writeJsonAtomic,别被这个标记误伤成静默不写。
|
|
461
|
+
// 返回是否写入:调用方据此报错(同步导入不能在拒写时还报成功)
|
|
431
462
|
if (configUnreadable) {
|
|
432
463
|
console.error('[zcodepro] zcodepro.json 读取失败或已损坏,拒绝写回以免清空配置');
|
|
433
|
-
return;
|
|
464
|
+
return false;
|
|
434
465
|
}
|
|
435
466
|
writeJsonAtomic(configFile, config);
|
|
467
|
+
return true;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
// —— zcodepro.json 跨进程写锁 ——————————————————————————————————
|
|
471
|
+
// 多个进程(helper、wallpaper CLI、同步导入…)会同时读改写 zcodepro.json,
|
|
472
|
+
// 不互斥时各拿旧快照写回,会把对方改的整段配置(WebDAV 凭据、别名、样式)盖掉。
|
|
473
|
+
// 锁 = 配置文件同目录下的锁目录(mkdir 原子创建),目录里写持有者信息(pid + 随机 token)。
|
|
474
|
+
const CONFIG_LOCK_STALE_MS = 10_000; // 锁龄超过这个数按悬挂锁接管
|
|
475
|
+
const CONFIG_LOCK_WAIT_MS = 5_000; // 等锁上限;等不到带提示继续尽力而为
|
|
476
|
+
|
|
477
|
+
// 进程还在不在(pid 被系统复用的极端情形由锁龄上限兜底)
|
|
478
|
+
function pidAlive(pid) {
|
|
479
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
480
|
+
try { process.kill(pid, 0); return true; } catch (err) { return err.code === 'EPERM'; }
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
// 抢一次锁:mkdir 成功即持有;已有锁时仅在持有者死亡或锁龄超时才拆掉接管。
|
|
484
|
+
// 返回是否拿到(没拿到由调用方等待重试)
|
|
485
|
+
function tryAcquireConfigLock(configFile, token) {
|
|
486
|
+
const lockDir = configFile + '.lock';
|
|
487
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
488
|
+
try {
|
|
489
|
+
mkdirSync(lockDir); // 原子创建:同时只有一个进程成功
|
|
490
|
+
try {
|
|
491
|
+
writeFileSync(join(lockDir, 'holder.json'), JSON.stringify({ pid: process.pid, token }), 'utf8');
|
|
492
|
+
} catch { /* 持有者信息写失败不影响锁本身,释放时按超时接管兜底 */ }
|
|
493
|
+
return true;
|
|
494
|
+
} catch (err) {
|
|
495
|
+
if (err.code !== 'EEXIST') throw err;
|
|
496
|
+
let stale = false;
|
|
497
|
+
try {
|
|
498
|
+
let alive = true;
|
|
499
|
+
try {
|
|
500
|
+
const holder = JSON.parse(readFileSync(join(lockDir, 'holder.json'), 'utf8'));
|
|
501
|
+
alive = pidAlive(Number(holder.pid));
|
|
502
|
+
} catch { alive = true; } // 持有者信息缺失/写坏:只按锁龄判悬挂
|
|
503
|
+
stale = Date.now() - statSync(lockDir).mtimeMs > CONFIG_LOCK_STALE_MS || !alive;
|
|
504
|
+
} catch { stale = true; } // 锁目录正被删/读不了:按悬挂接管
|
|
505
|
+
if (!stale) return false;
|
|
506
|
+
try { rmSync(lockDir, { recursive: true, force: true }); } catch { return false; }
|
|
507
|
+
// 接管后回到循环重试 mkdir(可能被另一个进程抢先)
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
return false;
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
// 释放锁:只认自己那份持有者信息,被别人接管后不能把别人的锁删掉
|
|
514
|
+
function releaseConfigLock(configFile, token) {
|
|
515
|
+
const lockDir = configFile + '.lock';
|
|
516
|
+
try {
|
|
517
|
+
const holder = JSON.parse(readFileSync(join(lockDir, 'holder.json'), 'utf8'));
|
|
518
|
+
if (holder.token !== token) return;
|
|
519
|
+
} catch { return; } // 读不到持有者信息(已被接管后删除等):不动目录,留超时接管
|
|
520
|
+
try { rmSync(lockDir, { recursive: true, force: true }); } catch { /* ignore */ }
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
// 在跨进程锁内同步执行 fn 并返回其结果:fn 里保持同步读改写(loadConfig→改→
|
|
524
|
+
// saveConfig 中间不要 await)。等锁上限约 5 秒,等不到带提示继续尽力而为
|
|
525
|
+
//(不加锁至少还能写成,别直接失败)。调用点是 async 就 await 这个函数。
|
|
526
|
+
export async function withConfigLock(configFile, fn) {
|
|
527
|
+
const token = randomBytes(12).toString('hex');
|
|
528
|
+
const deadline = Date.now() + CONFIG_LOCK_WAIT_MS;
|
|
529
|
+
while (!tryAcquireConfigLock(configFile, token)) {
|
|
530
|
+
if (Date.now() >= deadline) {
|
|
531
|
+
console.error('[zcodepro] 等 zcodepro.json 写锁超时,继续无锁写入(可能与别的进程互相覆盖)');
|
|
532
|
+
return fn();
|
|
533
|
+
}
|
|
534
|
+
await new Promise((r) => setTimeout(r, 100));
|
|
535
|
+
}
|
|
536
|
+
try {
|
|
537
|
+
return fn();
|
|
538
|
+
} finally {
|
|
539
|
+
releaseConfigLock(configFile, token);
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
// 同步等锁变体(同步调用点用,如 setHeadroomUsage):Atomics.wait 睡眠重试,
|
|
544
|
+
// 语义与 withConfigLock 相同
|
|
545
|
+
export function withConfigLockSync(configFile, fn) {
|
|
546
|
+
const token = randomBytes(12).toString('hex');
|
|
547
|
+
const deadline = Date.now() + CONFIG_LOCK_WAIT_MS;
|
|
548
|
+
while (!tryAcquireConfigLock(configFile, token)) {
|
|
549
|
+
if (Date.now() >= deadline) {
|
|
550
|
+
console.error('[zcodepro] 等 zcodepro.json 写锁超时,继续无锁写入(可能与别的进程互相覆盖)');
|
|
551
|
+
return fn();
|
|
552
|
+
}
|
|
553
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 100);
|
|
554
|
+
}
|
|
555
|
+
try {
|
|
556
|
+
return fn();
|
|
557
|
+
} finally {
|
|
558
|
+
releaseConfigLock(configFile, token);
|
|
559
|
+
}
|
|
436
560
|
}
|
|
437
561
|
|
|
438
562
|
// 一次性配置迁移已移除(原 wsRunningSpinOff):旧实验版“折叠项目运行提示”
|
|
@@ -564,7 +688,9 @@ function zcodeConfigSnapshot(dataRoot) {
|
|
|
564
688
|
return { ok: true, values, configured, stats };
|
|
565
689
|
}
|
|
566
690
|
|
|
567
|
-
export function startHelper({ port, token, dataRoot, state, agentsFile = defaultAgentsFile() }) {
|
|
691
|
+
export function startHelper({ port, token, dataRoot, state, agentsFile = defaultAgentsFile(), listenTries = 40, rolloutDir = '', visionFile = '' }) {
|
|
692
|
+
if (rolloutDir) rolloutDirOverride = rolloutDir;
|
|
693
|
+
if (!visionFile) visionFile = defaultVisionFile(); // 测试可覆盖,别把启动补写落到真实 ~/.zcode
|
|
568
694
|
const configFile = join(dataRoot, 'zcodepro.json');
|
|
569
695
|
const settingsFile = join(dataRoot, 'v2', 'setting.json');
|
|
570
696
|
const bootConfig = loadConfig(configFile);
|
|
@@ -654,6 +780,16 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
654
780
|
res2.end('read error');
|
|
655
781
|
}
|
|
656
782
|
};
|
|
783
|
+
// 媒体路由(CSS url()/<video> 引用,带不了鉴权请求头):认 URL 上的
|
|
784
|
+
// ?t= token,外部页面猜不到 token 就读不走图库媒体、也做不了存在性探测
|
|
785
|
+
if (req.method === 'GET' && (url.pathname.startsWith('/bg/file/')
|
|
786
|
+
|| url.pathname.startsWith('/bg/folder/file/') || url.pathname.startsWith('/bg/transcode/file/'))) {
|
|
787
|
+
const q = url.searchParams.get('t');
|
|
788
|
+
if (!token || (req.headers['x-zcodepro-token'] !== token && q !== token)) {
|
|
789
|
+
json(res, 401, { ok: false, error: 'unauthorized' });
|
|
790
|
+
return;
|
|
791
|
+
}
|
|
792
|
+
}
|
|
657
793
|
if (req.method === 'GET' && url.pathname.startsWith('/bg/file/')) {
|
|
658
794
|
const dec = decodeName(url.pathname.slice('/bg/file/'.length));
|
|
659
795
|
if (dec === null) { json(res, 400, { ok: false, error: '非法文件名编码' }); return; }
|
|
@@ -666,12 +802,9 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
666
802
|
const qDir = url.searchParams.get('dir');
|
|
667
803
|
let dir;
|
|
668
804
|
if (qDir) {
|
|
669
|
-
//
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
const allowed = [cfgB.folder,
|
|
673
|
-
cfgB.regions?.left?.folder, cfgB.regions?.center?.folder, cfgB.regions?.right?.folder].filter(Boolean);
|
|
674
|
-
if (qDir.length > 4096 || !isAbsolute(qDir) || !allowed.includes(qDir)) {
|
|
805
|
+
// dir 只认用户配置过的目录(全局文件夹 + 各分区目录),
|
|
806
|
+
// 判定与 /bg/folder/list 共用 bgFolderDirAllowed
|
|
807
|
+
if (!bgFolderDirAllowed(loadConfig(configFile).theme.bg, qDir)) {
|
|
675
808
|
json(res, 400, { ok: false, error: 'dir 参数无效或未配置' });
|
|
676
809
|
return;
|
|
677
810
|
}
|
|
@@ -697,7 +830,8 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
697
830
|
serveBgFile(dec, transcodeDir(dataRoot), res);
|
|
698
831
|
return;
|
|
699
832
|
}
|
|
700
|
-
|
|
833
|
+
// 空 token 视为配置错误直接拒绝(fail-closed),别放成免鉴权
|
|
834
|
+
if (!token || req.headers['x-zcodepro-token'] !== token) {
|
|
701
835
|
json(res, 401, { ok: false, error: 'unauthorized' });
|
|
702
836
|
return;
|
|
703
837
|
}
|
|
@@ -712,131 +846,139 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
712
846
|
}
|
|
713
847
|
if (req.method === 'POST' && url.pathname === '/config') {
|
|
714
848
|
const body = await readBody(req);
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
const v = body.proxy.trim();
|
|
722
|
-
if (v === '') current.proxy = '';
|
|
723
|
-
else if (/^https?:\/\/\S+:\d+$/.test(v) && v.length <= 300) current.proxy = v;
|
|
724
|
-
else {
|
|
725
|
-
json(res, 400, { ok: false, code: 'proxy-invalid', error: '代理地址需形如 http://127.0.0.1:7890,或留空清除' });
|
|
849
|
+
// 整段读改写(loadConfig→改→saveConfig)放进跨进程锁内同步执行,
|
|
850
|
+
// 防止两个写入方各拿旧快照写回、互相覆盖整份配置
|
|
851
|
+
await withConfigLock(configFile, () => {
|
|
852
|
+
const current = loadConfig(configFile);
|
|
853
|
+
if (configUnreadable) {
|
|
854
|
+
json(res, 500, { ok: false, code: 'config-unreadable', error: 'zcodepro.json 读取失败或已损坏,拒绝写回以免清空配置;请先修复该文件' });
|
|
726
855
|
return;
|
|
727
856
|
}
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
857
|
+
if (body && typeof body === 'object' && typeof body.proxy === 'string') {
|
|
858
|
+
const v = body.proxy.trim();
|
|
859
|
+
if (v === '') current.proxy = '';
|
|
860
|
+
else if (/^https?:\/\/\S+:\d+$/.test(v) && v.length <= 300) current.proxy = v;
|
|
861
|
+
else {
|
|
862
|
+
json(res, 400, { ok: false, code: 'proxy-invalid', error: '代理地址需形如 http://127.0.0.1:7890,或留空清除' });
|
|
863
|
+
return;
|
|
864
|
+
}
|
|
865
|
+
activeProxyUrl = current.proxy;
|
|
734
866
|
}
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
// 会话名锁定开关的每次变化都落日志:它被意外关闭两次(页面里是关、
|
|
742
|
-
// 配置文件是开,来源不明),有记录才能查到是谁改的
|
|
743
|
-
if (typeof body.features.titleLock === 'boolean' && body.features.titleLock !== (loadConfig(configFile).features.titleLock !== false)) {
|
|
744
|
-
titleGenLog(dataRoot, `titleLock ${body.features.titleLock ? 'on' : 'off'}(此前为 ${!body.features.titleLock ? 'on' : 'off'})`);
|
|
867
|
+
if (body && typeof body === 'object' && body.proxyScopes && typeof body.proxyScopes === 'object') {
|
|
868
|
+
// 代理生效范围按单项提交(每个开关只改自己那项),即时生效
|
|
869
|
+
for (const k of ['plugins', 'deps', 'sync']) {
|
|
870
|
+
if (typeof body.proxyScopes[k] === 'boolean') current.proxyScopes[k] = body.proxyScopes[k];
|
|
871
|
+
}
|
|
872
|
+
activeProxyScopes = { ...current.proxyScopes };
|
|
745
873
|
}
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
if (body && typeof body === 'object' && typeof body.idleReclaimMinutes === 'number' && Number.isFinite(body.idleReclaimMinutes)) {
|
|
749
|
-
current.idleReclaimMinutes = Math.min(1440, Math.max(1, Math.round(body.idleReclaimMinutes)));
|
|
750
|
-
}
|
|
751
|
-
if (body && typeof body === 'object' && typeof body.idleReclaimStartupMinutes === 'number' && Number.isFinite(body.idleReclaimStartupMinutes)) {
|
|
752
|
-
current.idleReclaimStartupMinutes = Math.min(1440, Math.max(0, Math.round(body.idleReclaimStartupMinutes)));
|
|
753
|
-
}
|
|
754
|
-
if (body && typeof body === 'object' && body.styles && typeof body.styles === 'object') {
|
|
755
|
-
current.styles = applyStylesPartial(current.styles, body.styles);
|
|
756
|
-
}
|
|
757
|
-
// 会话快捷切换的键位(设置 → 快捷键里修改):键名固定,值限单个字母或数字
|
|
758
|
-
if (body && typeof body === 'object' && body.shortcuts && typeof body.shortcuts === 'object') {
|
|
759
|
-
const patch = {};
|
|
760
|
-
for (const k of ['switchLast', 'switchPrev', 'switchNext', 'switchRecent', 'switchAttention']) {
|
|
761
|
-
const v = body.shortcuts[k];
|
|
762
|
-
if (typeof v === 'string' && /^[a-z0-9]$/.test(v)) patch[k] = v;
|
|
874
|
+
if (body && typeof body === 'object' && typeof body.devMode === 'boolean') {
|
|
875
|
+
current.devMode = body.devMode;
|
|
763
876
|
}
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
if (body && typeof body === 'object' && body.statusBar && typeof body.statusBar === 'object') {
|
|
770
|
-
const next = { ...(current.statusBar || {}) };
|
|
771
|
-
if (Array.isArray(body.statusBar.items)) {
|
|
772
|
-
const valid = new Set(['ctx', 'questions', 'todayTokens', 'totalTokens', 'tasks']);
|
|
773
|
-
const seen = new Set();
|
|
774
|
-
const items = [];
|
|
775
|
-
for (const it of body.statusBar.items) {
|
|
776
|
-
if (!it || !valid.has(it.id) || seen.has(it.id)) continue;
|
|
777
|
-
seen.add(it.id);
|
|
778
|
-
items.push({ id: it.id, on: it.on !== false });
|
|
877
|
+
if (body && typeof body === 'object' && body.features && typeof body.features === 'object') {
|
|
878
|
+
// 会话名锁定开关的每次变化都落日志:它被意外关闭两次(页面里是关、
|
|
879
|
+
// 配置文件是开,来源不明),有记录才能查到是谁改的
|
|
880
|
+
if (typeof body.features.titleLock === 'boolean' && body.features.titleLock !== (loadConfig(configFile).features.titleLock !== false)) {
|
|
881
|
+
titleGenLog(dataRoot, `titleLock ${body.features.titleLock ? 'on' : 'off'}(此前为 ${!body.features.titleLock ? 'on' : 'off'})`);
|
|
779
882
|
}
|
|
780
|
-
|
|
883
|
+
applyFeaturesPartial(current.features, body.features);
|
|
884
|
+
}
|
|
885
|
+
if (body && typeof body === 'object' && typeof body.idleReclaimMinutes === 'number' && Number.isFinite(body.idleReclaimMinutes)) {
|
|
886
|
+
current.idleReclaimMinutes = Math.min(1440, Math.max(1, Math.round(body.idleReclaimMinutes)));
|
|
887
|
+
}
|
|
888
|
+
if (body && typeof body === 'object' && typeof body.idleReclaimStartupMinutes === 'number' && Number.isFinite(body.idleReclaimStartupMinutes)) {
|
|
889
|
+
current.idleReclaimStartupMinutes = Math.min(1440, Math.max(0, Math.round(body.idleReclaimStartupMinutes)));
|
|
781
890
|
}
|
|
782
|
-
if (
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
891
|
+
if (body && typeof body === 'object' && body.styles && typeof body.styles === 'object') {
|
|
892
|
+
current.styles = applyStylesPartial(current.styles, body.styles);
|
|
893
|
+
}
|
|
894
|
+
// 会话快捷切换的键位(设置 → 快捷键里修改):键名固定,值限单个字母或数字
|
|
895
|
+
if (body && typeof body === 'object' && body.shortcuts && typeof body.shortcuts === 'object') {
|
|
896
|
+
const patch = {};
|
|
897
|
+
for (const k of ['switchLast', 'switchPrev', 'switchNext', 'switchRecent', 'switchAttention']) {
|
|
898
|
+
const v = body.shortcuts[k];
|
|
899
|
+
if (typeof v === 'string' && /^[a-z0-9]$/.test(v)) patch[k] = v;
|
|
790
900
|
}
|
|
791
|
-
|
|
901
|
+
current.shortcuts = { ...(current.shortcuts || {}), ...patch };
|
|
792
902
|
}
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
pauseOnBattery: bt.bg && bt.bg.pauseOnBattery !== undefined ? bt.bg.pauseOnBattery : cur.bg.pauseOnBattery,
|
|
822
|
-
regions: bt.bg && bt.bg.regions !== undefined ? bt.bg.regions : cur.bg.regions,
|
|
823
|
-
},
|
|
824
|
-
};
|
|
825
|
-
current.theme = mergeThemeConfig(next);
|
|
826
|
-
}
|
|
827
|
-
if (body && typeof body === 'object' && body.titleGen && typeof body.titleGen === 'object') {
|
|
828
|
-
current.titleGen = mergeTitleGenConfig({ ...current.titleGen, ...body.titleGen });
|
|
829
|
-
}
|
|
830
|
-
// 一次性迁移标记(如别名迁移弹窗的“暂不迁移”):按项合并,只接受布尔值
|
|
831
|
-
if (body && typeof body === 'object' && body.migrations && typeof body.migrations === 'object') {
|
|
832
|
-
const patch = {};
|
|
833
|
-
for (const [k, v] of Object.entries(body.migrations)) {
|
|
834
|
-
if (typeof v === 'boolean') patch[k] = v;
|
|
903
|
+
// 状态栏统计(设置 → 样式 → 状态栏):items(任务统计项)与
|
|
904
|
+
// turnItems(每轮统计项)两个清单各自整表覆盖,谁在请求里就更新谁;
|
|
905
|
+
// id 白名单 + 去重保序,未知项丢弃
|
|
906
|
+
if (body && typeof body === 'object' && body.statusBar && typeof body.statusBar === 'object') {
|
|
907
|
+
const next = { ...(current.statusBar || {}) };
|
|
908
|
+
if (Array.isArray(body.statusBar.items)) {
|
|
909
|
+
const valid = new Set(['ctx', 'tokRate', 'questions', 'todayTokens', 'totalTokens', 'tasks']);
|
|
910
|
+
const seen = new Set();
|
|
911
|
+
const items = [];
|
|
912
|
+
for (const it of body.statusBar.items) {
|
|
913
|
+
if (!it || !valid.has(it.id) || seen.has(it.id)) continue;
|
|
914
|
+
seen.add(it.id);
|
|
915
|
+
items.push({ id: it.id, on: it.on !== false });
|
|
916
|
+
}
|
|
917
|
+
next.items = items;
|
|
918
|
+
}
|
|
919
|
+
if (Array.isArray(body.statusBar.turnItems)) {
|
|
920
|
+
const turnValid = new Set(['turnIn', 'turnOut', 'turnCache']);
|
|
921
|
+
const tseen = new Set();
|
|
922
|
+
const turnItems = [];
|
|
923
|
+
for (const it of body.statusBar.turnItems) {
|
|
924
|
+
if (!it || !turnValid.has(it.id) || tseen.has(it.id)) continue;
|
|
925
|
+
tseen.add(it.id);
|
|
926
|
+
turnItems.push({ id: it.id, on: it.on !== false });
|
|
927
|
+
}
|
|
928
|
+
next.turnItems = turnItems;
|
|
929
|
+
}
|
|
930
|
+
current.statusBar = next;
|
|
835
931
|
}
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
932
|
+
// 主题(设置 → 样式 → 颜色/背景图):按字段合并,白名单校验在
|
|
933
|
+
// mergeThemeConfig;library 的 file 与 folder 的目录可能指向已不存在的
|
|
934
|
+
// 目标(图已删/目录移走/同步后缺失),注入层按“取不到 = 无背景”降级
|
|
935
|
+
if (body && typeof body === 'object' && body.theme && typeof body.theme === 'object') {
|
|
936
|
+
const bt = body.theme;
|
|
937
|
+
const cur = current.theme;
|
|
938
|
+
const next = {
|
|
939
|
+
skin: bt.skin !== undefined ? bt.skin : cur.skin,
|
|
940
|
+
custom: bt.custom !== undefined ? bt.custom : cur.custom,
|
|
941
|
+
bg: {
|
|
942
|
+
mode: bt.bg && bt.bg.mode !== undefined ? bt.bg.mode : cur.bg.mode,
|
|
943
|
+
file: bt.bg && bt.bg.file !== undefined ? bt.bg.file : cur.bg.file,
|
|
944
|
+
folder: bt.bg && bt.bg.folder !== undefined ? bt.bg.folder : cur.bg.folder,
|
|
945
|
+
folderRandom: bt.bg && bt.bg.folderRandom !== undefined ? bt.bg.folderRandom : cur.bg.folderRandom,
|
|
946
|
+
url: bt.bg && bt.bg.url !== undefined ? bt.bg.url : cur.bg.url,
|
|
947
|
+
intervalMin: bt.bg && bt.bg.intervalMin !== undefined ? bt.bg.intervalMin : cur.bg.intervalMin,
|
|
948
|
+
fit: bt.bg && bt.bg.fit !== undefined ? bt.bg.fit : cur.bg.fit,
|
|
949
|
+
maskOpacity: bt.bg && bt.bg.maskOpacity !== undefined ? bt.bg.maskOpacity : cur.bg.maskOpacity,
|
|
950
|
+
blurPx: bt.bg && bt.bg.blurPx !== undefined ? bt.bg.blurPx : cur.bg.blurPx,
|
|
951
|
+
panelOpacity: bt.bg && bt.bg.panelOpacity !== undefined ? bt.bg.panelOpacity : cur.bg.panelOpacity,
|
|
952
|
+
transition: bt.bg && bt.bg.transition !== undefined ? bt.bg.transition : cur.bg.transition,
|
|
953
|
+
fpsCap: bt.bg && bt.bg.fpsCap !== undefined ? bt.bg.fpsCap : cur.bg.fpsCap,
|
|
954
|
+
videoVolume: bt.bg && bt.bg.videoVolume !== undefined ? bt.bg.videoVolume : cur.bg.videoVolume,
|
|
955
|
+
playbackRate: bt.bg && bt.bg.playbackRate !== undefined ? bt.bg.playbackRate : cur.bg.playbackRate,
|
|
956
|
+
pauseOnHidden: bt.bg && bt.bg.pauseOnHidden !== undefined ? bt.bg.pauseOnHidden : cur.bg.pauseOnHidden,
|
|
957
|
+
pauseOnBlur: bt.bg && bt.bg.pauseOnBlur !== undefined ? bt.bg.pauseOnBlur : cur.bg.pauseOnBlur,
|
|
958
|
+
pauseOnBattery: bt.bg && bt.bg.pauseOnBattery !== undefined ? bt.bg.pauseOnBattery : cur.bg.pauseOnBattery,
|
|
959
|
+
dialogFrost: bt.bg && bt.bg.dialogFrost !== undefined ? bt.bg.dialogFrost : cur.bg.dialogFrost,
|
|
960
|
+
regions: bt.bg && bt.bg.regions !== undefined ? bt.bg.regions : cur.bg.regions,
|
|
961
|
+
},
|
|
962
|
+
};
|
|
963
|
+
current.theme = mergeThemeConfig(next);
|
|
964
|
+
}
|
|
965
|
+
if (body && typeof body === 'object' && body.titleGen && typeof body.titleGen === 'object') {
|
|
966
|
+
current.titleGen = mergeTitleGenConfig({ ...current.titleGen, ...body.titleGen });
|
|
967
|
+
}
|
|
968
|
+
// 一次性迁移标记(如别名迁移弹窗的“暂不迁移”):按项合并,只接受布尔值
|
|
969
|
+
if (body && typeof body === 'object' && body.migrations && typeof body.migrations === 'object') {
|
|
970
|
+
const patch = {};
|
|
971
|
+
for (const [k, v] of Object.entries(body.migrations)) {
|
|
972
|
+
if (typeof v === 'boolean') patch[k] = v;
|
|
973
|
+
}
|
|
974
|
+
current.migrations = { ...(current.migrations || {}), ...patch };
|
|
975
|
+
}
|
|
976
|
+
if (!saveConfig(configFile, current)) {
|
|
977
|
+
json(res, 500, { ok: false, code: 'config-unreadable', error: 'zcodepro.json 读取失败或已损坏,保存中止(请先修好配置文件)' });
|
|
978
|
+
return;
|
|
979
|
+
}
|
|
980
|
+
json(res, 200, { ok: true, config: current });
|
|
981
|
+
});
|
|
840
982
|
return;
|
|
841
983
|
}
|
|
842
984
|
// —— ZCode CLI 行为配置(设置 → 行为 → ZCode CLI):读写 ~/.zcode/cli/config.json
|
|
@@ -883,7 +1025,7 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
883
1025
|
json(res, 200, zcodeConfigSnapshot(zcodeDataRoot()));
|
|
884
1026
|
return;
|
|
885
1027
|
}
|
|
886
|
-
// —— 主题背景图库:列表 / base64 上传 /
|
|
1028
|
+
// —— 主题背景图库:列表 / base64 上传 / 删除(取文件见上方的 /bg/file,URL 带 ?t= token)——
|
|
887
1029
|
if (req.method === 'GET' && url.pathname === '/bg') {
|
|
888
1030
|
json(res, 200, { ok: true, files: listBgFiles(dataRoot), maxCount: BG_MAX_COUNT });
|
|
889
1031
|
return;
|
|
@@ -922,7 +1064,8 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
922
1064
|
}
|
|
923
1065
|
try {
|
|
924
1066
|
mkdirSync(dir, { recursive: true });
|
|
925
|
-
|
|
1067
|
+
// 临时名带 pid+随机:两个写者(上传/同步下载)撞同一文件名时不共用一个 .tmp
|
|
1068
|
+
const tmp = join(dir, `${name}.${process.pid}.${Date.now().toString(36)}.tmp`);
|
|
926
1069
|
writeFileSync(tmp, buf);
|
|
927
1070
|
renameOrReplace(tmp, join(dir, name));
|
|
928
1071
|
} catch (errBg) {
|
|
@@ -1031,7 +1174,7 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1031
1174
|
return;
|
|
1032
1175
|
}
|
|
1033
1176
|
if (!TRANSCODE_FPS.has(fps)) {
|
|
1034
|
-
json(res, 400, { ok: false, code: 'transcode-fps', error: '
|
|
1177
|
+
json(res, 400, { ok: false, code: 'transcode-fps', error: `帧率上限仅支持 ${[...TRANSCODE_FPS].join('/')}` });
|
|
1035
1178
|
return;
|
|
1036
1179
|
}
|
|
1037
1180
|
const srcStat = statSync(src);
|
|
@@ -1057,20 +1200,23 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1057
1200
|
const vf = `fps=${fps},scale=min(1920\\,iw):min(1920\\,ih):force_original_aspect_ratio=decrease`;
|
|
1058
1201
|
let child;
|
|
1059
1202
|
try {
|
|
1060
|
-
child = spawn('ffmpeg', ['-y', '-i', src, '-vf', vf, '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '23', '-c:a', 'aac', '-b:a', '128k', '-movflags', '+faststart', tmp], { stdio: 'ignore' });
|
|
1203
|
+
child = spawn('ffmpeg', ['-y', '-i', src, '-vf', vf, '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '23', '-c:a', 'aac', '-b:a', '128k', '-movflags', '+faststart', tmp], { stdio: 'ignore', windowsHide: true });
|
|
1204
|
+
transcodeChildren.add(child);
|
|
1061
1205
|
} catch (errSpawn) {
|
|
1062
1206
|
transcodeJobs.delete(key); // 同步抛错也把名额放掉
|
|
1063
1207
|
throw errSpawn;
|
|
1064
1208
|
}
|
|
1065
1209
|
child.on('exit', (code) => {
|
|
1066
1210
|
transcodeJobs.delete(key);
|
|
1211
|
+
transcodeChildren.delete(child);
|
|
1067
1212
|
try {
|
|
1068
1213
|
if (code === 0) renameOrReplace(tmp, out); // renameOrReplace 扛得住 Windows 文件占用
|
|
1069
1214
|
else rmSync(tmp, { force: true });
|
|
1070
1215
|
} catch { /* 缓存目录写失败:下次再试 */ }
|
|
1071
1216
|
});
|
|
1072
|
-
child.on('error', () => { transcodeJobs.delete(key); });
|
|
1073
|
-
|
|
1217
|
+
child.on('error', () => { transcodeJobs.delete(key); transcodeChildren.delete(child); });
|
|
1218
|
+
// 看门狗直接 SIGKILL(与 jobRun 一致):ffmpeg 不退则 exit 不触发、转码名额泄漏
|
|
1219
|
+
const killTimer = setTimeout(() => { try { child.kill('SIGKILL'); } catch { /* 已退出 */ } }, 30 * 60 * 1000);
|
|
1074
1220
|
child.on('exit', () => clearTimeout(killTimer));
|
|
1075
1221
|
}
|
|
1076
1222
|
json(res, 200, { ok: true, key, ready: false });
|
|
@@ -1106,9 +1252,14 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1106
1252
|
return;
|
|
1107
1253
|
}
|
|
1108
1254
|
if (req.method === 'GET' && url.pathname === '/bg/folder/list') {
|
|
1109
|
-
// dir
|
|
1255
|
+
// dir 查询参数:分区背景列自己目录时传入;缺省列全局设置的目录。
|
|
1256
|
+
// dir 只认用户配置过的目录(与取文件路由同一判定),不合法与文件路由同款报错
|
|
1110
1257
|
const qDir = url.searchParams.get('dir');
|
|
1111
|
-
|
|
1258
|
+
if (qDir && !bgFolderDirAllowed(loadConfig(configFile).theme.bg, qDir)) {
|
|
1259
|
+
json(res, 400, { ok: false, error: 'dir 参数无效或未配置' });
|
|
1260
|
+
return;
|
|
1261
|
+
}
|
|
1262
|
+
const dir = qDir || loadConfig(configFile).theme.bg.folder;
|
|
1112
1263
|
if (!dir || !existsSync(dir)) { json(res, 200, { ok: true, files: [], missing: true, dir: dir || '' }); return; }
|
|
1113
1264
|
try {
|
|
1114
1265
|
const r = listFolderBg(dir);
|
|
@@ -1192,7 +1343,7 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1192
1343
|
}
|
|
1193
1344
|
if (req.method === 'POST' && url.pathname === '/project/alias') {
|
|
1194
1345
|
const body = await readBody(req);
|
|
1195
|
-
json(res, ...setAlias(body, configFile));
|
|
1346
|
+
json(res, ...(await setAlias(body, configFile)));
|
|
1196
1347
|
return;
|
|
1197
1348
|
}
|
|
1198
1349
|
if (req.method === 'POST' && url.pathname === '/project/relocate') {
|
|
@@ -1207,8 +1358,9 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1207
1358
|
json(res, 200, { ok: true, ...(await pickFolderSystem(start, title)) });
|
|
1208
1359
|
return;
|
|
1209
1360
|
}
|
|
1210
|
-
// 会话拖动排序持久化:
|
|
1211
|
-
//
|
|
1361
|
+
// 会话拖动排序持久化:hint = 拖动落点所在的列表(project/pinned/section,
|
|
1362
|
+
// 缺省按数据判定),旧注入包的 scope(workspace/group-members)回退认作 hint;
|
|
1363
|
+
// 工作区列表重盖 updated_at,分组会话重写 members.sort_order
|
|
1212
1364
|
if (req.method === 'POST' && url.pathname === '/task-order') {
|
|
1213
1365
|
const body = await readBody(req);
|
|
1214
1366
|
const ordered = Array.isArray(body?.ordered) ? body.ordered.filter((k) => typeof k === 'string') : [];
|
|
@@ -1216,13 +1368,7 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1216
1368
|
json(res, 400, { ok: false, code: 'invalid-request', error: 'ordered 不能为空' });
|
|
1217
1369
|
return;
|
|
1218
1370
|
}
|
|
1219
|
-
|
|
1220
|
-
if (body.scope === 'workspace') result = await reorderWorkspaceTasks(dataRoot, ordered);
|
|
1221
|
-
else if (body.scope === 'group-members') result = await reorderGroupMembers(dataRoot, ordered);
|
|
1222
|
-
else {
|
|
1223
|
-
json(res, 400, { ok: false, code: 'invalid-request', error: '无效的 scope' });
|
|
1224
|
-
return;
|
|
1225
|
-
}
|
|
1371
|
+
const result = await reorderTasks(dataRoot, ordered, body.hint ?? body.scope);
|
|
1226
1372
|
if (result.error) {
|
|
1227
1373
|
json(res, 400, { ok: false, code: result.code, error: result.error });
|
|
1228
1374
|
return;
|
|
@@ -1258,29 +1404,36 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1258
1404
|
if (req.method === 'POST' && url.pathname === '/title-gen') {
|
|
1259
1405
|
const body = await readBody(req);
|
|
1260
1406
|
if (body && typeof body === 'object' && body.titleGen && typeof body.titleGen === 'object') {
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
const found = listTitleGenProviders().find((p) => p.id === providerId);
|
|
1269
|
-
if (found) {
|
|
1270
|
-
next.baseUrl = found.baseUrl;
|
|
1271
|
-
next.apiKey = found.apiKey;
|
|
1272
|
-
next.format = found.format;
|
|
1273
|
-
}
|
|
1274
|
-
// 找不到(手输 id 或已删):保留原有副本字段不动
|
|
1275
|
-
} else if (providerId === 'session') {
|
|
1407
|
+
// 读改写(loadConfig→改→saveConfig)放进跨进程锁内同步执行,
|
|
1408
|
+
// 防止与别的写入方互相覆盖整份配置
|
|
1409
|
+
await withConfigLock(configFile, () => {
|
|
1410
|
+
const current = loadConfig(configFile);
|
|
1411
|
+
const next = { ...current.titleGen, ...body.titleGen };
|
|
1412
|
+
// 选了列表内供应商:同步解析并保存其地址/密钥/协议副本——供应商日后
|
|
1413
|
+
// 被删,这份副本仍可直连(界面标注“已删除”并展开字段);
|
|
1276
1414
|
// 跟随会话不存副本(每次调用时按该会话实时解析)
|
|
1277
|
-
next.
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1415
|
+
const providerId = (next.provider || '').trim();
|
|
1416
|
+
if (providerId && providerId !== 'session') {
|
|
1417
|
+
const found = listTitleGenProviders().find((p) => p.id === providerId);
|
|
1418
|
+
if (found) {
|
|
1419
|
+
next.baseUrl = found.baseUrl;
|
|
1420
|
+
next.apiKey = found.apiKey;
|
|
1421
|
+
next.format = found.format;
|
|
1422
|
+
}
|
|
1423
|
+
// 找不到(手输 id 或已删):保留原有副本字段不动
|
|
1424
|
+
} else if (providerId === 'session') {
|
|
1425
|
+
// 跟随会话不存副本(每次调用时按该会话实时解析)
|
|
1426
|
+
next.baseUrl = '';
|
|
1427
|
+
next.apiKey = '';
|
|
1428
|
+
next.format = '';
|
|
1429
|
+
}
|
|
1430
|
+
current.titleGen = mergeTitleGenConfig(next);
|
|
1431
|
+
if (!saveConfig(configFile, current)) {
|
|
1432
|
+
json(res, 500, { ok: false, code: 'config-unreadable', error: 'zcodepro.json 读取失败或已损坏,保存中止(请先修好配置文件)' });
|
|
1433
|
+
return;
|
|
1434
|
+
}
|
|
1435
|
+
json(res, 200, { ok: true, titleGen: current.titleGen });
|
|
1436
|
+
});
|
|
1284
1437
|
return;
|
|
1285
1438
|
}
|
|
1286
1439
|
json(res, 400, { ok: false, code: 'invalid-request', error: 'body 需包含 titleGen 对象' });
|
|
@@ -1329,66 +1482,74 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1329
1482
|
json(res, 200, { ok: true, title, written: false, store: 'skipped: overridden' });
|
|
1330
1483
|
return;
|
|
1331
1484
|
}
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
// CLI 库不可写(旧版无 title_source 列 / 无该会话行)不阻断:退回
|
|
1337
|
-
// 单写任务索引的旧行为;任务索引随后失败也不回滚 CLI——同步器会补
|
|
1338
|
-
for (let attempt = 0; ; attempt++) {
|
|
1339
|
-
try {
|
|
1340
|
-
const r = await setCustomSessionTitle(dataRoot, sessId, title);
|
|
1341
|
-
store = r.written ? '' : (r.skipped || 'skipped');
|
|
1342
|
-
break;
|
|
1343
|
-
} catch (err) {
|
|
1344
|
-
if (err.code === 'index-busy' && attempt < 2) {
|
|
1345
|
-
await new Promise((r) => setTimeout(r, 1200));
|
|
1346
|
-
continue;
|
|
1347
|
-
}
|
|
1348
|
-
store = 'error: ' + (err?.message || err);
|
|
1349
|
-
titleGenLog(dataRoot, `cli-store-error sess=${sessId.slice(0, 13)} err=${err?.message || err}`);
|
|
1350
|
-
break;
|
|
1351
|
-
}
|
|
1352
|
-
}
|
|
1353
|
-
// 写库撞上宿主写入时稍候重试(起名不急这几秒)
|
|
1354
|
-
for (let attempt = 0; ; attempt++) {
|
|
1355
|
-
try {
|
|
1356
|
-
const r = await setTaskTitleIfNotOverridden(dataRoot, sessId, title);
|
|
1357
|
-
written = r.written;
|
|
1358
|
-
break;
|
|
1359
|
-
} catch (err) {
|
|
1360
|
-
if (err.code === 'index-busy' && attempt < 2) {
|
|
1361
|
-
await new Promise((r) => setTimeout(r, 1200));
|
|
1362
|
-
continue;
|
|
1363
|
-
}
|
|
1364
|
-
titleGenLog(dataRoot, `index-error sess=${sessId.slice(0, 13)} err=${err?.message || err}`);
|
|
1365
|
-
json(res, 500, { ok: false, code: err.code || 'index-error', error: err.message });
|
|
1366
|
-
return;
|
|
1367
|
-
}
|
|
1485
|
+
const r = await writeGeneratedTitle(dataRoot, configFile, sessId, title);
|
|
1486
|
+
if (r.error) {
|
|
1487
|
+
json(res, 500, { ok: false, code: r.error.code || 'index-error', error: r.error.message });
|
|
1488
|
+
return;
|
|
1368
1489
|
}
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
if (sessId && store === '') {
|
|
1372
|
-
const c = loadConfig(configFile);
|
|
1373
|
-
c.titleGen.customWritten = { ...(c.titleGen.customWritten || {}), [sessId]: { title, at: Date.now() } };
|
|
1374
|
-
saveConfig(configFile, c);
|
|
1490
|
+
written = r.written;
|
|
1491
|
+
store = r.store;
|
|
1375
1492
|
}
|
|
1376
1493
|
json(res, 200, { ok: true, title, written, store });
|
|
1377
1494
|
return;
|
|
1378
1495
|
}
|
|
1496
|
+
// 手动自动重命名(任务行悬浮按钮 / 右键菜单入口):取会话最近 N 轮问答按
|
|
1497
|
+
// 提示词生成标题并按“手动重命名”写库。用户显式动作:已重命名过也照写
|
|
1498
|
+
//(force),不受启用开关限制(入口各有开关);生成失败交外层统一 500
|
|
1499
|
+
if (req.method === 'POST' && url.pathname === '/title-gen/rename') {
|
|
1500
|
+
const body = await readBody(req);
|
|
1501
|
+
const sessId = typeof body?.sessId === 'string' && /^(?:sess|session)_[A-Za-z0-9._-]+$/.test(body.sessId) ? body.sessId : '';
|
|
1502
|
+
if (!sessId) {
|
|
1503
|
+
json(res, 400, { ok: false, code: 'invalid-request', error: 'sessId 不能为空' });
|
|
1504
|
+
return;
|
|
1505
|
+
}
|
|
1506
|
+
const cfg = loadConfig(configFile).titleGen;
|
|
1507
|
+
let material;
|
|
1508
|
+
try {
|
|
1509
|
+
material = await readRecentQa(dataRoot, sessId, cfg.recentQa);
|
|
1510
|
+
} catch (err) {
|
|
1511
|
+
titleGenLog(dataRoot, `rename-read-error sess=${sessId.slice(0, 13)} err=${err?.message || err}`);
|
|
1512
|
+
json(res, 500, { ok: false, code: 'read-error', error: err?.message || '读取会话内容失败' });
|
|
1513
|
+
return;
|
|
1514
|
+
}
|
|
1515
|
+
if (!material) {
|
|
1516
|
+
json(res, 200, { ok: false, code: 'no-content', error: '会话还没有问答内容' });
|
|
1517
|
+
return;
|
|
1518
|
+
}
|
|
1519
|
+
let title;
|
|
1520
|
+
try {
|
|
1521
|
+
title = await generateTitleWith(cfg, material, dataRoot, sessId);
|
|
1522
|
+
} catch (err) {
|
|
1523
|
+
titleGenLog(dataRoot, `rename-generate-failed sess=${sessId.slice(0, 13)} err=${err?.message || err}`);
|
|
1524
|
+
throw err; // 交给外层统一 500
|
|
1525
|
+
}
|
|
1526
|
+
const r = await writeGeneratedTitle(dataRoot, configFile, sessId, title, { force: true });
|
|
1527
|
+
if (r.error) {
|
|
1528
|
+
json(res, 500, { ok: false, code: r.error.code || 'index-error', error: r.error.message });
|
|
1529
|
+
return;
|
|
1530
|
+
}
|
|
1531
|
+
json(res, 200, { ok: true, title, written: r.written, store: r.store });
|
|
1532
|
+
return;
|
|
1533
|
+
}
|
|
1379
1534
|
// —— zcode-vision 插件(图片视觉代理):设置弹窗“视觉代理”标签页读写 ————
|
|
1380
1535
|
if (req.method === 'GET' && url.pathname === '/vision') {
|
|
1381
|
-
const file =
|
|
1536
|
+
const file = visionFile;
|
|
1382
1537
|
let parsed = readJsonFile(file);
|
|
1383
1538
|
// 装了 zcode-pro 默认启用识图卡片(插件纯安装默认关,纯文本展示):
|
|
1384
1539
|
// 只补从未写过的配置,用户显式设过 cardUi(含 false)不覆盖
|
|
1385
1540
|
if (parsed && typeof parsed === 'object' && !('cardUi' in parsed)) {
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1541
|
+
// 写前重读一次拿最新值合并:与插件侧的模板升级等写方并发时,
|
|
1542
|
+
// 拿读取时的旧快照整份写回会把对方刚写的键盖掉
|
|
1543
|
+
const fresh = readJsonFile(file);
|
|
1544
|
+
const base = (fresh && typeof fresh === 'object') ? fresh : parsed;
|
|
1545
|
+
if (!('cardUi' in base)) {
|
|
1546
|
+
const merged = { ...base, cardUi: true };
|
|
1547
|
+
try {
|
|
1548
|
+
const tmp = `${file}.${process.pid}.${Date.now().toString(36)}.tmp`; // 防多写者撕裂
|
|
1549
|
+
writeFileSync(tmp, JSON.stringify(merged, null, 2) + '\n', { encoding: 'utf-8', mode: 0o600 });
|
|
1550
|
+
renameSync(tmp, file);
|
|
1551
|
+
} catch { /* 补写失败下次再试,不阻塞读取 */ }
|
|
1552
|
+
}
|
|
1392
1553
|
}
|
|
1393
1554
|
if (parsed === null && existsSync(file)) {
|
|
1394
1555
|
json(res, 500, { ok: false, code: 'vision-read', error: 'zcode-vision.json 不是合法 JSON' });
|
|
@@ -1405,15 +1566,15 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1405
1566
|
return;
|
|
1406
1567
|
}
|
|
1407
1568
|
try {
|
|
1408
|
-
const file =
|
|
1569
|
+
const file = visionFile;
|
|
1409
1570
|
// 与磁盘旧配置合并(本块曾两次被并发改动覆盖回全量覆盖):前端按自己
|
|
1410
1571
|
// 的字段重建整份配置,直接覆盖会丢插件新增、面板还不认识的键
|
|
1411
1572
|
//(cardSandboxBudget/cardUi/interceptMode 等)
|
|
1412
1573
|
const merged = { ...(readJsonFile(file) || {}), ...cfg };
|
|
1413
1574
|
// forceIntercept 为 null = 面板选了「自动」:从磁盘配置删掉该键,恢复插件缺省联动
|
|
1414
1575
|
if (cfg.forceIntercept === null) delete merged.forceIntercept;
|
|
1415
|
-
const tmp = file
|
|
1416
|
-
writeFileSync(tmp, JSON.stringify(merged, null, 2) + '\n', 'utf-8');
|
|
1576
|
+
const tmp = `${file}.${process.pid}.${Date.now().toString(36)}.tmp`; // 防多写者撕裂
|
|
1577
|
+
writeFileSync(tmp, JSON.stringify(merged, null, 2) + '\n', { encoding: 'utf-8', mode: 0o600 });
|
|
1417
1578
|
renameSync(tmp, file);
|
|
1418
1579
|
} catch (err2) {
|
|
1419
1580
|
json(res, 500, { ok: false, code: 'vision-write', error: '写入 zcode-vision.json 失败: ' + (err2?.message || err2) });
|
|
@@ -1633,9 +1794,15 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1633
1794
|
return;
|
|
1634
1795
|
} else if (body && 'interval' in body) {
|
|
1635
1796
|
try {
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1797
|
+
// 只改 powerWatchInterval 一个键:readHeadroomConfig 会把非规范值归一
|
|
1798
|
+
// 成默认值(插件侧是宽松读法),整份写回会把 backend 之类的本机值打回默认。
|
|
1799
|
+
// 套配置锁:与同步导入、setHeadroomUsage 等自家写方互斥(插件侧写方走
|
|
1800
|
+
// 它自己的生命周期锁,两边共存仍留极小窗口,写回本身是原子改名兜底)
|
|
1801
|
+
await withConfigLock(file, () => {
|
|
1802
|
+
const cfg = readJsonFile(file) || {};
|
|
1803
|
+
cfg.powerWatchInterval = clampInt(body.interval, 10, 3600, Number(cfg.powerWatchInterval) || 60);
|
|
1804
|
+
writeHeadroomConfig(file, cfg);
|
|
1805
|
+
});
|
|
1639
1806
|
} catch (err) {
|
|
1640
1807
|
json(res, 500, { ok: false, code: 'headroom-write', error: '写入 headroom.json 失败: ' + (err?.message || err) });
|
|
1641
1808
|
return;
|
|
@@ -1658,8 +1825,10 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1658
1825
|
// 源码目录(有 package.json 与 esbuild)先构建,安装副本没有构建环境则跳过
|
|
1659
1826
|
let built = false;
|
|
1660
1827
|
const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..');
|
|
1661
|
-
|
|
1662
|
-
|
|
1828
|
+
// Windows 上优先 esbuild.exe:无扩展名的 bin/esbuild 是 JS 垫片,spawnSync 跑不起来
|
|
1829
|
+
const esbuildNames = process.platform === 'win32' ? ['esbuild.exe', 'esbuild'] : ['esbuild', 'esbuild.exe'];
|
|
1830
|
+
const esbuildBin = esbuildNames
|
|
1831
|
+
.map((n) => join(repoRoot, 'node_modules', 'esbuild', 'bin', n))
|
|
1663
1832
|
.find((p) => existsSync(p)) || '';
|
|
1664
1833
|
if (esbuildBin) {
|
|
1665
1834
|
try {
|
|
@@ -1680,7 +1849,10 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1680
1849
|
});
|
|
1681
1850
|
child.unref();
|
|
1682
1851
|
} catch { /* 拉不起来就只能等下次手动重启 */ }
|
|
1683
|
-
setTimeout(() =>
|
|
1852
|
+
setTimeout(() => {
|
|
1853
|
+
try { dispose(); } catch { /* ignore */ } // 收掉残留 ffmpeg 子进程,防孤儿与新实例抢写缓存
|
|
1854
|
+
process.exit(0);
|
|
1855
|
+
}, 250);
|
|
1684
1856
|
}, 150);
|
|
1685
1857
|
return;
|
|
1686
1858
|
}
|
|
@@ -1761,22 +1933,29 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1761
1933
|
}
|
|
1762
1934
|
if (req.method === 'POST' && url.pathname === '/sync') {
|
|
1763
1935
|
const body = await readBody(req);
|
|
1764
|
-
|
|
1765
|
-
//
|
|
1766
|
-
|
|
1767
|
-
const
|
|
1768
|
-
|
|
1769
|
-
|
|
1936
|
+
// 读改写(loadConfig→改→saveConfig)放进跨进程锁内同步执行,
|
|
1937
|
+
// 防止与别的写入方互相覆盖整份配置
|
|
1938
|
+
await withConfigLock(configFile, () => {
|
|
1939
|
+
const current = loadConfig(configFile);
|
|
1940
|
+
// 表单(类型/URL/登录/密码)与同步内容开关分开提交:表单全量替换,开关只改单项
|
|
1941
|
+
if (body && typeof body === 'object' && body.sync && typeof body.sync === 'object') {
|
|
1942
|
+
const v = validateSyncForm(body.sync);
|
|
1943
|
+
if (v.error) {
|
|
1944
|
+
json(res, 400, { ok: false, code: 'sync-invalid', error: v.error });
|
|
1945
|
+
return;
|
|
1946
|
+
}
|
|
1947
|
+
Object.assign(current.sync, v.sync);
|
|
1948
|
+
}
|
|
1949
|
+
if (body && typeof body === 'object' && body.include && typeof body.include === 'object') {
|
|
1950
|
+
if (typeof body.include.zcodepro === 'boolean') current.sync.include.zcodepro = body.include.zcodepro;
|
|
1951
|
+
if (typeof body.include.model === 'boolean') current.sync.include.model = body.include.model;
|
|
1952
|
+
}
|
|
1953
|
+
if (!saveConfig(configFile, current)) {
|
|
1954
|
+
json(res, 500, { ok: false, code: 'config-unreadable', error: 'zcodepro.json 读取失败或已损坏,保存中止(请先修好配置文件)' });
|
|
1770
1955
|
return;
|
|
1771
1956
|
}
|
|
1772
|
-
|
|
1773
|
-
}
|
|
1774
|
-
if (body && typeof body === 'object' && body.include && typeof body.include === 'object') {
|
|
1775
|
-
if (typeof body.include.zcodepro === 'boolean') current.sync.include.zcodepro = body.include.zcodepro;
|
|
1776
|
-
if (typeof body.include.model === 'boolean') current.sync.include.model = body.include.model;
|
|
1777
|
-
}
|
|
1778
|
-
saveConfig(configFile, current);
|
|
1779
|
-
json(res, 200, { ok: true, sync: current.sync });
|
|
1957
|
+
json(res, 200, { ok: true, sync: current.sync });
|
|
1958
|
+
});
|
|
1780
1959
|
return;
|
|
1781
1960
|
}
|
|
1782
1961
|
if (req.method === 'POST' && url.pathname === '/sync/run') {
|
|
@@ -1786,8 +1965,12 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1786
1965
|
json(res, 400, { ok: false, code: 'invalid-request', error: 'direction 只能是 push 或 pull' });
|
|
1787
1966
|
return;
|
|
1788
1967
|
}
|
|
1789
|
-
|
|
1790
|
-
|
|
1968
|
+
// 同 direction 的并发触发共用同一次执行结果(见 enqueueSyncRun),
|
|
1969
|
+
// 不同 direction 串行排队
|
|
1970
|
+
const r = await enqueueSyncRun(direction, async () => {
|
|
1971
|
+
const cfg = loadConfig(configFile);
|
|
1972
|
+
return runSettingsSync({ direction, dataRoot, configFile, config: cfg, proxyUrl: proxyUrlFor('sync') });
|
|
1973
|
+
});
|
|
1791
1974
|
if (r.error) {
|
|
1792
1975
|
json(res, r.status || 500, { ok: false, code: r.code || 'sync-run', error: r.error });
|
|
1793
1976
|
return;
|
|
@@ -1821,6 +2004,10 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1821
2004
|
json(res, 400, { ok: false, code: 'sync-not-configured', error: '请先填写 WebDAV URL 并保存' });
|
|
1822
2005
|
return;
|
|
1823
2006
|
}
|
|
2007
|
+
if (!webdavHttpSchemeOk(sync.url)) {
|
|
2008
|
+
json(res, 400, { ok: false, code: 'sync-not-configured', error: '公网 WebDAV 地址需改用 https(http 明文传输登录名和密码);内网或回环地址可继续用 http' });
|
|
2009
|
+
return;
|
|
2010
|
+
}
|
|
1824
2011
|
const r = await listSyncVersions(sync, proxyUrlFor('sync'));
|
|
1825
2012
|
if (r.error) {
|
|
1826
2013
|
json(res, r.status || 500, { ok: false, code: r.code || 'sync-request', error: r.error });
|
|
@@ -1848,6 +2035,10 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1848
2035
|
json(res, 400, { ok: false, code: 'sync-not-configured', error: '请先填写 WebDAV URL 并保存' });
|
|
1849
2036
|
return;
|
|
1850
2037
|
}
|
|
2038
|
+
if (!webdavHttpSchemeOk(sync.url)) {
|
|
2039
|
+
json(res, 400, { ok: false, code: 'sync-not-configured', error: '公网 WebDAV 地址需改用 https(http 明文传输登录名和密码);内网或回环地址可继续用 http' });
|
|
2040
|
+
return;
|
|
2041
|
+
}
|
|
1851
2042
|
const remoteMissing = () => json(res, 404, { ok: false, code: 'sync-remote-missing', error: `云端文件 ${file} 不存在(可能已被删除)` });
|
|
1852
2043
|
if (action === 'apply') {
|
|
1853
2044
|
const remote = await fetchSyncNamedDoc(sync, proxyUrlFor('sync'), file);
|
|
@@ -1862,6 +2053,10 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1862
2053
|
const kind = file.startsWith('model') ? 'model' : 'zcodepro';
|
|
1863
2054
|
sync.lastPullAt = Date.now();
|
|
1864
2055
|
const r = applySyncDocs({ docs: { [kind]: remote.doc.data }, dataRoot, configFile, config, sync });
|
|
2056
|
+
if (r && r.error) {
|
|
2057
|
+
json(res, r.status || 500, { ok: false, code: r.code, error: r.error });
|
|
2058
|
+
return;
|
|
2059
|
+
}
|
|
1865
2060
|
json(res, 200, { ok: true, applied: r.applied, sync: loadConfig(configFile).sync });
|
|
1866
2061
|
return;
|
|
1867
2062
|
}
|
|
@@ -1910,7 +2105,8 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1910
2105
|
return;
|
|
1911
2106
|
}
|
|
1912
2107
|
try {
|
|
1913
|
-
writeFileSync(target, r.body, 'utf8');
|
|
2108
|
+
writeFileSync(target, r.body, { encoding: 'utf8', mode: 0o600 }); // 导出内容含明文 apiKey,限制本人读写
|
|
2109
|
+
try { chmodSync(target, 0o600); } catch { /* 覆盖同名旧文件时 mode 不生效,补一次 */ }
|
|
1914
2110
|
} catch (err) {
|
|
1915
2111
|
json(res, 500, { ok: false, code: 'sync-export', error: `写入 ${target} 失败: ${err?.message || err}` });
|
|
1916
2112
|
return;
|
|
@@ -1923,8 +2119,13 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1923
2119
|
// model-io-*.jsonl 每行一次模型调用,response.usage 有分项 token;成本字段
|
|
1924
2120
|
// 官方未落本地,成本类统计项由注入侧按“无数据自动隐藏”处理
|
|
1925
2121
|
if (req.method === 'GET' && url.pathname === '/stats/usage') {
|
|
1926
|
-
|
|
1927
|
-
|
|
2122
|
+
// 会话 id 校验同 sessId 白名单:不像会话 id 的一律按全局口径处理
|
|
2123
|
+
//(降级后注入侧仍按“本会话”展示全局速率,官方改 key 格式时才会踩到)
|
|
2124
|
+
const rawSid = url.searchParams.get('session') || '';
|
|
2125
|
+
const sessionId = /^(?:sess|session)_[A-Za-z0-9._-]+$/.test(rawSid) ? rawSid : '';
|
|
2126
|
+
// turns=0 跳过分钟桶聚合(状态栏只读 global,不白建每轮桶)
|
|
2127
|
+
const wantTurns = url.searchParams.get('turns') !== '0';
|
|
2128
|
+
const { global, recentTurns } = collectUsageStats(sessionId, wantTurns);
|
|
1928
2129
|
// 任务总数 60 秒缓存:状态栏每 2 秒请求一次,不必每次开关 SQLite
|
|
1929
2130
|
if (Date.now() - tasksCountAt > 60_000) {
|
|
1930
2131
|
tasksCountAt = Date.now();
|
|
@@ -1935,13 +2136,19 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1935
2136
|
return;
|
|
1936
2137
|
}
|
|
1937
2138
|
if (req.method === 'GET' && url.pathname === '/plugins/status') {
|
|
1938
|
-
|
|
1939
|
-
//
|
|
1940
|
-
//
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
await
|
|
1944
|
-
|
|
2139
|
+
// 市场同步与更新任务共用同一条串行队列,不能绕过它:两处同时 clone/pull
|
|
2140
|
+
// 同一个市场目录会互相删对方的中间目录(ENOENT/坏目录)。
|
|
2141
|
+
// 有更新任务在跑/排队时整个跳过(任务自身会做市场同步并刷新时间戳),
|
|
2142
|
+
// 状态页轮询不排队等待、不能被长任务挂住;检查与入队在同一同步段内完成
|
|
2143
|
+
if (!pluginsUpdateJobs.size) {
|
|
2144
|
+
await runPluginsQueued(async () => {
|
|
2145
|
+
await ensureZcodePluginsMarketplace();
|
|
2146
|
+
if (Date.now() - lastMarketplaceSync > 30 * 60 * 1000) {
|
|
2147
|
+
await ensureZcodePluginsCloneFresh();
|
|
2148
|
+
await runZcodeCli(['plugins', 'marketplace', 'update', ZCODE_PLUGINS_MARKETPLACE], 60000);
|
|
2149
|
+
lastMarketplaceSync = Date.now();
|
|
2150
|
+
}
|
|
2151
|
+
});
|
|
1945
2152
|
}
|
|
1946
2153
|
const status = pluginUpdateStatus();
|
|
1947
2154
|
if (!status) {
|
|
@@ -1959,19 +2166,22 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1959
2166
|
}
|
|
1960
2167
|
json(res, 404, { ok: false, error: 'not found' });
|
|
1961
2168
|
} catch (err) {
|
|
1962
|
-
|
|
2169
|
+
// 完整错误只进日志;响应里的消息抹掉主目录前缀,别把本机路径结构带出去
|
|
2170
|
+
console.error('[zcodepro] 路由处理出错:', err);
|
|
2171
|
+
json(res, 500, { ok: false, error: String(err?.message || err).split(homedir()).join('~') });
|
|
1963
2172
|
}
|
|
1964
2173
|
});
|
|
1965
2174
|
|
|
1966
2175
|
// 端口被占时重试:开发重载的交接窗口内,旧进程退出略晚于新进程启动,
|
|
1967
|
-
//
|
|
2176
|
+
// 新进程在这里等它让出端口(默认最多 20 秒),而不是启动失败;
|
|
2177
|
+
// 热替换路径传小的 listenTries,别把启动器主循环卡在这里
|
|
1968
2178
|
return new Promise((resolveStarted, rejectStarted) => {
|
|
1969
2179
|
let attempts = 0;
|
|
1970
2180
|
const tryListen = () => {
|
|
1971
2181
|
attempts += 1;
|
|
1972
2182
|
server.removeAllListeners('error');
|
|
1973
2183
|
server.once('error', (err) => {
|
|
1974
|
-
if (err && err.code === 'EADDRINUSE' && attempts <
|
|
2184
|
+
if (err && err.code === 'EADDRINUSE' && attempts < listenTries) {
|
|
1975
2185
|
try { server.close(); } catch { /* ignore */ }
|
|
1976
2186
|
setTimeout(tryListen, 500);
|
|
1977
2187
|
return;
|
|
@@ -1981,17 +2191,17 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1981
2191
|
// 启动即补视觉配置缺省键:装了 zcode-pro ⇒ cardUi=true(识图卡片开,缺省
|
|
1982
2192
|
// 才补、显式设过不动,规则同 GET /vision),不必等用户打开视觉设置页
|
|
1983
2193
|
try {
|
|
1984
|
-
const vFile =
|
|
2194
|
+
const vFile = visionFile;
|
|
1985
2195
|
const vParsed = readJsonFile(vFile);
|
|
1986
2196
|
if (vParsed && typeof vParsed === 'object' && !('cardUi' in vParsed)) {
|
|
1987
2197
|
vParsed.cardUi = true;
|
|
1988
|
-
const vTmp = vFile
|
|
1989
|
-
writeFileSync(vTmp, JSON.stringify(vParsed, null, 2) + '\n', 'utf-8');
|
|
2198
|
+
const vTmp = `${vFile}.${process.pid}.${Date.now().toString(36)}.tmp`; // 防多写者共用同一 .tmp 撕裂
|
|
2199
|
+
writeFileSync(vTmp, JSON.stringify(vParsed, null, 2) + '\n', { encoding: 'utf-8', mode: 0o600 }); // 文件里有明文 apiKey,限制本人读写
|
|
1990
2200
|
renameSync(vTmp, vFile);
|
|
1991
2201
|
}
|
|
1992
2202
|
} catch { /* 无配置或不可写不影响启动 */ }
|
|
1993
2203
|
// 服务就绪即安排 headroom 代理兜底(内部延迟 5 秒执行,避开启动高峰)
|
|
1994
|
-
server.listen(port, '127.0.0.1', () => { ensureHeadroomAtStartup(); resolveStarted(server); });
|
|
2204
|
+
server.listen(port, '127.0.0.1', () => { ensureHeadroomAtStartup(state); resolveStarted(server); });
|
|
1995
2205
|
};
|
|
1996
2206
|
tryListen();
|
|
1997
2207
|
});
|
|
@@ -2006,7 +2216,28 @@ let tasksCountCache = 0; // 任务总数缓存(/stats/usage 高频轮询,60
|
|
|
2006
2216
|
// ~/.zcode/cli/rollout/model-io-*.jsonl 每行一次模型调用;usage 字段有两种键风格
|
|
2007
2217
|
// (协议 camelCase 与原始 snake_case),两种都解析。文件小(个位数、每会话一个),
|
|
2008
2218
|
// 按 mtime+size 缓存只重读变过的文件;聚合结果含按日分桶(本地时区)供“今日”用
|
|
2009
|
-
const usageFileCache = new Map(); // 文件名 → { mtime, size, recs: [{at, in, out,
|
|
2219
|
+
const usageFileCache = new Map(); // 文件名 → { mtime, size, recs: [{at, ts, ms, in, out, cacheRead, session}] }
|
|
2220
|
+
// 测试缝:覆盖 rollout 记录目录(scripts/test-usage-stats.mjs 用假数据跑真实聚合)
|
|
2221
|
+
let rolloutDirOverride = '';
|
|
2222
|
+
// 记录合并结果缓存:文件签名(名称+mtime+size)没变就直接复用上次合并好的记录
|
|
2223
|
+
let rolloutSig = '';
|
|
2224
|
+
let rolloutRecsCache = null;
|
|
2225
|
+
// 聚合结果缓存:同文件签名 + 同查询参数(含本地日期)直接复用,
|
|
2226
|
+
// /stats/usage 2 秒轮询不用每次全量重聚合十万级记录
|
|
2227
|
+
let statsResultCache = { sig: '', key: '', result: null };
|
|
2228
|
+
// 供启动器热替换前调用:旧模块实例被 ESM 模块表永久持有,清掉大块缓存省内存
|
|
2229
|
+
export function dispose() {
|
|
2230
|
+
usageFileCache.clear();
|
|
2231
|
+
rolloutRecsCache = null; // 合并后的全量记录数组(可达十万级),不留
|
|
2232
|
+
rolloutSig = '';
|
|
2233
|
+
statsResultCache = { sig: '', key: '', result: null };
|
|
2234
|
+
// 残留的 ffmpeg 转码子进程一并收掉(退出/交接时调用):孤儿进程会与新实例
|
|
2235
|
+
// 并发写同一个 .tmp.mp4 写坏缓存且不再重建;杀掉只会丢半截临时文件,重启后重建
|
|
2236
|
+
for (const child of transcodeChildren) {
|
|
2237
|
+
try { child.kill(); } catch { /* 已退出 */ }
|
|
2238
|
+
}
|
|
2239
|
+
transcodeChildren.clear();
|
|
2240
|
+
}
|
|
2010
2241
|
// 解析一段 rollout 文本为记录;completeBytes = 已完整解析的整行字节数
|
|
2011
2242
|
//(末行若是不完整 JSON(写入中途)不计入,调用方据此决定偏移推进量)
|
|
2012
2243
|
function parseRolloutLines(text) {
|
|
@@ -2050,8 +2281,11 @@ function parseRolloutLines(text) {
|
|
|
2050
2281
|
input = num(u.input_tokens) + cacheRead + cacheWrite;
|
|
2051
2282
|
}
|
|
2052
2283
|
const output = num(u.outputTokens ?? u.output_tokens);
|
|
2284
|
+
const at = d.completedAt || d.startedAt || '';
|
|
2053
2285
|
recs.push({
|
|
2054
|
-
at
|
|
2286
|
+
at,
|
|
2287
|
+
ts: Date.parse(at),
|
|
2288
|
+
ms: Number(d.durationMs) || 0,
|
|
2055
2289
|
in: input, out: output,
|
|
2056
2290
|
cacheRead,
|
|
2057
2291
|
session: String(d.sessionId || ''),
|
|
@@ -2064,21 +2298,34 @@ function parseRolloutLines(text) {
|
|
|
2064
2298
|
}
|
|
2065
2299
|
|
|
2066
2300
|
function rolloutRecords() {
|
|
2067
|
-
const dir = join(
|
|
2301
|
+
const dir = rolloutDirOverride || join(resolveDataRootDir(), 'cli', 'rollout'); // 官方 rollout 目录跟数据根迁移
|
|
2068
2302
|
let names = [];
|
|
2069
|
-
try { names = readdirSync(dir).filter((n) => n.startsWith('model-io-') && n.endsWith('.jsonl')); } catch {
|
|
2303
|
+
try { names = readdirSync(dir).filter((n) => n.startsWith('model-io-') && n.endsWith('.jsonl')); } catch {
|
|
2304
|
+
// 读目录失败(杀软/权限抖动)时旧签名作废:否则空记录算出的 0 值结果会
|
|
2305
|
+
// 连着旧签名进缓存,目录恢复后文件没变就一直命中 0
|
|
2306
|
+
rolloutSig = '';
|
|
2307
|
+
rolloutRecsCache = null;
|
|
2308
|
+
return [];
|
|
2309
|
+
}
|
|
2070
2310
|
// 缓存条目随文件淘汰:会话记录滚动删除后残留条目不再增长(虽小但是纯泄漏)
|
|
2311
|
+
const nameSet = new Set(names); // Set 判定:文件数上千时 names.includes 是 O(F²)
|
|
2071
2312
|
for (const k of usageFileCache.keys()) {
|
|
2072
|
-
if (!
|
|
2313
|
+
if (!nameSet.has(k)) usageFileCache.delete(k);
|
|
2073
2314
|
}
|
|
2074
2315
|
const recs = [];
|
|
2316
|
+
// 先取各文件 stat 并算签名:签名没变直接复用上次合并好的记录。shortcut:
|
|
2317
|
+
// 同一毫秒内改写成相同字节数检测不到,实际不会发生,如遇到可把签名换成内容哈希
|
|
2318
|
+
const stats = [];
|
|
2075
2319
|
for (const name of names) {
|
|
2320
|
+
try { stats.push([name, statSync(join(dir, name))]); } catch { /* 读不到的文件跳过 */ }
|
|
2321
|
+
}
|
|
2322
|
+
const sig = stats.map(([name, st]) => `${name}:${st.mtimeMs}:${st.size}`).join('|');
|
|
2323
|
+
if (sig === rolloutSig && rolloutRecsCache) return rolloutRecsCache;
|
|
2324
|
+
for (const [name, st] of stats) {
|
|
2076
2325
|
const full = join(dir, name);
|
|
2077
|
-
let st;
|
|
2078
|
-
try { st = statSync(full); } catch { continue; }
|
|
2079
2326
|
const cached = usageFileCache.get(name);
|
|
2080
2327
|
if (cached && cached.mtime === st.mtimeMs && cached.size === st.size) {
|
|
2081
|
-
|
|
2328
|
+
for (const r of cached.recs) recs.push(r); // 不用展开语法:单文件 13 万条会 RangeError
|
|
2082
2329
|
continue;
|
|
2083
2330
|
}
|
|
2084
2331
|
// 追加式增量解析:jsonl 只追加(流式输出期间当前会话文件持续增长,整文件
|
|
@@ -2098,7 +2345,8 @@ function rolloutRecords() {
|
|
|
2098
2345
|
size: cached.size + completeBytes,
|
|
2099
2346
|
recs: cached.recs.concat(added),
|
|
2100
2347
|
});
|
|
2101
|
-
|
|
2348
|
+
for (const r of cached.recs) recs.push(r);
|
|
2349
|
+
for (const r of added) recs.push(r);
|
|
2102
2350
|
continue;
|
|
2103
2351
|
}
|
|
2104
2352
|
let parsed = [];
|
|
@@ -2112,39 +2360,78 @@ function rolloutRecords() {
|
|
|
2112
2360
|
parsedBytes = Math.min(r.completeBytes, Buffer.byteLength(text, 'utf8'));
|
|
2113
2361
|
} catch { /* 文件读失败跳过 */ }
|
|
2114
2362
|
usageFileCache.set(name, { mtime: st.mtimeMs, size: parsedBytes, recs: parsed });
|
|
2115
|
-
recs.push(
|
|
2363
|
+
for (const r of parsed) recs.push(r);
|
|
2116
2364
|
}
|
|
2365
|
+
rolloutSig = sig;
|
|
2366
|
+
rolloutRecsCache = recs;
|
|
2117
2367
|
return recs;
|
|
2118
2368
|
}
|
|
2119
2369
|
|
|
2120
|
-
function collectUsageStats(sessionId) {
|
|
2370
|
+
function collectUsageStats(sessionId, wantTurns = true) {
|
|
2121
2371
|
const recs = rolloutRecords();
|
|
2122
|
-
//
|
|
2123
|
-
//
|
|
2124
|
-
|
|
2372
|
+
// 分钟桶只服务每轮统计(turn-usage 带 session 拉取),状态栏请求带 turns=0
|
|
2373
|
+
// 跳过:省掉全记录分桶与 60 桶序列化(大记录集下每请求几十毫秒)
|
|
2374
|
+
wantTurns = wantTurns && !!sessionId;
|
|
2125
2375
|
const today = new Date();
|
|
2126
2376
|
const todayKey = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
|
|
2377
|
+
// 记录没变(文件签名相同)+ 查询口径没变时直接复用上次聚合结果:锚定速率是
|
|
2378
|
+
// 记录的纯函数(锚 = 最新完成时刻,不随请求时刻移动),跨午夜才要重算"今日"
|
|
2379
|
+
const cacheKey = `${sessionId || ''}|${wantTurns ? 1 : 0}|${todayKey}`;
|
|
2380
|
+
if (statsResultCache.sig === rolloutSig && statsResultCache.key === cacheKey && statsResultCache.result) {
|
|
2381
|
+
return statsResultCache.result;
|
|
2382
|
+
}
|
|
2127
2383
|
const global = { todayTokens: 0, todayOut: 0, totalTokens: 0, totalOut: 0, tasks: 0, records: recs.length };
|
|
2128
2384
|
// 每轮用量按本地 HH:mm 分桶(回答末尾的显示时间与之匹配);
|
|
2129
2385
|
// 本地记录只留最近几轮,注入侧只给能对上时间的回答显示
|
|
2130
2386
|
const byMinute = new Map();
|
|
2387
|
+
// 最近 60 秒速率(状态栏 tokRate 项):token 按调用耗时摊到时间轴(完成
|
|
2388
|
+
// 时刻往前 durationMs 一段),按窗口重叠比例折算,长调用完成瞬间不会出现
|
|
2389
|
+
// 假尖峰。窗口以该口径最新一条记录的完成时刻为锚、往前 60 秒——回答结束
|
|
2390
|
+
// 后锚不再移动,速率自然停在最后的值:不衰减归零,也不依赖进程内状态
|
|
2391
|
+
//(重启/热替换后显示一致);有新调用完成锚前移、数值刷新。
|
|
2392
|
+
// 统计范围:带 ?session= 只算该会话,不带则全局;与每轮桶不同,辅助小调用
|
|
2393
|
+
// 也计入(它们是真实消耗)
|
|
2394
|
+
const winMs = 60_000;
|
|
2395
|
+
let anchor = 0;
|
|
2396
|
+
for (const r of recs) {
|
|
2397
|
+
if (Number.isFinite(r.ts) && (!sessionId || r.session === sessionId)) anchor = Math.max(anchor, r.ts);
|
|
2398
|
+
}
|
|
2399
|
+
const anchorFuture = anchor > Date.now(); // 未来时间戳:钳制值依赖请求时刻,结果不能缓存
|
|
2400
|
+
anchor = Math.min(anchor, Date.now()); // 未来时间戳(时钟回拨等)别把锚拉到未来
|
|
2401
|
+
let rateTotal = 0;
|
|
2402
|
+
let rateOut = 0;
|
|
2131
2403
|
for (const r of recs) {
|
|
2132
2404
|
const total = r.in + r.out;
|
|
2133
2405
|
global.totalTokens += total;
|
|
2134
2406
|
global.totalOut += r.out;
|
|
2135
|
-
|
|
2136
|
-
|
|
2407
|
+
// 按本地日期归"今日":r.at 是 ISO/UTC 串,直接取前 10 位是 UTC 日期,
|
|
2408
|
+
// 本地凌晨(UTC+8 的 0-8 点)完成的调用会被算进昨天
|
|
2409
|
+
if (Number.isFinite(r.ts)) {
|
|
2410
|
+
const rd = new Date(r.ts);
|
|
2411
|
+
const day = `${rd.getFullYear()}-${String(rd.getMonth() + 1).padStart(2, '0')}-${String(rd.getDate()).padStart(2, '0')}`;
|
|
2412
|
+
if (day === todayKey) { global.todayTokens += total; global.todayOut += r.out; }
|
|
2413
|
+
}
|
|
2414
|
+
const end = r.ts;
|
|
2415
|
+
if (Number.isFinite(end) && (!sessionId || r.session === sessionId)) {
|
|
2416
|
+
const dur = Math.max(r.ms || 0, 1); // 无耗时字段的旧记录按 1ms 点事件计
|
|
2417
|
+
const overlap = Math.min(end, anchor) - Math.max(end - dur, anchor - winMs);
|
|
2418
|
+
if (overlap > 0) {
|
|
2419
|
+
const w = overlap / dur;
|
|
2420
|
+
rateTotal += total * w;
|
|
2421
|
+
rateOut += r.out * w;
|
|
2422
|
+
}
|
|
2423
|
+
}
|
|
2137
2424
|
// 每轮回答只统计主对话流的调用:起名等辅助请求是独立小上下文、
|
|
2138
2425
|
// 缓存从零开始,混进分钟桶会把命中率拉到个位数(全局统计仍全量计入)
|
|
2139
2426
|
if (!wantTurns || total < 5000) continue;
|
|
2140
2427
|
// 指定会话时每轮桶只算该会话的调用——否则切到别的会话聊天后,
|
|
2141
2428
|
// 那些调用会被区间归属算进当前会话最后一行的头上
|
|
2142
2429
|
if (r.session !== sessionId) continue;
|
|
2143
|
-
const t =
|
|
2430
|
+
const t = r.ts;
|
|
2144
2431
|
if (!Number.isFinite(t)) continue;
|
|
2145
2432
|
const d = new Date(t);
|
|
2146
|
-
//
|
|
2147
|
-
//
|
|
2433
|
+
// 桶键 = 本地"月-日 时:分";注入侧不读这个键(按 ts 区间归属到回答行),
|
|
2434
|
+
// 键只用于同分钟的调用并桶
|
|
2148
2435
|
const hm = (d.getMonth() + 1) + '-' + d.getDate() + ' ' + String(d.getHours()).padStart(2, '0') + ':' + String(d.getMinutes()).padStart(2, '0');
|
|
2149
2436
|
const bucket = byMinute.get(hm) || { hm, in: 0, out: 0, cacheRead: 0, ts: t };
|
|
2150
2437
|
bucket.in += r.in;
|
|
@@ -2153,8 +2440,13 @@ function collectUsageStats(sessionId) {
|
|
|
2153
2440
|
bucket.ts = Math.max(bucket.ts, t);
|
|
2154
2441
|
byMinute.set(hm, bucket);
|
|
2155
2442
|
}
|
|
2443
|
+
// 保留 1 位小数:工具循环期的输出只有零点几每秒,取整会显示成 0/s
|
|
2444
|
+
const perSec = (x) => Math.round((x / (winMs / 1000)) * 10) / 10;
|
|
2445
|
+
global.rate60 = { total: perSec(rateTotal), out: perSec(rateOut) };
|
|
2156
2446
|
const recentTurns = [...byMinute.values()].sort((a, b) => b.ts - a.ts).slice(0, 60);
|
|
2157
|
-
|
|
2447
|
+
const out = { global, recentTurns };
|
|
2448
|
+
if (!anchorFuture) statsResultCache = { sig: rolloutSig, key: cacheKey, result: out };
|
|
2449
|
+
return out;
|
|
2158
2450
|
}
|
|
2159
2451
|
|
|
2160
2452
|
function readJsonFile(p) {
|
|
@@ -2202,6 +2494,9 @@ function mergeTitleGenConfig(saved) {
|
|
|
2202
2494
|
baseUrl: typeof s.baseUrl === 'string' ? s.baseUrl.trim().slice(0, 500) : d.baseUrl,
|
|
2203
2495
|
apiKey: typeof s.apiKey === 'string' ? s.apiKey.trim().slice(0, 500) : d.apiKey,
|
|
2204
2496
|
format: s.format === 'openai' ? 'openai' : s.format === 'anthropic' ? 'anthropic' : '',
|
|
2497
|
+
recentQa: Number.isFinite(Number(s.recentQa)) ? Math.min(20, Math.max(1, Math.round(Number(s.recentQa)))) : d.recentQa,
|
|
2498
|
+
hoverBtn: s.hoverBtn !== false,
|
|
2499
|
+
menuEntry: s.menuEntry !== false,
|
|
2205
2500
|
customWritten: written,
|
|
2206
2501
|
};
|
|
2207
2502
|
}
|
|
@@ -2238,6 +2533,30 @@ function mergeSyncConfig(saved) {
|
|
|
2238
2533
|
};
|
|
2239
2534
|
}
|
|
2240
2535
|
|
|
2536
|
+
// WebDAV 地址的协议判定:http 明文会把 Basic 登录名和密码原样传出去,
|
|
2537
|
+
// http 只放行回环与内网地址(内网 NAS 常用 http),公网主机必须 https
|
|
2538
|
+
function webdavHttpSchemeOk(raw) {
|
|
2539
|
+
const url = typeof raw === 'string' ? raw.trim() : '';
|
|
2540
|
+
if (!/^https?:\/\//i.test(url)) return false;
|
|
2541
|
+
if (/^https:/i.test(url)) return true;
|
|
2542
|
+
let host = '';
|
|
2543
|
+
try { host = new URL(url).hostname.toLowerCase(); } catch { return false; }
|
|
2544
|
+
host = host.replace(/^\[|\]$/g, ''); // URL.hostname 对 IPv6 地址带方括号
|
|
2545
|
+
if (host === 'localhost' || host === '::1') return true;
|
|
2546
|
+
// IPv6 字面量不走下面的域名规则(不含点,会被误判成内网主机名):
|
|
2547
|
+
// 只放行链路本地(fe80::/10)与 ULA(fc00::/7)内网段,公网 v6 仍要 https
|
|
2548
|
+
// (按 RFC 5952 规范写法匹配首段,缩写首段的极端写法不认)
|
|
2549
|
+
if (host.includes(':')) return /^(fe[89ab][0-9a-f]|f[cd][0-9a-f]{2}):/i.test(host);
|
|
2550
|
+
// 单标签主机名(无点,如 mynas)与 .local/.lan/.internal 后缀的域名按内网 NAS
|
|
2551
|
+
// 处理放行 http;其余域名型主机要求 https
|
|
2552
|
+
if (!host.includes('.') || /\.(local|lan|internal)$/.test(host)) return true;
|
|
2553
|
+
const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host);
|
|
2554
|
+
if (!m) return false;
|
|
2555
|
+
const a = Number(m[1]);
|
|
2556
|
+
const b = Number(m[2]);
|
|
2557
|
+
return a === 127 || a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168);
|
|
2558
|
+
}
|
|
2559
|
+
|
|
2241
2560
|
// POST /sync 表单校验:url/login/password/dir 全量替换(dir 缺省时不动已有值)。
|
|
2242
2561
|
// URL 必填,指向 WebDAV 服务器(可含路径前缀);dir 为其下的上传目录,可多级;
|
|
2243
2562
|
// historyLimit 可选(缺省时不动已有值),0–100 的整数
|
|
@@ -2248,6 +2567,7 @@ function validateSyncForm(raw) {
|
|
|
2248
2567
|
if (!url) return { error: '请先填写 URL(如 https://dav.jianguoyun.com/dav/)' };
|
|
2249
2568
|
if (!/^https?:\/\/\S+$/.test(url)) return { error: 'URL 需为 WebDAV 服务器地址,如 https://dav.example.com/dav/' };
|
|
2250
2569
|
if (url.length > 500) return { error: 'URL 过长(最多 500 字符)' };
|
|
2570
|
+
if (!webdavHttpSchemeOk(url)) return { error: '公网地址需用 https(http 明文传输登录名和密码);内网或回环地址(如 http://192.168.1.5:5005)可继续用 http' };
|
|
2251
2571
|
if (login.length > 300 || password.length > 300) return { error: '登录名或密码过长(最多 300 字符)' };
|
|
2252
2572
|
const out = { type: 'webdav', url, login, password };
|
|
2253
2573
|
if (typeof raw.dir === 'string') {
|
|
@@ -2367,7 +2687,8 @@ async function syncBgPull({ sync, proxyUrl, dataRoot }) {
|
|
|
2367
2687
|
if (!name) continue; // 云端的异常文件名条目不镜像
|
|
2368
2688
|
const l = localByName.get(name);
|
|
2369
2689
|
if (l && l.size === f.size) continue;
|
|
2370
|
-
|
|
2690
|
+
// 临时名带 pid+随机:与上传路径撞同一文件名时不共用一个 .tmp
|
|
2691
|
+
const tmp = join(dir, `${name}.${process.pid}.${Date.now().toString(36)}.tmp`);
|
|
2371
2692
|
const get = await webdavRequest({ method: 'GET', url: syncBgFileUrl(sync, name), login: sync.login, password: sync.password, proxyUrl, timeoutMs: 120000, downloadFile: tmp });
|
|
2372
2693
|
const bad = !get.ok || get.httpCode < 200 || get.httpCode >= 300;
|
|
2373
2694
|
if (bad) {
|
|
@@ -2387,8 +2708,8 @@ async function syncBgPull({ sync, proxyUrl, dataRoot }) {
|
|
|
2387
2708
|
}
|
|
2388
2709
|
|
|
2389
2710
|
// 信封校验:云端文件必须是 { app: 'zcode-pro', kind, format, data } 且组别与文件名
|
|
2390
|
-
// 前缀一致;4MB
|
|
2391
|
-
function parseSyncEnvelope(body, kind, label) {
|
|
2711
|
+
// 前缀一致;4MB 上限挡住异常大文件。导出供回归测试直接喂坏信封
|
|
2712
|
+
export function parseSyncEnvelope(body, kind, label) {
|
|
2392
2713
|
if (body.length > 4 * 1024 * 1024) {
|
|
2393
2714
|
return { error: `云端 ${label} 超过 4MB,已拒绝应用`, code: 'sync-remote-invalid', status: 400 };
|
|
2394
2715
|
}
|
|
@@ -2397,6 +2718,10 @@ function parseSyncEnvelope(body, kind, label) {
|
|
|
2397
2718
|
if (!doc || typeof doc !== 'object' || doc.app !== 'zcode-pro' || doc.kind !== kind || !doc.data || typeof doc.data !== 'object') {
|
|
2398
2719
|
return { error: `云端 ${label} 不是 zcode-pro 的同步数据(可能被其他内容占用),请删除该文件或换一个目录`, code: 'sync-remote-invalid', status: 409 };
|
|
2399
2720
|
}
|
|
2721
|
+
// format 超出认识范围(更新版本的 zcode-pro 写入的新格式):不导入,提示升级客户端
|
|
2722
|
+
if (doc.format !== 1) {
|
|
2723
|
+
return { error: `云端 ${label} 是更新版本的 zcode-pro 写入的数据,当前客户端版本过旧,请升级 zcode-pro 后再同步`, code: 'sync-remote-invalid', status: 400 };
|
|
2724
|
+
}
|
|
2400
2725
|
return { doc };
|
|
2401
2726
|
}
|
|
2402
2727
|
|
|
@@ -2425,11 +2750,38 @@ async function fetchSyncNamedDoc(sync, proxyUrl, fileName) {
|
|
|
2425
2750
|
return parseSyncEnvelope(r.body, kind, fileName);
|
|
2426
2751
|
}
|
|
2427
2752
|
|
|
2753
|
+
// —— /sync/run 单飞 ————————————————————————————————————
|
|
2754
|
+
// 同 direction 的并发触发共用同一个 promise(去重),不同 direction 串行排队:
|
|
2755
|
+
// 两轮同步并发跑会互相清掉对方刚上传的历史版本。在途(排队 + 执行)期间计入
|
|
2756
|
+
// 忙碌标志,启动器热替换据此延后——同步中途换进程同样会互删历史版本
|
|
2757
|
+
let syncRunJobs = new Map(); // direction → 在跑或排队的 promise
|
|
2758
|
+
let syncRunQueue = Promise.resolve();
|
|
2759
|
+
|
|
2760
|
+
function enqueueSyncRun(direction, fn) {
|
|
2761
|
+
const inflight = syncRunJobs.get(direction);
|
|
2762
|
+
if (inflight) return inflight;
|
|
2763
|
+
const prev = syncRunQueue;
|
|
2764
|
+
const promise = (async () => {
|
|
2765
|
+
await prev;
|
|
2766
|
+
try {
|
|
2767
|
+
return await fn();
|
|
2768
|
+
} finally {
|
|
2769
|
+
syncRunJobs.delete(direction);
|
|
2770
|
+
}
|
|
2771
|
+
})();
|
|
2772
|
+
syncRunQueue = promise.then(() => undefined, () => undefined);
|
|
2773
|
+
syncRunJobs.set(direction, promise);
|
|
2774
|
+
return trackBusy(promise);
|
|
2775
|
+
}
|
|
2776
|
+
|
|
2428
2777
|
async function runSettingsSync({ direction, dataRoot, configFile, config, proxyUrl }) {
|
|
2429
2778
|
const sync = config.sync;
|
|
2430
2779
|
if (!sync.url || !/^https?:\/\/\S+$/.test(sync.url)) {
|
|
2431
2780
|
return { code: 'sync-not-configured', status: 400, error: '请先填写 WebDAV URL 并保存' };
|
|
2432
2781
|
}
|
|
2782
|
+
if (!webdavHttpSchemeOk(sync.url)) {
|
|
2783
|
+
return { code: 'sync-not-configured', status: 400, error: '公网 WebDAV 地址需改用 https(http 明文传输登录名和密码);内网或回环地址可继续用 http' };
|
|
2784
|
+
}
|
|
2433
2785
|
if (!sync.include.zcodepro && !sync.include.model) {
|
|
2434
2786
|
return { code: 'sync-not-configured', status: 400, error: '请至少选择一项同步内容' };
|
|
2435
2787
|
}
|
|
@@ -2438,10 +2790,17 @@ async function runSettingsSync({ direction, dataRoot, configFile, config, proxyU
|
|
|
2438
2790
|
: runSyncPull({ dataRoot, configFile, config, sync, proxyUrl });
|
|
2439
2791
|
}
|
|
2440
2792
|
|
|
2441
|
-
// headroom.json 里值得同步/应用的判定:providers
|
|
2442
|
-
//
|
|
2793
|
+
// headroom.json 里值得同步/应用的判定:providers 每条注册都得带路由必需的
|
|
2794
|
+
// id/upstream/format/keyHash 才算有效——空对象、空注册或残缺条目(如只写个 id
|
|
2795
|
+
// 的测试夹具)不上传也不覆盖,免得把别台机器拉回无映射状态(请求 502)
|
|
2443
2796
|
function validHeadroomDoc(hr) {
|
|
2444
|
-
return !!hr && typeof hr === 'object' && !Array.isArray(hr)
|
|
2797
|
+
return !!hr && typeof hr === 'object' && !Array.isArray(hr)
|
|
2798
|
+
&& Array.isArray(hr.providers) && hr.providers.length > 0
|
|
2799
|
+
&& hr.providers.every((p) => !!p && typeof p === 'object'
|
|
2800
|
+
&& typeof p.id === 'string' && p.id !== ''
|
|
2801
|
+
&& typeof p.upstream === 'string' && p.upstream !== ''
|
|
2802
|
+
&& (p.format === 'anthropic' || p.format === 'openai')
|
|
2803
|
+
&& typeof p.keyHash === 'string' && p.keyHash !== '');
|
|
2445
2804
|
}
|
|
2446
2805
|
|
|
2447
2806
|
// 上传:每组独立一个云端文件(zcodepro.json / model.json,始终最新一版),勾选几组
|
|
@@ -2456,6 +2815,11 @@ async function runSyncPush({ dataRoot, configFile, config, sync, proxyUrl }) {
|
|
|
2456
2815
|
if (sync.include.zcodepro) {
|
|
2457
2816
|
// sync(本机的同步配置与凭据)、version(本机 helper 版本)与 aliases 不外发
|
|
2458
2817
|
const { sync: _s, version: _v, aliases: _a, ...rest } = config;
|
|
2818
|
+
// titleGen.apiKey 是模型凭据,与 sync 一样只留本机(设置页文案:凭据不参与同步)
|
|
2819
|
+
if (rest.titleGen && typeof rest.titleGen === 'object') {
|
|
2820
|
+
const { apiKey: _k, ...tg } = rest.titleGen;
|
|
2821
|
+
rest.titleGen = tg;
|
|
2822
|
+
}
|
|
2459
2823
|
docs.zcodepro = rest;
|
|
2460
2824
|
}
|
|
2461
2825
|
if (sync.include.model) {
|
|
@@ -2520,10 +2884,12 @@ async function runSyncPush({ dataRoot, configFile, config, sync, proxyUrl }) {
|
|
|
2520
2884
|
}
|
|
2521
2885
|
sync.lastPushAt = Date.now();
|
|
2522
2886
|
// 同步是分钟级网络流程:写回前重读配置、只合并本次时间戳,
|
|
2523
|
-
//
|
|
2524
|
-
|
|
2525
|
-
|
|
2526
|
-
|
|
2887
|
+
// 别把期间用户在设置弹窗的修改用这份旧快照盖掉;读改写放进跨进程锁内同步执行
|
|
2888
|
+
await withConfigLock(configFile, () => {
|
|
2889
|
+
const freshPush = loadConfig(configFile);
|
|
2890
|
+
freshPush.sync = { ...freshPush.sync, lastPushAt: sync.lastPushAt };
|
|
2891
|
+
if (!saveConfig(configFile, freshPush)) console.error('[zcodepro] lastPushAt 写回被拒(zcodepro.json 损坏),上传本身已成功');
|
|
2892
|
+
});
|
|
2527
2893
|
// 上传成功后清理超出保留个数的旧历史版本(best-effort,失败不影响上传结果)
|
|
2528
2894
|
const pruned = await pruneSyncHistory(sync, proxyUrl, keep);
|
|
2529
2895
|
// 背景图库镜像上传(勾了 zcodepro 组才传;设置文档已传走,图库失败单独报错,重试幂等)
|
|
@@ -2575,25 +2941,33 @@ export function applySyncDocs({ docs, dataRoot, configFile, config, sync }) {
|
|
|
2575
2941
|
try { if (existsSync(p)) copyFileSync(p, p + '.zcodepro-backup'); } catch { /* 备份失败不阻塞 */ }
|
|
2576
2942
|
};
|
|
2577
2943
|
const atomicWrite = (p, obj) => {
|
|
2578
|
-
const tmp = p
|
|
2579
|
-
writeFileSync(tmp, JSON.stringify(obj, null, 2) + '\n', 'utf8');
|
|
2944
|
+
const tmp = `${p}.${process.pid}.${Date.now().toString(36)}.tmp`; // 防多写者共用同一 .tmp 撕裂
|
|
2945
|
+
writeFileSync(tmp, JSON.stringify(obj, null, 2) + '\n', { encoding: 'utf8', mode: 0o600 });
|
|
2580
2946
|
renameSync(tmp, p);
|
|
2581
2947
|
};
|
|
2582
2948
|
|
|
2583
2949
|
if (docs.zcodepro) {
|
|
2584
2950
|
const rz = docs.zcodepro;
|
|
2585
|
-
|
|
2586
|
-
|
|
2587
|
-
|
|
2588
|
-
|
|
2589
|
-
|
|
2590
|
-
|
|
2591
|
-
|
|
2592
|
-
|
|
2593
|
-
|
|
2594
|
-
|
|
2595
|
-
|
|
2596
|
-
|
|
2951
|
+
// 整段 zcodepro.json 读改写放进跨进程锁内同步执行(applySyncDocs 是同步
|
|
2952
|
+
// 调用点,用同步等锁变体),防止与别的写入方互相覆盖整份配置
|
|
2953
|
+
const rzErr = withConfigLockSync(configFile, () => {
|
|
2954
|
+
const next = loadConfig(configFile);
|
|
2955
|
+
applyFeaturesPartial(next.features, rz.features);
|
|
2956
|
+
next.styles = applyStylesPartial(next.styles, rz.styles);
|
|
2957
|
+
// 别名保持本机的原样:云端备份里的别名可能出自其他机器(路径在本机无效),
|
|
2958
|
+
// 且 3.16.1 起别名功能已停用,不再导入
|
|
2959
|
+
if (typeof rz.proxy === 'string') {
|
|
2960
|
+
const v = rz.proxy.trim();
|
|
2961
|
+
if (v === '' || /^https?:\/\/\S+:\d+$/.test(v)) next.proxy = v;
|
|
2962
|
+
}
|
|
2963
|
+
next.sync = { ...next.sync, lastPullAt: sync.lastPullAt }; // 保留本机 sync 配置与凭据,只记本次拉取时间
|
|
2964
|
+
backupFile(configFile);
|
|
2965
|
+
if (!saveConfig(configFile, next)) {
|
|
2966
|
+
return { error: 'zcodepro.json 读取失败或已损坏,导入中止(请先修好配置文件)', code: 'config-unreadable', status: 500 };
|
|
2967
|
+
}
|
|
2968
|
+
return null;
|
|
2969
|
+
});
|
|
2970
|
+
if (rzErr) return rzErr;
|
|
2597
2971
|
applied.push('zcodepro');
|
|
2598
2972
|
}
|
|
2599
2973
|
if (docs.model) {
|
|
@@ -2611,19 +2985,28 @@ export function applySyncDocs({ docs, dataRoot, configFile, config, sync }) {
|
|
|
2611
2985
|
atomicWrite(pcFile, pc);
|
|
2612
2986
|
}
|
|
2613
2987
|
// headroom.json 只在云端文档带有效注册时才覆盖(旧版云端文档没有该字段、
|
|
2614
|
-
// 或 providers
|
|
2615
|
-
// 与 router
|
|
2988
|
+
// 或 providers 为空/残缺,都不动本机,免得清掉已有映射);instances(实例端口表)
|
|
2989
|
+
// 与 router(监听端口)是本机运行状态,云端的一律不用,保留本机的。
|
|
2990
|
+
// 路径跟随 dataRoot(与同组其他文件一致):defaultHeadroomFile() 按 HOME 定位,
|
|
2991
|
+
// 测试跑进真配置会把用户的路由表整个写坏
|
|
2616
2992
|
const hr = docs.model.headroom;
|
|
2617
2993
|
if (validHeadroomDoc(hr)) {
|
|
2618
|
-
const hrFile =
|
|
2619
|
-
|
|
2620
|
-
|
|
2621
|
-
const
|
|
2622
|
-
|
|
2623
|
-
|
|
2624
|
-
|
|
2625
|
-
|
|
2626
|
-
|
|
2994
|
+
const hrFile = join(dataRoot, 'headroom.json');
|
|
2995
|
+
// 云端文档里带的三个设置键也剥掉:kompressBackend/powerSaveCpu/powerWatchInterval
|
|
2996
|
+
// 是本机设置,云端的赢会把 B 机器的压缩设备决策改成 A 机器的
|
|
2997
|
+
const { instances: _remoteInst, router: _remoteRouter, kompressBackend: _rKb, powerSaveCpu: _rPs, powerWatchInterval: _rWi, ...hrRest } = hr;
|
|
2998
|
+
// 读改写整段持 headroom.json 文件锁(与面板 interval 写入、setHeadroomUsage 互斥),
|
|
2999
|
+
// 锁内重读最新基线合并:以本机现有键为底、云端注册覆盖 providers,
|
|
3000
|
+
// instances/router 与三个本机设置键保留本机值
|
|
3001
|
+
withConfigLockSync(hrFile, () => {
|
|
3002
|
+
const fresh = readJsonFile(hrFile);
|
|
3003
|
+
const base = (fresh && typeof fresh === 'object') ? fresh : {};
|
|
3004
|
+
const merged = { ...base, ...hrRest };
|
|
3005
|
+
if (base.instances) merged.instances = base.instances;
|
|
3006
|
+
if (base.router) merged.router = base.router;
|
|
3007
|
+
backupFile(hrFile);
|
|
3008
|
+
atomicWrite(hrFile, merged);
|
|
3009
|
+
});
|
|
2627
3010
|
// 让路由立刻吃到新映射、缺的实例补起来(路由器本身每请求重读配置,
|
|
2628
3011
|
// 只有新上游的实例需要这一步),失败不影响同步结果
|
|
2629
3012
|
runHeadroomHook(['ensure'], 20000).catch(() => { /* 尽力而为 */ });
|
|
@@ -2633,9 +3016,12 @@ export function applySyncDocs({ docs, dataRoot, configFile, config, sync }) {
|
|
|
2633
3016
|
// 没动 zcodepro.json 时,lastPullAt 也要写入配置文件(动了则已随 next 一起保存)。
|
|
2634
3017
|
// 写回前重读配置、只合并时间戳:别用旧快照盖掉同步期间用户的修改
|
|
2635
3018
|
if (!applied.includes('zcodepro')) {
|
|
2636
|
-
|
|
2637
|
-
|
|
2638
|
-
|
|
3019
|
+
// lastPullAt 读改写同样在跨进程锁内同步完成
|
|
3020
|
+
withConfigLockSync(configFile, () => {
|
|
3021
|
+
const freshPull = loadConfig(configFile);
|
|
3022
|
+
freshPull.sync = { ...freshPull.sync, lastPullAt: sync.lastPullAt };
|
|
3023
|
+
if (!saveConfig(configFile, freshPull)) console.error('[zcodepro] lastPullAt 写回被拒(zcodepro.json 损坏)');
|
|
3024
|
+
});
|
|
2639
3025
|
}
|
|
2640
3026
|
return { applied };
|
|
2641
3027
|
}
|
|
@@ -2661,7 +3047,9 @@ async function runSyncTest({ sync, proxyUrl }) {
|
|
|
2661
3047
|
});
|
|
2662
3048
|
return { ok, resp };
|
|
2663
3049
|
};
|
|
2664
|
-
|
|
3050
|
+
// PROPFIND 的集合地址统一带尾斜杠(图库列表 syncBgListRemote 同款):
|
|
3051
|
+
// 会给目录地址回 301 的网盘不认无斜杠写法,会报“HTTP 301”
|
|
3052
|
+
const baseDir = syncBaseDir(sync) + '/';
|
|
2665
3053
|
// ① 只要拿到响应且不是凭据问题就算连通(404/409 = 目录还没建,交给第②步处理)
|
|
2666
3054
|
const connect = await probe('connect', () => webdavRequest({ method: 'PROPFIND', url: baseDir, ...auth, timeoutMs: 20000, headers: ['Depth: 0'] }));
|
|
2667
3055
|
if (!connect.ok && connect.resp.ok && (connect.resp.httpCode === 404 || connect.resp.httpCode === 409)) {
|
|
@@ -2697,7 +3085,7 @@ async function runSyncTest({ sync, proxyUrl }) {
|
|
|
2697
3085
|
// PROPFIND 云端同步目录,列出全部备份版本(固定名 + 带时间戳的历史):
|
|
2698
3086
|
// 按修改时间从新到旧(时间缺失的按文件名排后);目录还不存在视为空列表
|
|
2699
3087
|
async function listSyncVersions(sync, proxyUrl) {
|
|
2700
|
-
const r = await webdavRequest({ method: 'PROPFIND', url: syncBaseDir(sync), login: sync.login, password: sync.password, proxyUrl, timeoutMs: 30000, headers: ['Depth: 1'] });
|
|
3088
|
+
const r = await webdavRequest({ method: 'PROPFIND', url: syncBaseDir(sync) + '/', login: sync.login, password: sync.password, proxyUrl, timeoutMs: 30000, headers: ['Depth: 1'] });
|
|
2701
3089
|
if (!r.ok) return { error: r.error, code: 'sync-request', status: 502 };
|
|
2702
3090
|
if (r.httpCode === 404 || r.httpCode === 409) return { files: [] };
|
|
2703
3091
|
if (r.httpCode < 200 || r.httpCode >= 300) return { error: webdavHttpText(r.httpCode), code: 'sync-request', status: 502 };
|
|
@@ -2741,40 +3129,6 @@ async function pruneSyncHistory(sync, proxyUrl, keep) {
|
|
|
2741
3129
|
return removed;
|
|
2742
3130
|
}
|
|
2743
3131
|
|
|
2744
|
-
// 别名表清洗(同步下载用):只收 路径字符串 → 短字符串 的条目,数量限幅
|
|
2745
|
-
function sanitizeAliases(raw) {
|
|
2746
|
-
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
|
|
2747
|
-
const out = {};
|
|
2748
|
-
let n = 0;
|
|
2749
|
-
for (const [k, v] of Object.entries(raw)) {
|
|
2750
|
-
if (typeof k !== 'string' || k.length > 500 || k.includes('\0')) continue;
|
|
2751
|
-
if (typeof v !== 'string' || v.length > 200 || /[\r\n\0]/.test(v)) continue;
|
|
2752
|
-
out[k] = v;
|
|
2753
|
-
if (++n >= 2000) break;
|
|
2754
|
-
}
|
|
2755
|
-
return out;
|
|
2756
|
-
}
|
|
2757
|
-
|
|
2758
|
-
// 别名表合并(同步上传/下载共用):取两边的并集,配过别名的条目优先——同一路径
|
|
2759
|
-
// 两边都配了别名时用本机的;只有一边配过时保留配过的那个。所以在一台机器上清除
|
|
2760
|
-
// 别名后,只要别的机器还配着,下次同步还会把这条带回来,两边都清掉才会真正消失。
|
|
2761
|
-
// 导出以便测试脚本直接驱动。
|
|
2762
|
-
export function mergeAliases(localRaw, remoteRaw) {
|
|
2763
|
-
const out = {};
|
|
2764
|
-
const put = (k, v) => {
|
|
2765
|
-
if (typeof k !== 'string' || k.length > 500 || k.includes('\0')) return;
|
|
2766
|
-
if (typeof v !== 'string' || !v || v.length > 200 || /[\r\n\0]/.test(v)) return;
|
|
2767
|
-
out[k] = v;
|
|
2768
|
-
};
|
|
2769
|
-
const entries = (raw) => (raw && typeof raw === 'object' && !Array.isArray(raw)) ? Object.entries(raw) : [];
|
|
2770
|
-
for (const [k, v] of entries(remoteRaw)) put(k, v);
|
|
2771
|
-
for (const [k, v] of entries(localRaw)) {
|
|
2772
|
-
// 本机配过的覆盖云端同路径条目;本机是空值(视为没配过)时不覆盖,云端配过的留下
|
|
2773
|
-
if (v) put(k, v);
|
|
2774
|
-
}
|
|
2775
|
-
return out;
|
|
2776
|
-
}
|
|
2777
|
-
|
|
2778
3132
|
// features 部分更新(POST /config 与同步下载共用):只收已知开关的布尔值
|
|
2779
3133
|
function applyFeaturesPartial(base, partial) {
|
|
2780
3134
|
const out = (base && typeof base === 'object') ? base : {};
|
|
@@ -2782,9 +3136,9 @@ function applyFeaturesPartial(base, partial) {
|
|
|
2782
3136
|
const known = new Set(Object.keys(defaultConfig().features));
|
|
2783
3137
|
for (const key of Object.keys(partial)) {
|
|
2784
3138
|
// 布尔特性一律可存(新特性未列入 defaultConfig 时不能被丢弃),
|
|
2785
|
-
//
|
|
3139
|
+
// 非布尔值只在已知键内、且与默认值同类型时接受——防垃圾类型进配置
|
|
2786
3140
|
if (typeof partial[key] === 'boolean') out[key] = partial[key];
|
|
2787
|
-
else if (known.has(key)) out[key] = partial[key];
|
|
3141
|
+
else if (known.has(key) && typeof partial[key] === typeof defaultConfig().features[key]) out[key] = partial[key];
|
|
2788
3142
|
}
|
|
2789
3143
|
return out;
|
|
2790
3144
|
}
|
|
@@ -2862,30 +3216,36 @@ function scanIdleBusyLinux(paths) {
|
|
|
2862
3216
|
for (const pid of pids) {
|
|
2863
3217
|
try {
|
|
2864
3218
|
if (readFileSync(`/proc/${pid}/comm`, 'utf8').trim() !== 'zcode-cli') continue;
|
|
2865
|
-
|
|
3219
|
+
const cwd = readlinkSync(`/proc/${pid}/cwd`);
|
|
3220
|
+
// 同一工作区可以开多个会话进程:记列表别后写覆盖先写——漏扫一个会话的
|
|
3221
|
+
// 子进程会把跑着命令的项目判成空闲
|
|
3222
|
+
const arr = cliPidByCwd.get(cwd);
|
|
3223
|
+
if (arr) arr.push(pid); else cliPidByCwd.set(cwd, [pid]);
|
|
2866
3224
|
} catch { /* 进程退出/权限:跳过 */ }
|
|
2867
3225
|
}
|
|
2868
3226
|
const busy = new Set();
|
|
2869
|
-
for (const [cwd,
|
|
3227
|
+
for (const [cwd, cliPids] of cliPidByCwd) {
|
|
2870
3228
|
const wantedPaths = wantedByCwd.get(cwd);
|
|
2871
3229
|
if (!wantedPaths) continue;
|
|
2872
|
-
|
|
2873
|
-
|
|
2874
|
-
|
|
2875
|
-
|
|
2876
|
-
const
|
|
2877
|
-
|
|
2878
|
-
|
|
2879
|
-
|
|
2880
|
-
|
|
2881
|
-
|
|
2882
|
-
|
|
2883
|
-
|
|
2884
|
-
|
|
2885
|
-
|
|
2886
|
-
|
|
2887
|
-
|
|
2888
|
-
|
|
3230
|
+
for (const pid of cliPids) {
|
|
3231
|
+
let children = '';
|
|
3232
|
+
try { children = readFileSync(`/proc/${pid}/task/${pid}/children`, 'utf8'); }
|
|
3233
|
+
catch { continue; }
|
|
3234
|
+
for (const childPidStr of children.split(/\s+/)) {
|
|
3235
|
+
const childPid = Number(childPidStr);
|
|
3236
|
+
if (!Number.isFinite(childPid)) continue;
|
|
3237
|
+
let cmdline = '';
|
|
3238
|
+
let zombie = false;
|
|
3239
|
+
try {
|
|
3240
|
+
cmdline = normCmdline(readFileSync(`/proc/${childPid}/cmdline`, 'utf8').replace(/\0/g, ' ').trim());
|
|
3241
|
+
const stat = readFileSync(`/proc/${childPid}/stat`, 'utf8');
|
|
3242
|
+
zombie = /\) Z /.test(stat);
|
|
3243
|
+
} catch { continue; }
|
|
3244
|
+
if (zombie) continue;
|
|
3245
|
+
if (!cmdline || !isInfraCmdline(cmdline)) {
|
|
3246
|
+
for (const wp of wantedPaths) busy.add(wp); // 认不出的进程宁可误判为忙,也不回收可能在跑命令的项目
|
|
3247
|
+
break;
|
|
3248
|
+
}
|
|
2889
3249
|
}
|
|
2890
3250
|
}
|
|
2891
3251
|
}
|
|
@@ -2916,8 +3276,11 @@ async function scanIdleBusyDarwin(paths) {
|
|
|
2916
3276
|
const busy = new Set();
|
|
2917
3277
|
for (const cli of clis) {
|
|
2918
3278
|
const lsof = await runCmd('lsof', ['-a', '-p', String(cli.pid), '-d', 'cwd', '-Fn', '-w']);
|
|
3279
|
+
// 与注释的约定一致:任一 CLI 的工作目录取不到就整轮放弃(scan=false)——
|
|
3280
|
+
// lsof 缺失/被限权/进程行取不到 cwd 时都不能把项目判成空闲
|
|
3281
|
+
if (lsof.err) return SCAN_OFF;
|
|
2919
3282
|
const cwd = (lsof.stdout.match(/^n(.+)$/m) || [])[1];
|
|
2920
|
-
if (!cwd)
|
|
3283
|
+
if (!cwd) return SCAN_OFF;
|
|
2921
3284
|
const wantedPaths = wantedByCwd.get(cwd);
|
|
2922
3285
|
if (!wantedPaths) continue;
|
|
2923
3286
|
for (const child of procs) {
|
|
@@ -2937,8 +3300,10 @@ async function scanIdleBusyDarwin(paths) {
|
|
|
2937
3300
|
// 查任务索引反查工作区;认不出且无会话 ID 的活动子进程无法归属 → 全部请求判忙(保守)。
|
|
2938
3301
|
// 路径比较忽略大小写与分隔符差异
|
|
2939
3302
|
async function scanIdleBusyWindows(paths, dataRoot) {
|
|
3303
|
+
// 输出编码固定 UTF-8(同 pickFolder.mjs):默认走 OEM 代码页(中文系统 936),
|
|
3304
|
+
// 按 UTF-8 解码不只乱码,GBK 尾字节 0x5C 还会被当转义符让 JSON.parse 抛错
|
|
2940
3305
|
const ps = await runCmd('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command',
|
|
2941
|
-
'Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,Name,CommandLine | ConvertTo-Json -Compress'], 30000);
|
|
3306
|
+
'[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,Name,CommandLine | ConvertTo-Json -Compress'], 30000);
|
|
2942
3307
|
if (ps.err || !ps.stdout.trim()) return SCAN_OFF;
|
|
2943
3308
|
let list;
|
|
2944
3309
|
try {
|
|
@@ -2984,9 +3349,11 @@ export async function classifyIdleBusyWindows(procs, paths, lookupTaskWs) {
|
|
|
2984
3349
|
if (child.ppid !== cli.pid) continue;
|
|
2985
3350
|
if (isInfraCmdline(child.cmdline)) continue;
|
|
2986
3351
|
if (!child.cmdline) { unattributed = true; continue; }
|
|
2987
|
-
// 会话 id 有 sess_ 与 session_ 两种前缀(新版应用为 session_
|
|
2988
|
-
//
|
|
2989
|
-
|
|
3352
|
+
// 会话 id 有 sess_ 与 session_ 两种前缀(新版应用为 session_);字符集与
|
|
3353
|
+
// 路由校验的 id 白名单一致(含 . 和 _)——字符类偏窄会在这些字符处截断成
|
|
3354
|
+
// 前缀,撞上别的真实 task_id 会把错误项目判忙。匹配不到会走 unattributed
|
|
3355
|
+
// 全量判忙——新形式命令挂着时空闲回收会整体停摆
|
|
3356
|
+
const sess = child.cmdline.match(/(?:sess|session)_[A-Za-z0-9._-]+/);
|
|
2990
3357
|
if (sess) await markByTask(sess[0]);
|
|
2991
3358
|
else unattributed = true; // 用户进程但无会话线索:归属不到具体项目
|
|
2992
3359
|
}
|
|
@@ -3080,7 +3447,7 @@ const TITLE_GEN_DEFAULT_PROMPTS = {
|
|
|
3080
3447
|
// 界面语言:桌面设置(v2/setting.json 的 localePreference)为 en-US / zh-CN 时
|
|
3081
3448
|
// 直接采用;system 或未设置时按系统环境语言判断(中文环境 → 中文,其余 → 英文)
|
|
3082
3449
|
function titleGenLocale() {
|
|
3083
|
-
const s = readJsonFile(join(
|
|
3450
|
+
const s = readJsonFile(join(resolveDataRootDir(), 'v2', 'setting.json')); // 官方 v2 配置跟数据根迁移(同 startHelper 的 settingsFile)
|
|
3084
3451
|
const pref = String((s && s.localePreference) || '').toLowerCase();
|
|
3085
3452
|
if (pref.startsWith('en')) return 'en';
|
|
3086
3453
|
if (pref.startsWith('zh')) return 'zh';
|
|
@@ -3102,7 +3469,7 @@ const TITLE_GEN_TIMEOUT_MS = 60000; // 单次模型调用超时(与官方起
|
|
|
3102
3469
|
// providerFamilyConnectionSelections)读当前登录的连接方式(kind 含
|
|
3103
3470
|
// individual → 个人、team → 团队),读不到时退回“个人/团队”
|
|
3104
3471
|
function codingPlanKindByFamily() {
|
|
3105
|
-
const s = readJsonFile(join(
|
|
3472
|
+
const s = readJsonFile(join(resolveDataRootDir(), 'v2', 'setting.json')); // 官方 v2 配置跟数据根迁移
|
|
3106
3473
|
const sel = (s && s.providerFamilyConnectionSelections && typeof s.providerFamilyConnectionSelections === 'object')
|
|
3107
3474
|
? s.providerFamilyConnectionSelections : {};
|
|
3108
3475
|
const out = {};
|
|
@@ -3152,7 +3519,7 @@ export function listTitleGenProviders() {
|
|
|
3152
3519
|
const byId = new Map();
|
|
3153
3520
|
const planKinds = codingPlanKindByFamily();
|
|
3154
3521
|
// 注册表读一次,供下方各条目的协议判定兜底复用(文件不存在时为空数组)
|
|
3155
|
-
const headroomProviders = (readJsonFile(
|
|
3522
|
+
const headroomProviders = (readJsonFile(defaultHeadroomFile()) || {}).providers || [];
|
|
3156
3523
|
const add = (id, { name, aliases = [], kind, baseUrl, apiKey, models = [] }) => {
|
|
3157
3524
|
baseUrl = typeof baseUrl === 'string' ? baseUrl.trim() : '';
|
|
3158
3525
|
apiKey = typeof apiKey === 'string' ? apiKey.trim() : '';
|
|
@@ -3178,9 +3545,9 @@ export function listTitleGenProviders() {
|
|
|
3178
3545
|
out.push(entry);
|
|
3179
3546
|
};
|
|
3180
3547
|
|
|
3181
|
-
const v2 = readJsonFile(join(
|
|
3548
|
+
const v2 = readJsonFile(join(resolveDataRootDir(), 'v2', 'config.json')); // 官方 v2 配置跟数据根迁移
|
|
3182
3549
|
const providers = (v2 && typeof v2.provider === 'object' && v2.provider) || {};
|
|
3183
|
-
const rulesDoc = readJsonFile(join(
|
|
3550
|
+
const rulesDoc = readJsonFile(join(resolveDataRootDir(), 'v2', 'provider_config.json'));
|
|
3184
3551
|
const rules = (rulesDoc && rulesDoc.config?.providerConfigRules?.providerRules) || [];
|
|
3185
3552
|
const ruleById = new Map(rules.filter((r) => r && typeof r.providerId === 'string').map((r) => [r.providerId, r]));
|
|
3186
3553
|
// 同一 id 在两张表的字段并起来(provider 表优先:地址/密钥以桌面实际在用的为准)
|
|
@@ -3261,6 +3628,64 @@ async function callOpenAiText(baseUrl, apiKey, model, content) {
|
|
|
3261
3628
|
} finally { clearTimeout(timer); }
|
|
3262
3629
|
}
|
|
3263
3630
|
|
|
3631
|
+
// 生成标题的双写收尾,顺序不能反:先写 CLI 会话库(title_source=custom,权威层
|
|
3632
|
+
// ——官方自动起名看到 custom 会放弃,桌面同步器会把 custom 标题带着 overridden=1
|
|
3633
|
+
// 送回任务索引),再写任务索引(展示层,立即上屏)。只写任务索引时,官方运行时
|
|
3634
|
+
// 排队的自动标题会在几秒后把它覆盖(实测)。CLI 库不可写(旧版无 title_source
|
|
3635
|
+
// 列 / 无该会话行)不阻断:退回单写任务索引的旧行为;任务索引随后失败也不回滚
|
|
3636
|
+
// CLI——同步器会补。写库撞上宿主写入时稍候重试(起名不急这几秒)。
|
|
3637
|
+
// force = 手动“自动重命名”:已重命名的会话也照写(用户显式改名)。
|
|
3638
|
+
// 返回 { written, store, error }:store '' 成功 | skipped 原因 | 'error…';
|
|
3639
|
+
// error 非空 = 任务索引最终没写成(err 带 code,由调用方转 500)。
|
|
3640
|
+
// CLI 库写成功才登记回查记录(reconcileCustomTitles 只认这些记录校正),
|
|
3641
|
+
// 登记只是回查簿记,失败不影响改名结果。导出以便测试
|
|
3642
|
+
export async function writeGeneratedTitle(dataRoot, configFile, sessId, title, { force = false } = {}) {
|
|
3643
|
+
let written = false;
|
|
3644
|
+
let store = ''; // CLI 会话库写入结果:'' 成功 | skipped 原因 | 'error…'
|
|
3645
|
+
for (let attempt = 0; ; attempt++) {
|
|
3646
|
+
try {
|
|
3647
|
+
const r = await setCustomSessionTitle(dataRoot, sessId, title);
|
|
3648
|
+
store = r.written ? '' : (r.skipped || 'skipped');
|
|
3649
|
+
break;
|
|
3650
|
+
} catch (err) {
|
|
3651
|
+
if (err.code === 'index-busy' && attempt < 2) {
|
|
3652
|
+
await new Promise((r) => setTimeout(r, 1200));
|
|
3653
|
+
continue;
|
|
3654
|
+
}
|
|
3655
|
+
store = 'error: ' + (err?.message || err);
|
|
3656
|
+
titleGenLog(dataRoot, `cli-store-error sess=${sessId.slice(0, 13)} err=${err?.message || err}`);
|
|
3657
|
+
break;
|
|
3658
|
+
}
|
|
3659
|
+
}
|
|
3660
|
+
for (let attempt = 0; ; attempt++) {
|
|
3661
|
+
try {
|
|
3662
|
+
const r = await setTaskTitleIfNotOverridden(dataRoot, sessId, title, { force });
|
|
3663
|
+
written = r.written;
|
|
3664
|
+
break;
|
|
3665
|
+
} catch (err) {
|
|
3666
|
+
if (err.code === 'index-busy' && attempt < 2) {
|
|
3667
|
+
await new Promise((r) => setTimeout(r, 1200));
|
|
3668
|
+
continue;
|
|
3669
|
+
}
|
|
3670
|
+
titleGenLog(dataRoot, `index-error sess=${sessId.slice(0, 13)} err=${err?.message || err}`);
|
|
3671
|
+
return { written, store, error: err };
|
|
3672
|
+
}
|
|
3673
|
+
}
|
|
3674
|
+
if (store === '') {
|
|
3675
|
+
// 跨进程锁内同步读改写,防止与别的写入方互相覆盖整份配置
|
|
3676
|
+
await withConfigLock(configFile, () => {
|
|
3677
|
+
try {
|
|
3678
|
+
const c = loadConfig(configFile);
|
|
3679
|
+
c.titleGen.customWritten = { ...(c.titleGen.customWritten || {}), [sessId]: { title, at: Date.now() } };
|
|
3680
|
+
if (!saveConfig(configFile, c)) throw new Error('zcodepro.json 损坏,写入被拒');
|
|
3681
|
+
} catch (err) {
|
|
3682
|
+
titleGenLog(dataRoot, `customWritten-save-error sess=${sessId.slice(0, 13)} err=${err?.message || err}`);
|
|
3683
|
+
}
|
|
3684
|
+
});
|
|
3685
|
+
}
|
|
3686
|
+
return { written, store };
|
|
3687
|
+
}
|
|
3688
|
+
|
|
3264
3689
|
// 生成标题。provider 三种取值:
|
|
3265
3690
|
// - 'session':跟随当前会话——从任务索引解析该会话正在用的供应商与模型
|
|
3266
3691
|
// (model 已填时用填写的),供应商需在可直连列表内;
|
|
@@ -3388,6 +3813,7 @@ export async function exchangeAccountProjectToken(family, dataRoot) {
|
|
|
3388
3813
|
const issueCtrl = new AbortController();
|
|
3389
3814
|
const issueTimer = setTimeout(() => issueCtrl.abort(), 20000);
|
|
3390
3815
|
let issueResp;
|
|
3816
|
+
let issue;
|
|
3391
3817
|
try {
|
|
3392
3818
|
issueResp = await fetch(`${origin}${keysUrl}/${encodeURIComponent(apiKeyId)}/access_tokens`, {
|
|
3393
3819
|
method: 'POST',
|
|
@@ -3395,8 +3821,9 @@ export async function exchangeAccountProjectToken(family, dataRoot) {
|
|
|
3395
3821
|
headers: { 'content-type': 'application/json', authorization: `Bearer ${loginToken}` },
|
|
3396
3822
|
body: JSON.stringify({ clientType: 'zcode', clientVersion: VERSION }),
|
|
3397
3823
|
});
|
|
3824
|
+
// 响应体读取也放超时保护内(与 api() 同款):管理接口回完头拖着不发体会永久挂起
|
|
3825
|
+
issue = await issueResp.json().catch(() => null);
|
|
3398
3826
|
} finally { clearTimeout(issueTimer); }
|
|
3399
|
-
const issue = await issueResp.json().catch(() => null);
|
|
3400
3827
|
const issueData = (issue && [200, 0, '200', '0'].includes(issue.code)) ? issue.data : null;
|
|
3401
3828
|
if (!issueData) throw new Error(`签发项目 token 失败(${issueResp.status})`);
|
|
3402
3829
|
// enable 语义与官方一致:旧版接口不回该字段(实测回的是同义的 enabled),
|
|
@@ -3511,7 +3938,9 @@ export function validateVisionConfig(raw) {
|
|
|
3511
3938
|
if (!Array.isArray(raw.chain) || raw.chain.some((n) => typeof n !== 'string')) return [null, 'chain 必须是代理名数组'];
|
|
3512
3939
|
if (!Array.isArray(raw.proxies)) return [null, 'proxies 必须是数组'];
|
|
3513
3940
|
const cfg = {
|
|
3514
|
-
|
|
3941
|
+
// enabled 同 cardUi:显式给值才写键,缺省保持磁盘原值(否则磁盘上显式
|
|
3942
|
+
// false 会被一次省略 enabled 的保存覆盖回 true)
|
|
3943
|
+
...(raw.enabled !== undefined ? { enabled: raw.enabled !== false } : {}),
|
|
3515
3944
|
chainMode: raw.chainMode,
|
|
3516
3945
|
chain: raw.chain.map((s) => s.trim()).filter(Boolean),
|
|
3517
3946
|
proxies: [],
|
|
@@ -3614,8 +4043,10 @@ export function validateRtkWhitelist(raw) {
|
|
|
3614
4043
|
// (钩子视为未自定义);文件头带注释说明格式,方便用户直接编辑。
|
|
3615
4044
|
function writeRtkState(dir, { mode, whitelist }) {
|
|
3616
4045
|
mkdirSync(dir, { recursive: true });
|
|
4046
|
+
// 临时名带 pid+随机:钩子进程与面板并发写这两个文件时不共用一个 .tmp
|
|
4047
|
+
const pidTmp = (f) => `${f}.${process.pid}.${Date.now().toString(36)}.tmp`;
|
|
3617
4048
|
const modeFile = join(dir, 'mode');
|
|
3618
|
-
const tmp = modeFile
|
|
4049
|
+
const tmp = pidTmp(modeFile);
|
|
3619
4050
|
writeFileSync(tmp, mode, 'utf8');
|
|
3620
4051
|
renameSync(tmp, modeFile);
|
|
3621
4052
|
const wlFile = join(dir, 'whitelist');
|
|
@@ -3623,7 +4054,7 @@ function writeRtkState(dir, { mode, whitelist }) {
|
|
|
3623
4054
|
try { unlinkSync(wlFile); } catch { /* 不存在即目标状态 */ }
|
|
3624
4055
|
return;
|
|
3625
4056
|
}
|
|
3626
|
-
const wlTmp = wlFile
|
|
4057
|
+
const wlTmp = pidTmp(wlFile);
|
|
3627
4058
|
writeFileSync(wlTmp, '# rtk 白名单(不压缩直接放行):每行 name 或 git:name(git 子命令)。删除本文件即恢复默认。\n'
|
|
3628
4059
|
+ whitelist.join('\n') + '\n', 'utf8');
|
|
3629
4060
|
renameSync(wlTmp, wlFile);
|
|
@@ -3746,16 +4177,20 @@ function startRtkUpgrade() {
|
|
|
3746
4177
|
j.output += `下载 ${info.assetName}…\n`;
|
|
3747
4178
|
const archPath = join(dir, info.assetName);
|
|
3748
4179
|
await downloadToFile(j, info.assetUrl, archPath, 600000);
|
|
3749
|
-
// sha256 校验(checksums.txt
|
|
3750
|
-
|
|
4180
|
+
// sha256 校验(checksums.txt 与本机摘要工具;失败即中止,不替换)。
|
|
4181
|
+
// Release 没有 checksums.txt:无从校验,直接中止升级,绝不替换未经校验的二进制
|
|
4182
|
+
if (!info.sumsUrl) throw new Error('Release 缺少 checksums.txt,无法校验下载文件,已中止升级');
|
|
4183
|
+
{
|
|
3751
4184
|
const sumPath = join(dir, 'checksums.txt');
|
|
3752
4185
|
await downloadToFile(j, info.sumsUrl, sumPath, 30000);
|
|
3753
4186
|
const want = readFileSync(sumPath, 'utf8').split('\n')
|
|
3754
4187
|
.find((l) => l.trim().endsWith(info.assetName))?.trim().split(/\s+/)[0];
|
|
3755
4188
|
let got = '';
|
|
3756
4189
|
if (WIN) {
|
|
4190
|
+
// 路径包进单引号(内部 ' 写成 ''):双引号里 $、反引号会被当变量/子表达式求值
|
|
4191
|
+
const safeArch = String(archPath).replace(/'/g, "''");
|
|
3757
4192
|
const local = await execCapture('powershell.exe',
|
|
3758
|
-
['-NoProfile', '-Command', `(Get-FileHash -Algorithm SHA256 -LiteralPath
|
|
4193
|
+
['-NoProfile', '-Command', `(Get-FileHash -Algorithm SHA256 -LiteralPath '${safeArch}').Hash`], 60000);
|
|
3759
4194
|
got = (/[0-9a-fA-F]{64}/.exec(local.output || '') || [''])[0];
|
|
3760
4195
|
} else {
|
|
3761
4196
|
const sumCmd = process.platform === 'darwin' ? 'shasum' : 'sha256sum';
|
|
@@ -3783,6 +4218,9 @@ function startRtkUpgrade() {
|
|
|
3783
4218
|
if (!WIN) chmodSync(newBin, 0o755);
|
|
3784
4219
|
const v = await binVersionOf(newBin);
|
|
3785
4220
|
if (!v) throw new Error('新版本无法运行(--version 无输出)');
|
|
4221
|
+
// 试运行有约 10 秒窗口:期间被取消就别再替换二进制(否则状态显示
|
|
4222
|
+
// 已取消又显示升级成功,自相矛盾)
|
|
4223
|
+
if (j.canceled) throw new Error('canceled');
|
|
3786
4224
|
// 放置:全新安装建目录直接放;已有旧文件则原子替换(先挪走,失败可回滚)
|
|
3787
4225
|
if (freshInstall) mkdirSync(dirname(bin), { recursive: true });
|
|
3788
4226
|
const backup = bin + '.rtk-old';
|
|
@@ -3825,20 +4263,39 @@ function startRtkUpgrade() {
|
|
|
3825
4263
|
// 把目录追加进用户级 PATH(HKCU\Environment,Windows):保持原值类型不展开(REG_EXPAND_SZ
|
|
3826
4264
|
// 里的 %VAR% 引用原样保留),已含该目录则不动。不广播环境变更——运行中的进程读不到,
|
|
3827
4265
|
// 重启 ZCode 后新会话生效(rtk 钩子按固定清单找 rtk,不受 PATH 影响)。
|
|
4266
|
+
// 注册表读写走 PowerShell 而不是 reg.exe:reg 的输出按系统代码页编码(中文 Windows
|
|
4267
|
+
// 是 GBK),Node 按 UTF-8 解码会把中文条目弄乱,原样写回就把用户 PATH 写坏了;
|
|
4268
|
+
// PowerShell 经 .NET 读写值本身不做编码转换,只有控制台输出要固定 UTF-8(同 pickFolder.mjs)。
|
|
3828
4269
|
async function ensureUserPathEntry(dir) {
|
|
3829
|
-
const
|
|
3830
|
-
|
|
3831
|
-
|
|
3832
|
-
|
|
4270
|
+
const psRead = [
|
|
4271
|
+
'[Console]::OutputEncoding = [System.Text.Encoding]::UTF8',
|
|
4272
|
+
"$k = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $false)",
|
|
4273
|
+
"if ($null -eq $k -or -not ($k.GetValueNames() -contains 'PATH')) { exit 2 }",
|
|
4274
|
+
"$v = $k.GetValue('PATH', $null, [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)",
|
|
4275
|
+
"[Console]::Out.Write([string]($k.GetValueKind('PATH')) + [char]10 + [string]$v)",
|
|
4276
|
+
].join('; ');
|
|
4277
|
+
const q = await execCapture('powershell.exe', ['-NoProfile', '-Command', psRead], 15000);
|
|
4278
|
+
// 值缺失才新建;读取本身出错一律不动用户 PATH(不能把整份值覆盖没了)
|
|
4279
|
+
let kind = 'String';
|
|
4280
|
+
let next = dir; // 缺失分支写调用方给的目录,别写死别的路径
|
|
4281
|
+
if (q.code !== 2) {
|
|
4282
|
+
if (!q.ok) return false;
|
|
4283
|
+
const nl = q.output.indexOf('\n');
|
|
4284
|
+
const curKind = (nl < 0 ? q.output : q.output.slice(0, nl)).trim();
|
|
4285
|
+
if (curKind !== 'String' && curKind !== 'ExpandString') return false; // REG_SZ/REG_EXPAND_SZ 之外的类型不认识,不动它
|
|
4286
|
+
const cur = (nl < 0 ? '' : q.output.slice(nl + 1)).trim();
|
|
4287
|
+
const norm = (s) => s.replace(/[/\\]+/g, '\\').replace(/\\+$/, '').toLowerCase();
|
|
4288
|
+
const expanded = cur.replaceAll('%USERPROFILE%', homedir());
|
|
4289
|
+
if (expanded.split(';').some((p) => p && norm(p) === norm(dir))) return true;
|
|
4290
|
+
kind = curKind;
|
|
4291
|
+
next = cur ? `${cur};${dir}` : dir;
|
|
3833
4292
|
}
|
|
3834
|
-
|
|
3835
|
-
|
|
3836
|
-
|
|
3837
|
-
|
|
3838
|
-
|
|
3839
|
-
|
|
3840
|
-
const next = cur ? `${cur};${dir}` : dir;
|
|
3841
|
-
const r = await execCapture('reg', ['add', 'HKCU\\Environment', '/v', 'PATH', '/t', m[1], '/d', next, '/f'], 15000);
|
|
4293
|
+
// 值包进单引号(内部 ' 写成 ''):$、反引号、$( ) 都不会被当变量/子表达式求值
|
|
4294
|
+
const psWrite = [
|
|
4295
|
+
"$k = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Environment')",
|
|
4296
|
+
`$k.SetValue('PATH', '${next.replace(/'/g, "''")}', [Microsoft.Win32.RegistryValueKind]::${kind})`,
|
|
4297
|
+
].join('; ');
|
|
4298
|
+
const r = await execCapture('powershell.exe', ['-NoProfile', '-Command', psWrite], 15000);
|
|
3842
4299
|
return r.ok;
|
|
3843
4300
|
}
|
|
3844
4301
|
|
|
@@ -3893,8 +4350,8 @@ export function writeHeadroomConfig(file, cfg) {
|
|
|
3893
4350
|
for (const k of ['kompressBackend', 'powerSaveCpu', 'powerWatchInterval']) {
|
|
3894
4351
|
if (cfg[k] !== undefined) out[k] = cfg[k];
|
|
3895
4352
|
}
|
|
3896
|
-
const tmp = file
|
|
3897
|
-
writeFileSync(tmp, JSON.stringify(out, null, 2) + '\n', 'utf8');
|
|
4353
|
+
const tmp = `${file}.${process.pid}.${Date.now().toString(36)}.tmp`; // 防多写者共用同一 .tmp 撕裂
|
|
4354
|
+
writeFileSync(tmp, JSON.stringify(out, null, 2) + '\n', { encoding: 'utf8', mode: 0o600 }); // 配置含供应商凭据,限制本人读写
|
|
3898
4355
|
renameSync(tmp, file);
|
|
3899
4356
|
}
|
|
3900
4357
|
|
|
@@ -3998,18 +4455,31 @@ async function downloadToFile(j, url, dest, timeoutMs = 600000) {
|
|
|
3998
4455
|
if (!res.ok || !res.body) throw new Error(`下载失败 HTTP ${res.status}`);
|
|
3999
4456
|
const total = Number(res.headers.get('content-length')) || 0;
|
|
4000
4457
|
const out = createWriteStream(dest);
|
|
4458
|
+
// 写盘错误必须有人接(磁盘满/杀软锁文件):无人订阅的 error 事件直接崩进程,
|
|
4459
|
+
// 挂在 drain 等待上时还会永久不返回、升级任务卡死
|
|
4460
|
+
let outErr = null;
|
|
4461
|
+
out.on('error', (e) => { outErr = e; });
|
|
4001
4462
|
let got = 0;
|
|
4002
4463
|
let lastPct = -1;
|
|
4003
4464
|
try {
|
|
4004
4465
|
for await (const chunk of res.body) {
|
|
4005
4466
|
if (j.canceled) throw new Error('canceled');
|
|
4006
|
-
if (
|
|
4467
|
+
if (outErr) throw outErr;
|
|
4468
|
+
if (!out.write(chunk)) {
|
|
4469
|
+
await new Promise((r) => {
|
|
4470
|
+
const done = () => { out.off('drain', done); out.off('error', done); r(); };
|
|
4471
|
+
out.once('drain', done);
|
|
4472
|
+
out.once('error', done); // 出错也解除等待,别永久挂起
|
|
4473
|
+
});
|
|
4474
|
+
if (outErr) throw outErr;
|
|
4475
|
+
}
|
|
4007
4476
|
got += chunk.length;
|
|
4008
4477
|
if (total > 0) {
|
|
4009
4478
|
const pct = Math.floor((got / total) * 100);
|
|
4010
4479
|
if (pct >= lastPct + 5) { lastPct = pct; j.output += `下载中 ${pct}%\n`; }
|
|
4011
4480
|
}
|
|
4012
4481
|
}
|
|
4482
|
+
if (outErr) throw outErr;
|
|
4013
4483
|
await new Promise((resolve, reject) => { out.end(resolve); out.once('error', reject); });
|
|
4014
4484
|
} catch (err) {
|
|
4015
4485
|
try { out.destroy(); } catch { /* ignore */ }
|
|
@@ -4206,10 +4676,10 @@ async function runHeadroomHook(args, timeoutMs = 30000) {
|
|
|
4206
4676
|
// 旧版 headroom 插件的钩子只匹配 startup,代理不会自动启动(要等用户新建会话或
|
|
4207
4677
|
// 手动重启)。helper 就绪后延迟几秒补一次 ensure:动作幂等(已在跑秒回),新版
|
|
4208
4678
|
// 插件侧还带跨进程锁;失败一律静默——没装 headroom 插件/本体的环境不能打扰启动。
|
|
4209
|
-
|
|
4210
|
-
|
|
4211
|
-
if (
|
|
4212
|
-
|
|
4679
|
+
function ensureHeadroomAtStartup(state = {}) {
|
|
4680
|
+
// 标志挂 state(跨热替换实例共享):放模块级时每次热替换都重置,兜底 ensure 会重复排队
|
|
4681
|
+
if (state.headroomEnsureFired) return;
|
|
4682
|
+
state.headroomEnsureFired = true;
|
|
4213
4683
|
const timer = setTimeout(() => {
|
|
4214
4684
|
runHeadroomHook(['ensure'], 20000).catch(() => { /* 兜底失败不影响启动 */ });
|
|
4215
4685
|
}, 5000);
|
|
@@ -4279,12 +4749,17 @@ export function headroomUsageScan(dataRoot) {
|
|
|
4279
4749
|
// 切换启用状态:enable=false 时 127.0.0.1 条目 → 直连(并记录);enable=true 时按
|
|
4280
4750
|
// 记录把直连条目切回代理。改写前各留 .zcodepro-backup 备份,与同步导入同款。
|
|
4281
4751
|
export function setHeadroomUsage(dataRoot, configFile, enable) {
|
|
4752
|
+
// 同步调用点用同步等锁变体:整段读改写在跨进程锁内完成,防止与别的写入方互相覆盖
|
|
4753
|
+
return withConfigLockSync(configFile, () => setHeadroomUsageLocked(dataRoot, configFile, enable));
|
|
4754
|
+
}
|
|
4755
|
+
|
|
4756
|
+
function setHeadroomUsageLocked(dataRoot, configFile, enable) {
|
|
4282
4757
|
const backupFile = (p) => {
|
|
4283
4758
|
try { if (existsSync(p)) copyFileSync(p, p + '.zcodepro-backup'); } catch { /* 备份失败不阻塞 */ }
|
|
4284
4759
|
};
|
|
4285
4760
|
const atomicWrite = (p, obj) => {
|
|
4286
|
-
const tmp = p
|
|
4287
|
-
writeFileSync(tmp, JSON.stringify(obj, null, 2) + '\n', 'utf8');
|
|
4761
|
+
const tmp = `${p}.${process.pid}.${Date.now().toString(36)}.tmp`; // 防多写者共用同一 .tmp 撕裂
|
|
4762
|
+
writeFileSync(tmp, JSON.stringify(obj, null, 2) + '\n', { encoding: 'utf8', mode: 0o600 });
|
|
4288
4763
|
renameSync(tmp, p);
|
|
4289
4764
|
};
|
|
4290
4765
|
const v2File = join(dataRoot, 'v2', 'config.json');
|
|
@@ -4336,7 +4811,9 @@ export function setHeadroomUsage(dataRoot, configFile, enable) {
|
|
|
4336
4811
|
if (touched) { backupFile(pcFile); atomicWrite(pcFile, pc); }
|
|
4337
4812
|
}
|
|
4338
4813
|
config.headroomRoutes = routes;
|
|
4339
|
-
saveConfig(configFile, config)
|
|
4814
|
+
if (!saveConfig(configFile, config)) {
|
|
4815
|
+
return { ok: false, code: 'config-unreadable', error: 'zcodepro.json 读取失败或已损坏,保存中止(请先修好配置文件)' };
|
|
4816
|
+
}
|
|
4340
4817
|
return { ok: true, changed };
|
|
4341
4818
|
}
|
|
4342
4819
|
|
|
@@ -4506,11 +4983,33 @@ export async function ensureZcodePluginsMarketplace() {
|
|
|
4506
4983
|
|
|
4507
4984
|
// /plugins/update 并发控制:启动自动更新、打开设置弹窗时的自动触发、手动按钮、
|
|
4508
4985
|
// 各插件面板的单插件操作都打到这个端点,而 CLI 同时改同一个插件目录会互相破坏。
|
|
4509
|
-
//
|
|
4510
|
-
//
|
|
4511
|
-
let
|
|
4986
|
+
// 按目标键(全量 = 空键,或同一插件名)去重:同目标的并发请求共用同一次执行结果,
|
|
4987
|
+
// 不同目标各占一个槽位互不顶掉、排队串行,后到的等前一个结束再跑
|
|
4988
|
+
let pluginsUpdateJobs = new Map(); // only 键 → 在跑或排队的任务 promise
|
|
4989
|
+
// 一般后台任务在途标志(市场克隆/刷新、WebDAV 同步):排队 + 执行期间 +1,跑完 -1
|
|
4990
|
+
let busyBackground = 0;
|
|
4991
|
+
// 后台任务占用标志:启动器热替换前查询,有任务在跑就延后换——新模块实例
|
|
4992
|
+
// 不继承任务锁,立刻换会跟旧实例拉起的子进程(插件更新/同步/转码等)并发互删中间文件。
|
|
4993
|
+
// 升级任务对象完成后变量不置回 null(只把 running 置 false),必须看 running
|
|
4994
|
+
export function busyJobs() {
|
|
4995
|
+
return !!(pluginsUpdateJobs.size || busyBackground || (headroomUpgradeJob && headroomUpgradeJob.running) || (rtkUpgradeJob && rtkUpgradeJob.running) || transcodeJobs.size);
|
|
4996
|
+
}
|
|
4512
4997
|
let pluginsUpdateQueue = Promise.resolve();
|
|
4513
4998
|
|
|
4999
|
+
// 任务在途(排队 + 执行)期间计入忙碌标志,跑完清掉,热替换据此延后
|
|
5000
|
+
function trackBusy(promise) {
|
|
5001
|
+
busyBackground += 1;
|
|
5002
|
+
promise.then(() => { busyBackground -= 1; }, () => { busyBackground -= 1; });
|
|
5003
|
+
return promise;
|
|
5004
|
+
}
|
|
5005
|
+
|
|
5006
|
+
// 把一步市场操作排进串行队列(状态页的节流同步用):与更新任务互斥执行
|
|
5007
|
+
function runPluginsQueued(fn) {
|
|
5008
|
+
const promise = pluginsUpdateQueue.then(() => fn());
|
|
5009
|
+
pluginsUpdateQueue = promise.then(() => undefined, () => undefined);
|
|
5010
|
+
return trackBusy(promise);
|
|
5011
|
+
}
|
|
5012
|
+
|
|
4514
5013
|
async function runPluginsUpdateJob(body) {
|
|
4515
5014
|
// name 指定时只处理该插件:已装且有更新则更新,未装则安装(各插件面板的单插件操作)
|
|
4516
5015
|
const only = typeof body?.name === 'string' && body.name.trim() ? body.name.trim() : null;
|
|
@@ -4555,18 +5054,21 @@ async function runPluginsUpdateJob(body) {
|
|
|
4555
5054
|
|
|
4556
5055
|
function enqueuePluginsUpdate(body) {
|
|
4557
5056
|
const only = typeof body?.name === 'string' && body.name.trim() ? body.name.trim() : null;
|
|
4558
|
-
|
|
5057
|
+
// 按 only 键去重:单个槽位会被后到的不同目标顶掉,被顶掉的任务随后会重复跑
|
|
5058
|
+
const key = only || '';
|
|
5059
|
+
const inflight = pluginsUpdateJobs.get(key);
|
|
5060
|
+
if (inflight) return inflight;
|
|
4559
5061
|
const prev = pluginsUpdateQueue;
|
|
4560
5062
|
const promise = (async () => {
|
|
4561
5063
|
await prev;
|
|
4562
5064
|
try {
|
|
4563
5065
|
return await runPluginsUpdateJob(body);
|
|
4564
5066
|
} finally {
|
|
4565
|
-
|
|
5067
|
+
pluginsUpdateJobs.delete(key); // 同键去重保证此刻槽里就是自己,不用再比对
|
|
4566
5068
|
}
|
|
4567
5069
|
})();
|
|
4568
5070
|
pluginsUpdateQueue = promise.then(() => undefined, () => undefined);
|
|
4569
|
-
|
|
5071
|
+
pluginsUpdateJobs.set(key, promise);
|
|
4570
5072
|
return promise;
|
|
4571
5073
|
}
|
|
4572
5074
|
|
|
@@ -4596,9 +5098,13 @@ export function writeAgents(body, agentsFile) {
|
|
|
4596
5098
|
} else if (empty) {
|
|
4597
5099
|
return [200, { ok: true, content: '' }];
|
|
4598
5100
|
}
|
|
4599
|
-
|
|
5101
|
+
// 改名目标取真实路径:直接 rename 到 agentsFile 会把符号链接本身替换成
|
|
5102
|
+
// 普通文件(dotfiles 管理的链接会丢)
|
|
5103
|
+
let real = agentsFile;
|
|
5104
|
+
try { real = realpathSync(agentsFile); } catch { /* 文件还不存在:直接写原路径 */ }
|
|
5105
|
+
const tmp = `${real}.${process.pid}.${Date.now().toString(36)}.tmp`; // 防多写者共用同一 .tmp 撕裂
|
|
4600
5106
|
writeFileSync(tmp, body.content, 'utf8');
|
|
4601
|
-
renameSync(tmp,
|
|
5107
|
+
renameSync(tmp, real);
|
|
4602
5108
|
} catch (err) {
|
|
4603
5109
|
return [500, { ok: false, code: 'agents-write', error: '写入 AGENTS.md 失败: ' + (err?.message || err) }];
|
|
4604
5110
|
}
|
|
@@ -4719,7 +5225,12 @@ export function openWithDefaultApp(rawPath) {
|
|
|
4719
5225
|
const child = spawn('rundll32.exe', ['url.dll,FileProtocolHandler', p], { detached: true, stdio: 'ignore', windowsHide: true });
|
|
4720
5226
|
child.on('spawn', () => finish(null));
|
|
4721
5227
|
child.on('error', () => {
|
|
4722
|
-
|
|
5228
|
+
// cmd 兜底里路径不能直接拼进命令行(%VAR% 会被展开改写命令结构):
|
|
5229
|
+
// 走环境变量传入,% 的展开是单遍、变量值不会被二次扫描
|
|
5230
|
+
const viaCmd = spawn('cmd.exe', ['/d /s /c start "" "%ZP_OPEN%"'], {
|
|
5231
|
+
env: { ...process.env, ZP_OPEN: p },
|
|
5232
|
+
windowsVerbatimArguments: true, detached: true, stdio: 'ignore', windowsHide: true,
|
|
5233
|
+
});
|
|
4723
5234
|
viaCmd.on('spawn', () => finish(null));
|
|
4724
5235
|
viaCmd.on('error', finish);
|
|
4725
5236
|
});
|
|
@@ -4729,7 +5240,7 @@ export function openWithDefaultApp(rawPath) {
|
|
|
4729
5240
|
|
|
4730
5241
|
// 设置/清除项目自定义别名(纯渲染层,不动磁盘与任何 ZCode 数据)。
|
|
4731
5242
|
// alias 传空字符串/null 即清除该项目条目。
|
|
4732
|
-
export function setAlias(body, configFile) {
|
|
5243
|
+
export async function setAlias(body, configFile) {
|
|
4733
5244
|
const raw = typeof body?.path === 'string' ? body.path.trim() : '';
|
|
4734
5245
|
// 先校验再 resolve:resolve 会把相对路径悄悄变绝对,绕过校验
|
|
4735
5246
|
if (!raw || !isAbsolute(raw)) return [400, { ok: false, error: '无效的项目路径' }];
|
|
@@ -4739,16 +5250,21 @@ export function setAlias(body, configFile) {
|
|
|
4739
5250
|
if (name.length > 100) return [400, { ok: false, error: '别名过长(最多 100 字符)', code: 'name-too-long' }];
|
|
4740
5251
|
if (/[\r\n\0]/.test(name)) return [400, { ok: false, error: '别名不能包含换行等控制字符', code: 'name-invalid-chars' }];
|
|
4741
5252
|
}
|
|
4742
|
-
|
|
4743
|
-
|
|
4744
|
-
|
|
4745
|
-
|
|
4746
|
-
|
|
4747
|
-
|
|
4748
|
-
|
|
4749
|
-
|
|
4750
|
-
|
|
4751
|
-
|
|
5253
|
+
// 读改写放进跨进程锁内同步执行,防止与别的写入方互相覆盖整份配置
|
|
5254
|
+
return withConfigLock(configFile, () => {
|
|
5255
|
+
const config = loadConfig(configFile);
|
|
5256
|
+
if (!config.aliases || typeof config.aliases !== 'object') config.aliases = {};
|
|
5257
|
+
if (name) config.aliases[path] = name;
|
|
5258
|
+
else delete config.aliases[path];
|
|
5259
|
+
try {
|
|
5260
|
+
if (!saveConfig(configFile, config)) {
|
|
5261
|
+
return [500, { ok: false, code: 'config-unreadable', error: 'zcodepro.json 读取失败或已损坏,保存中止(请先修好配置文件)' }];
|
|
5262
|
+
}
|
|
5263
|
+
} catch (err) {
|
|
5264
|
+
return [500, { ok: false, code: 'config-save', error: '保存配置失败: ' + (err?.message || err) }];
|
|
5265
|
+
}
|
|
5266
|
+
return [200, { ok: true, path, alias: name, aliases: config.aliases }];
|
|
5267
|
+
});
|
|
4752
5268
|
}
|
|
4753
5269
|
|
|
4754
5270
|
function invalidProjectName(name) {
|
|
@@ -4796,11 +5312,11 @@ export async function relocateProject(body, dataRoot) {
|
|
|
4796
5312
|
}
|
|
4797
5313
|
}
|
|
4798
5314
|
|
|
4799
|
-
// setting.json 路径引用同步(recentProjects / lastWorkspaceSession / webRemoteControl
|
|
5315
|
+
// setting.json 路径引用同步(recentProjects / lastWorkspaceSession / webRemoteControl…);
|
|
5316
|
+
// 写回前比对 mtime 的重算逻辑在 remapSettingsPathsAtomic 里
|
|
4800
5317
|
const settingsFile = join(dataRoot, 'v2', 'setting.json');
|
|
4801
5318
|
try {
|
|
4802
|
-
|
|
4803
|
-
writeSettingsAtomic(settingsFile, remapSettingsPaths(settings, oldPath, newPath));
|
|
5319
|
+
remapSettingsPathsAtomic(settingsFile, oldPath, newPath);
|
|
4804
5320
|
} catch (err) {
|
|
4805
5321
|
return [500, { ok: false, error: '更新 setting.json 失败: ' + (err?.message || err) }];
|
|
4806
5322
|
}
|
|
@@ -4811,8 +5327,7 @@ export async function relocateProject(body, dataRoot) {
|
|
|
4811
5327
|
await remapTaskIndexPaths(dataRoot, oldPath, newPath);
|
|
4812
5328
|
} catch (err) {
|
|
4813
5329
|
try {
|
|
4814
|
-
|
|
4815
|
-
writeSettingsAtomic(settingsFile, remapSettingsPaths(cur, newPath, oldPath));
|
|
5330
|
+
remapSettingsPathsAtomic(settingsFile, newPath, oldPath);
|
|
4816
5331
|
} catch { /* 回滚失败:setting.json.zcodepro-backup 仍有兜底 */ }
|
|
4817
5332
|
return [500, {
|
|
4818
5333
|
ok: false,
|
|
@@ -4822,16 +5337,19 @@ export async function relocateProject(body, dataRoot) {
|
|
|
4822
5337
|
}
|
|
4823
5338
|
}
|
|
4824
5339
|
|
|
4825
|
-
//
|
|
5340
|
+
// 别名随迁(仅渲染层数据,失败不影响结果);读改写放进跨进程锁内同步执行,
|
|
5341
|
+
// 防止与别的写入方互相覆盖整份配置
|
|
4826
5342
|
try {
|
|
4827
|
-
|
|
4828
|
-
|
|
4829
|
-
|
|
4830
|
-
|
|
4831
|
-
|
|
4832
|
-
|
|
4833
|
-
|
|
4834
|
-
|
|
5343
|
+
await withConfigLock(join(dataRoot, 'zcodepro.json'), () => {
|
|
5344
|
+
const config = loadConfig(join(dataRoot, 'zcodepro.json'));
|
|
5345
|
+
const aliases = config.aliases || {};
|
|
5346
|
+
if (Object.prototype.hasOwnProperty.call(aliases, oldPath)) {
|
|
5347
|
+
const v = aliases[oldPath];
|
|
5348
|
+
delete aliases[oldPath];
|
|
5349
|
+
aliases[newPath] = v;
|
|
5350
|
+
saveConfig(join(dataRoot, 'zcodepro.json'), config);
|
|
5351
|
+
}
|
|
5352
|
+
});
|
|
4835
5353
|
} catch { /* ignore */ }
|
|
4836
5354
|
|
|
4837
5355
|
return [200, {
|