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/settings.mjs
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// 读用于 helper 的 /projects 端点;写仅用于“切换文件夹”后的路径引用同步,
|
|
3
3
|
// 采用原子写并保留备份。
|
|
4
4
|
|
|
5
|
-
import { copyFileSync, existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
5
|
+
import { copyFileSync, existsSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
|
|
6
6
|
import { join } from 'node:path';
|
|
7
7
|
|
|
8
8
|
export function readSettings(settingsFile) {
|
|
@@ -24,11 +24,24 @@ export function writeSettingsAtomic(settingsFile, next) {
|
|
|
24
24
|
if (existsSync(settingsFile)) {
|
|
25
25
|
try { copyFileSync(settingsFile, backup); } catch { /* 备份失败不阻塞 */ }
|
|
26
26
|
}
|
|
27
|
-
const tmp = settingsFile
|
|
27
|
+
const tmp = `${settingsFile}.${process.pid}.${Date.now().toString(36)}.tmp`; // 防多写者共用同一 .tmp 撕裂
|
|
28
28
|
writeFileSync(tmp, JSON.stringify(next, null, 2), 'utf8');
|
|
29
29
|
renameSync(tmp, settingsFile);
|
|
30
30
|
}
|
|
31
31
|
|
|
32
|
+
// 读改写 setting.json 的路径引用同步:应用本体也在写这个文件,写回前核对文件
|
|
33
|
+
// mtime,期间被写过就重读重算再写(最多重算一次),别用旧快照覆盖应用刚写的条目
|
|
34
|
+
export function remapSettingsPathsAtomic(settingsFile, oldPath, newPath) {
|
|
35
|
+
const mtimeOf = () => { try { return statSync(settingsFile).mtimeMs; } catch { return 0; } };
|
|
36
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
37
|
+
const stamp = mtimeOf();
|
|
38
|
+
const next = remapSettingsPaths(readSettings(settingsFile), oldPath, newPath);
|
|
39
|
+
if (attempt === 0 && mtimeOf() !== stamp) continue; // 期间被写过:重读重算再写
|
|
40
|
+
writeSettingsAtomic(settingsFile, next);
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
32
45
|
// 将 setting.json 中所有引用旧路径的字段映射到新路径,返回新 settings 对象。
|
|
33
46
|
// 替换时保留原值的尾分隔符风格(ZCode 自身多写带 / 的路径),减少与宿主写入的差异。
|
|
34
47
|
export function remapSettingsPaths(settings, oldPath, newPath) {
|
package/src/host/setup.mjs
CHANGED
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
// 文件编码,避开代码页问题;
|
|
16
16
|
// - 仓库内 PowerShell 脚本(install.ps1 等)必须保存为带 BOM 的 UTF-8。
|
|
17
17
|
import { execFileSync } from 'node:child_process';
|
|
18
|
-
import { accessSync, chmodSync, constants as fsConstants, copyFileSync, existsSync, mkdirSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
|
|
18
|
+
import { accessSync, chmodSync, constants as fsConstants, copyFileSync, existsSync, lstatSync, mkdirSync, readFileSync, readlinkSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
|
|
19
19
|
import { basename, dirname, join, sep } from 'node:path';
|
|
20
20
|
import { homedir, platform } from 'node:os';
|
|
21
21
|
import { fileURLToPath } from 'node:url';
|
|
@@ -144,6 +144,13 @@ function lnkIsOurs(lnkPath) {
|
|
|
144
144
|
|
|
145
145
|
const psQuote = (s) => String(s).replace(/'/g, "''"); // PowerShell 单引号字面量转义
|
|
146
146
|
|
|
147
|
+
// 降级快捷方式的起始位置:命令所在目录;剥不出绝对路径(PATH 里的裸命令名)就
|
|
148
|
+
// 交给调用方走回退(USERPROFILE 等),别把文件名当目录
|
|
149
|
+
const cmdWorkDir = (cmd) => {
|
|
150
|
+
const d = String(cmd).replace(/[\\/][^\\/]*$/, '');
|
|
151
|
+
return /^[A-Za-z]:[\\/]/.test(d) || /^[\\/]{2}/.test(d) ? d : '';
|
|
152
|
+
};
|
|
153
|
+
|
|
147
154
|
// 快捷方式计划(导出仅供测试审查,不执行)。desktop 为真时同时创建桌面快捷方式,
|
|
148
155
|
// 桌面目录由 PowerShell 的 GetFolderPath 解析(正确跟随 OneDrive 重定向等)。
|
|
149
156
|
// wshOk 为假(WSH 异常的机器)时降级:.lnk 直接经 cmd 最小化启动,不再依赖
|
|
@@ -159,7 +166,9 @@ export function windowsShortcutPlan(cmd, desktop = false, wshOk = true, menuLnk
|
|
|
159
166
|
' Dim parts()',
|
|
160
167
|
' ReDim parts(WScript.Arguments.Count - 1)',
|
|
161
168
|
' For i = 0 To WScript.Arguments.Count - 1',
|
|
162
|
-
'
|
|
169
|
+
" ' strip double quotes from each arg (Windows filenames never contain them)",
|
|
170
|
+
" ' an embedded quote would close the quoting and let the rest run as a command",
|
|
171
|
+
' parts(i) = """" & Replace(WScript.Arguments(i), """", "") & """"',
|
|
163
172
|
' Next',
|
|
164
173
|
' cmd = cmd & " " & Join(parts, " ")',
|
|
165
174
|
'End If',
|
|
@@ -182,8 +191,12 @@ export function windowsShortcutPlan(cmd, desktop = false, wshOk = true, menuLnk
|
|
|
182
191
|
] : [
|
|
183
192
|
'function setProps($l) {',
|
|
184
193
|
' $l.TargetPath = "$env:SystemRoot\\System32\\cmd.exe"',
|
|
194
|
+
// cmd.exe 会展开参数里的 %VAR%:cmd 路径本身含 % 的安装位置会被展开成别的
|
|
195
|
+
// 文件。命令行参数没有可靠转义方式,暂不处理(vbs 主路径不受影响)
|
|
185
196
|
` $l.Arguments = '/c start "ZCodePro-Setup" /min "${psQuote(cmd)}"'`,
|
|
186
|
-
|
|
197
|
+
// 降级分支不建 vbsDir(目录可能不存在,快捷方式会报“起始位置无效”):
|
|
198
|
+
// 起始位置改用命令所在目录
|
|
199
|
+
` $l.WorkingDirectory = '${psQuote(cmdWorkDir(cmd) || process.env.USERPROFILE || process.env.HOME || paths.vbsDir)}'`,
|
|
187
200
|
" $l.Description = 'ZCode 桌面版增强启动器(壁纸引擎、皮肤主题等,不修改客户端文件)'",
|
|
188
201
|
iconLine,
|
|
189
202
|
' $l.WindowStyle = 7',
|
|
@@ -215,7 +228,7 @@ export function windowsShortcutPlan(cmd, desktop = false, wshOk = true, menuLnk
|
|
|
215
228
|
// PowerShell 的 GetFolderPath,正确跟随 OneDrive 重定向)。OneDrive 桌面重定向时
|
|
216
229
|
// 桌面在 %OneDrive%\Desktop,未重定向时在用户主目录
|
|
217
230
|
export function desktopLnkPathApprox() {
|
|
218
|
-
for (const od of [process.env.OneDrive, process.env.OneDriveConsumer]) {
|
|
231
|
+
for (const od of [process.env.OneDrive, process.env.OneDriveConsumer, process.env.OneDriveCommercial]) {
|
|
219
232
|
if (od && existsSync(join(od, 'Desktop'))) return join(od, 'Desktop', 'ZCode Pro.lnk');
|
|
220
233
|
}
|
|
221
234
|
return join(homedir(), 'Desktop', 'ZCode Pro.lnk');
|
|
@@ -325,7 +338,10 @@ const shortcutItem = {
|
|
|
325
338
|
// 早期版本写过 0644 的条目:即使内容无需重写也补上执行位(原因见 writeDesktopEntry)
|
|
326
339
|
chmodSync(target, 0o755);
|
|
327
340
|
const exec = (cur.match(/^Exec=(.+)$/m) || [])[1] || '';
|
|
328
|
-
|
|
341
|
+
// 去掉引号后全等比较:子串判断会把指向旧命令(如 zcode-pro-old)的条目
|
|
342
|
+
// 误当成已指向当前命令而跳过更新
|
|
343
|
+
const execCmd = exec.trim().replace(/^"(.*)"$/, '$1');
|
|
344
|
+
if (execCmd === cmd) {
|
|
329
345
|
parts.push('app-menu entry already exists and points to the current command, nothing to do');
|
|
330
346
|
} else {
|
|
331
347
|
writeDesktopEntry(target, cmd);
|
|
@@ -394,6 +410,10 @@ const shortcutItem = {
|
|
|
394
410
|
if (existsSync(app) && !existsSync(marker)) {
|
|
395
411
|
return { skipped: `${app} exists and was not created by setup, not overwritten` };
|
|
396
412
|
}
|
|
413
|
+
// 归属标记先于内容写入:中途失败(复制图标、写启动器等)留下的残包仍带标记,
|
|
414
|
+
// 下次重装直接覆盖重建;反过来(标记最后写)会留下装不进也卸不掉的半成品
|
|
415
|
+
mkdirSync(contents, { recursive: true });
|
|
416
|
+
writeFileSync(marker, '');
|
|
397
417
|
let iconCopied = false;
|
|
398
418
|
for (const src of [join('/', 'Applications', 'ZCode.app', 'Contents', 'Resources', 'app.icns'),
|
|
399
419
|
join(homedir(), 'Applications', 'ZCode.app', 'Contents', 'Resources', 'app.icns')]) {
|
|
@@ -407,20 +427,28 @@ const shortcutItem = {
|
|
|
407
427
|
}
|
|
408
428
|
mkdirSync(join(contents, 'MacOS'), { recursive: true });
|
|
409
429
|
const launcher = join(contents, 'MacOS', 'zcode-pro');
|
|
410
|
-
|
|
430
|
+
// 路径里的 " ` $ \ 按 shell 双引号规则转义:不转义时路径含这些字符会破坏
|
|
431
|
+
// 生成的启动器甚至被当命令替换求值
|
|
432
|
+
writeFileSync(launcher, `#!/bin/sh\nexec "${String(cmd).replace(/([\\"`$])/g, '\\$1')}" "$@"\n`);
|
|
411
433
|
chmodSync(launcher, 0o755);
|
|
412
434
|
writeFileSync(join(contents, 'Info.plist'), plistContent(iconCopied));
|
|
413
|
-
writeFileSync(marker, '');
|
|
414
435
|
let detail = `created ${app} (launcher -> ${cmd}${iconCopied ? ', icon copied' : ''})`;
|
|
415
436
|
if (opts.desktop) {
|
|
416
437
|
const link = macDesktopLink();
|
|
417
|
-
|
|
438
|
+
// 断链符号链接 existsSync 也返回假,会被误判成不存在,symlinkSync 反而报
|
|
439
|
+
// EEXIST 被空 catch 吞掉、桌面入口静默建不出:存在性改用 lstat 判断
|
|
440
|
+
let linkExists = true;
|
|
441
|
+
try { lstatSync(link); } catch { linkExists = false; }
|
|
442
|
+
if (linkExists) {
|
|
418
443
|
detail += '; desktop entry with the same name exists, not overwritten';
|
|
419
444
|
} else {
|
|
420
445
|
try {
|
|
421
446
|
symlinkSync(app, link);
|
|
422
447
|
detail += `; desktop ${link}`;
|
|
423
|
-
} catch {
|
|
448
|
+
} catch (err) {
|
|
449
|
+
// EEXIST(判断与创建之间被抢先建出)按“已存在不覆盖”汇报;其余失败只省略桌面入口
|
|
450
|
+
if (err?.code === 'EEXIST') detail += '; desktop entry with the same name exists, not overwritten';
|
|
451
|
+
}
|
|
424
452
|
}
|
|
425
453
|
}
|
|
426
454
|
return { detail };
|
|
@@ -454,7 +482,10 @@ const shortcutItem = {
|
|
|
454
482
|
const paths = windowsPaths();
|
|
455
483
|
const hadVbs = existsSync(paths.vbsPath);
|
|
456
484
|
const hadLnk = existsSync(paths.lnkPath);
|
|
457
|
-
|
|
485
|
+
// 桌面 .lnk 可能是唯一残留(开始菜单与 vbs 已被清掉):提前返回前一并判断,
|
|
486
|
+
// 否则桌面快捷方式漏删
|
|
487
|
+
const hadDesk = existsSync(desktopLnkPathApprox());
|
|
488
|
+
if (!hadVbs && !hadLnk && !hadDesk) return { skipped: 'no setup-created shortcuts found' };
|
|
458
489
|
// .lnk 可能已被 install.ps1 等重建并指向它自己:只有 Arguments 带本功能归属
|
|
459
490
|
// 标记才删;校验失败也保留 .lnk(宁可漏删不误删)
|
|
460
491
|
let lnkRemoved = false;
|
|
@@ -473,7 +504,7 @@ const shortcutItem = {
|
|
|
473
504
|
'}',
|
|
474
505
|
].join('\r\n'));
|
|
475
506
|
verified = true;
|
|
476
|
-
lnkRemoved = !existsSync(paths.lnkPath);
|
|
507
|
+
lnkRemoved = !existsSync(paths.lnkPath) && !existsSync(desktopLnkPathApprox());
|
|
477
508
|
} catch { /* 校验失败则不动 .lnk */ }
|
|
478
509
|
let vbsCleaned = !hadVbs;
|
|
479
510
|
if (hadVbs) {
|
|
@@ -493,7 +524,7 @@ const shortcutItem = {
|
|
|
493
524
|
}
|
|
494
525
|
}
|
|
495
526
|
const parts = [];
|
|
496
|
-
if (hadLnk) {
|
|
527
|
+
if (hadLnk || hadDesk) {
|
|
497
528
|
parts.push(lnkRemoved ? 'start-menu/desktop shortcut' : verified ? 'shortcut not created by setup, kept' : 'shortcut ownership check failed, .lnk kept');
|
|
498
529
|
}
|
|
499
530
|
if (hadVbs) parts.push(vbsCleaned ? 'generated launcher script' : 'launcher script (delete failed)');
|
|
@@ -506,9 +537,17 @@ const shortcutItem = {
|
|
|
506
537
|
if (!existsSync(marker)) return { skipped: 'no setup-created app bundle found' };
|
|
507
538
|
// setup --desktop 建的桌面入口一并清理(只删指向本应用包的链接)
|
|
508
539
|
const link = macDesktopLink();
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
} catch { /*
|
|
540
|
+
// 断链符号链接 existsSync 返回假、realpath 抛错,都会漏删:存在性用 lstat 判断
|
|
541
|
+
let linkInfo = null;
|
|
542
|
+
try { linkInfo = lstatSync(link); } catch { /* 无桌面入口 */ }
|
|
543
|
+
if (linkInfo) {
|
|
544
|
+
// 目标比较先用链接记录的文本(本功能建链时写的就是应用包路径,断链也读得出),
|
|
545
|
+
// 再退回解析后的真实路径(目标经其他符号链接中转的情形)
|
|
546
|
+
let ours = false;
|
|
547
|
+
try { ours = linkInfo.isSymbolicLink() && readlinkSync(link) === app; } catch { /* 读不出目标 */ }
|
|
548
|
+
if (!ours) { try { ours = realpathSync(link) === realpathSync(app); } catch { /* 断链且目标文本不同 */ } }
|
|
549
|
+
if (ours) rmSync(link);
|
|
550
|
+
}
|
|
512
551
|
rmSync(app, { recursive: true, force: true });
|
|
513
552
|
return { detail: `removed ${app}` };
|
|
514
553
|
},
|
package/src/host/skill-stats.mjs
CHANGED
|
@@ -37,7 +37,12 @@ function parseFrontmatter(text) {
|
|
|
37
37
|
function loadSkill(dir) {
|
|
38
38
|
const path = join(dir, 'SKILL.md');
|
|
39
39
|
if (!existsSync(path)) return null;
|
|
40
|
-
|
|
40
|
+
let fm;
|
|
41
|
+
try {
|
|
42
|
+
fm = parseFrontmatter(readFileSync(path, 'utf8'));
|
|
43
|
+
} catch {
|
|
44
|
+
return null; // 断链、无权限等坏条目跳过,别砸掉整个统计
|
|
45
|
+
}
|
|
41
46
|
let name;
|
|
42
47
|
let description = '';
|
|
43
48
|
let whenToUse = '';
|
package/src/host/taskIndex.mjs
CHANGED
|
@@ -5,8 +5,9 @@
|
|
|
5
5
|
// - 仅 workspace_key:task_group_workspace_bootstraps(主键)、automation_runs;
|
|
6
6
|
// - workspace_key + workspace_path + workspace_identity:
|
|
7
7
|
// tasks(key 为联合主键)、automations、off_peak_tasks、task_group_members(key 为联合主键);
|
|
8
|
-
// - 另有 tasks.meta_json 内嵌 "workspacePath":"<路径>"
|
|
8
|
+
// - 另有 tasks.meta_json 内嵌 "workspacePath":"<路径>"(冒号后可能带空格,两种写法都替换);
|
|
9
9
|
// task_group_view_node_orders.node_key(node_type='task')内嵌 JSON 数组 ["<workspace_key>","<task_id>"];
|
|
10
|
+
// - projects/project_roots.root_path(3.16.1+ 虚拟项目)按精确等值替换;
|
|
10
11
|
// - workspace_identity 格式未详,按“引号界定的精确串”替换(哈希值不会含路径,LIKE 只做免更新过滤);
|
|
11
12
|
// - tasks.searchable_text 是会话内容文本(可能提及任何路径),不属于路径引用,不动。
|
|
12
13
|
//
|
|
@@ -76,6 +77,7 @@ export async function probeTaskIndexWritable(dataRoot) {
|
|
|
76
77
|
}
|
|
77
78
|
|
|
78
79
|
// 把索引中所有引用 oldPath 的 workspace 键/字段重映射为 newPath,单事务。
|
|
80
|
+
// 旧版库缺表/缺列时跳过对应语句(其余表照常改),不让一张缺表把整个事务回滚。
|
|
79
81
|
// 返回 { changed }(SQLite changes() 计数之和,CLI 驱动返回 null)。
|
|
80
82
|
export async function remapTaskIndexPaths(dataRoot, oldPath, newPath) {
|
|
81
83
|
const dbFile = taskIndexPath(dataRoot);
|
|
@@ -95,9 +97,17 @@ export async function remapTaskIndexPaths(dataRoot, oldPath, newPath) {
|
|
|
95
97
|
const KEY_TABLES = ['tasks', 'task_group_members', 'task_group_workspace_bootstraps', 'automations', 'automation_runs', 'off_peak_tasks'];
|
|
96
98
|
// 带 workspace_path / workspace_identity 的表
|
|
97
99
|
const PATH_TABLES = ['tasks', 'automations', 'off_peak_tasks', 'task_group_members'];
|
|
100
|
+
// root_path 所在的表(3.16.1+ 虚拟项目,listVirtualProjects 在读);老库没有照跳
|
|
101
|
+
const ROOT_TABLES = ['projects', 'project_roots'];
|
|
98
102
|
// 引号界定的 JSON 字符串替换:"/a/b/old" 不会命中 "/a/b/old2"
|
|
99
103
|
const quoted = (p) => JSON.stringify(p);
|
|
100
|
-
|
|
104
|
+
// meta_json 里 "workspacePath" 的两种写法(紧凑 / 冒号后带空格)各替换一次
|
|
105
|
+
const metaTokenPairs = (oldKey, newKey) => [
|
|
106
|
+
['"workspacePath":' + JSON.stringify(oldKey), '"workspacePath":' + JSON.stringify(newKey)],
|
|
107
|
+
['"workspacePath": ' + JSON.stringify(oldKey), '"workspacePath": ' + JSON.stringify(newKey)],
|
|
108
|
+
];
|
|
109
|
+
// 重映射涉及的全部表名:写入前查 sqlite_master 与列名,旧版库缺表/缺列时跳过对应语句
|
|
110
|
+
const ALL_TABLES = [...new Set([...KEY_TABLES, ...PATH_TABLES, ...ROOT_TABLES, 'tasks', 'task_group_view_node_orders'])];
|
|
101
111
|
|
|
102
112
|
if (driver.kind === 'node') return remapWithNode(driver.DatabaseSync, dbFile);
|
|
103
113
|
return remapWithCli(dbFile);
|
|
@@ -109,21 +119,39 @@ export async function remapTaskIndexPaths(dataRoot, oldPath, newPath) {
|
|
|
109
119
|
db.exec(`PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS}`);
|
|
110
120
|
db.exec('BEGIN IMMEDIATE');
|
|
111
121
|
try {
|
|
112
|
-
|
|
113
|
-
|
|
122
|
+
// 先查在场的表和列:旧版库缺表/缺列(缺新表)时跳过对应语句,其余表照常改,
|
|
123
|
+
// 不再让一张缺表把整个事务回滚掉
|
|
124
|
+
const present = new Map();
|
|
125
|
+
const inDb = new Set(db.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((r) => String(r.name)));
|
|
126
|
+
for (const t of ALL_TABLES) {
|
|
127
|
+
if (inDb.has(t)) present.set(t, new Set(db.prepare(`PRAGMA table_info(${t})`).all().map((c) => String(c.name))));
|
|
128
|
+
}
|
|
129
|
+
const run = (table, column, sql, params) => {
|
|
130
|
+
if (!present.get(table)?.has(column)) return;
|
|
131
|
+
try {
|
|
132
|
+
changed += db.prepare(sql).run(...params).changes;
|
|
133
|
+
} catch (err) {
|
|
134
|
+
// 预检后仍撞上缺表/缺列(预检到写入之间被别的进程改库):跳过这条,其余继续
|
|
135
|
+
if (!/no such (table|column)/i.test(String(err?.message || err))) throw err;
|
|
136
|
+
}
|
|
114
137
|
};
|
|
115
138
|
for (const [oldKey, newKey] of variants) {
|
|
116
139
|
for (const table of KEY_TABLES) {
|
|
117
|
-
run(`UPDATE ${table} SET workspace_key = ? WHERE workspace_key = ?`, [newKey, oldKey]);
|
|
140
|
+
run(table, 'workspace_key', `UPDATE ${table} SET workspace_key = ? WHERE workspace_key = ?`, [newKey, oldKey]);
|
|
118
141
|
}
|
|
119
142
|
for (const table of PATH_TABLES) {
|
|
120
|
-
run(`UPDATE ${table} SET workspace_path = ? WHERE workspace_path = ?`, [newKey, oldKey]);
|
|
121
|
-
run(`UPDATE ${table} SET workspace_identity = replace(workspace_identity, ?, ?)
|
|
143
|
+
run(table, 'workspace_path', `UPDATE ${table} SET workspace_path = ? WHERE workspace_path = ?`, [newKey, oldKey]);
|
|
144
|
+
run(table, 'workspace_identity', `UPDATE ${table} SET workspace_identity = replace(workspace_identity, ?, ?)
|
|
122
145
|
WHERE instr(workspace_identity, ?) > 0`, [quoted(oldKey), quoted(newKey), oldKey]);
|
|
123
146
|
}
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
147
|
+
for (const table of ROOT_TABLES) {
|
|
148
|
+
run(table, 'root_path', `UPDATE ${table} SET root_path = ? WHERE root_path = ?`, [newKey, oldKey]);
|
|
149
|
+
}
|
|
150
|
+
for (const [oldTok, newTok] of metaTokenPairs(oldKey, newKey)) {
|
|
151
|
+
run('tasks', 'meta_json', `UPDATE tasks SET meta_json = replace(meta_json, ?, ?)
|
|
152
|
+
WHERE instr(meta_json, ?) > 0`, [oldTok, newTok, oldKey]);
|
|
153
|
+
}
|
|
154
|
+
run('task_group_view_node_orders', 'node_key', `UPDATE task_group_view_node_orders SET node_key = replace(node_key, ?, ?)
|
|
127
155
|
WHERE instr(node_key, ?) > 0`, [quoted(oldKey), quoted(newKey), oldKey]);
|
|
128
156
|
}
|
|
129
157
|
db.exec('COMMIT');
|
|
@@ -137,19 +165,36 @@ export async function remapTaskIndexPaths(dataRoot, oldPath, newPath) {
|
|
|
137
165
|
|
|
138
166
|
function remapWithCli(file) {
|
|
139
167
|
const esc = (v) => "'" + String(v).replace(/'/g, "''") + "'";
|
|
168
|
+
// sqlite3 CLI 带 -bail 执行:一条报错就停,缺表/缺列只能靠预检过滤掉
|
|
169
|
+
// (与 node 驱动同一套在场表/列判定),预检漏掉的照旧报错回滚
|
|
170
|
+
const present = new Map();
|
|
171
|
+
const inDb = new Set(runCli(file, "SELECT name FROM sqlite_master WHERE type = 'table';").stdout.split(/\r?\n/).filter(Boolean));
|
|
172
|
+
for (const t of ALL_TABLES) {
|
|
173
|
+
if (!inDb.has(t)) continue;
|
|
174
|
+
const cols = runCli(file, `PRAGMA table_info(${t});`).stdout.split(/\r?\n/).filter(Boolean).map((l) => l.split('|')[1]);
|
|
175
|
+
present.set(t, new Set(cols));
|
|
176
|
+
}
|
|
140
177
|
const stmts = [];
|
|
178
|
+
const add = (table, column, sql) => {
|
|
179
|
+
if (present.get(table)?.has(column)) stmts.push(sql);
|
|
180
|
+
};
|
|
141
181
|
for (const [oldKey, newKey] of variants) {
|
|
142
182
|
for (const table of KEY_TABLES) {
|
|
143
|
-
|
|
183
|
+
add(table, 'workspace_key', `UPDATE ${table} SET workspace_key = ${esc(newKey)} WHERE workspace_key = ${esc(oldKey)};`);
|
|
144
184
|
}
|
|
145
185
|
for (const table of PATH_TABLES) {
|
|
146
|
-
|
|
147
|
-
|
|
186
|
+
add(table, 'workspace_path', `UPDATE ${table} SET workspace_path = ${esc(newKey)} WHERE workspace_path = ${esc(oldKey)};`);
|
|
187
|
+
add(table, 'workspace_identity', `UPDATE ${table} SET workspace_identity = replace(workspace_identity, ${esc(quoted(oldKey))}, ${esc(quoted(newKey))})
|
|
148
188
|
WHERE instr(workspace_identity, ${esc(oldKey)}) > 0;`);
|
|
149
189
|
}
|
|
150
|
-
|
|
190
|
+
for (const table of ROOT_TABLES) {
|
|
191
|
+
add(table, 'root_path', `UPDATE ${table} SET root_path = ${esc(newKey)} WHERE root_path = ${esc(oldKey)};`);
|
|
192
|
+
}
|
|
193
|
+
for (const [oldTok, newTok] of metaTokenPairs(oldKey, newKey)) {
|
|
194
|
+
add('tasks', 'meta_json', `UPDATE tasks SET meta_json = replace(meta_json, ${esc(oldTok)}, ${esc(newTok)})
|
|
151
195
|
WHERE instr(meta_json, ${esc(oldKey)}) > 0;`);
|
|
152
|
-
|
|
196
|
+
}
|
|
197
|
+
add('task_group_view_node_orders', 'node_key', `UPDATE task_group_view_node_orders SET node_key = replace(node_key, ${esc(quoted(oldKey))}, ${esc(quoted(newKey))})
|
|
153
198
|
WHERE instr(node_key, ${esc(oldKey)}) > 0;`);
|
|
154
199
|
}
|
|
155
200
|
try {
|
|
@@ -201,14 +246,14 @@ export async function listVirtualProjects(dataRoot) {
|
|
|
201
246
|
} else {
|
|
202
247
|
const act = runCli(dbFile,
|
|
203
248
|
`SELECT p.project_id || ${TAB} || p.name || ${TAB} || r.root_path || ${TAB} || r.is_primary || ${TAB} || p.name_overridden${SQL_ACTIVE.slice(SQL_ACTIVE.indexOf(' FROM'))};`).stdout;
|
|
204
|
-
activeRows = act.split(
|
|
249
|
+
activeRows = act.split(/\r?\n/).filter(Boolean).map((l) => {
|
|
205
250
|
const [pid, name, path, primary, overridden] = l.split('\t');
|
|
206
251
|
return { pid, name, path, primary, name_overridden: overridden };
|
|
207
252
|
});
|
|
208
253
|
const del = runCli(dbFile,
|
|
209
254
|
`SELECT r.root_path FROM projects p JOIN project_roots r ON r.project_id = p.project_id
|
|
210
255
|
WHERE p.deleted = 1 AND (p.host_id = 'local' OR p.host_id IS NULL);`).stdout;
|
|
211
|
-
deletedRows = del.split(
|
|
256
|
+
deletedRows = del.split(/\r?\n/).filter(Boolean).map((p) => ({ path: p }));
|
|
212
257
|
}
|
|
213
258
|
const byId = new Map();
|
|
214
259
|
for (const row of activeRows) {
|
|
@@ -228,7 +273,7 @@ export async function listVirtualProjects(dataRoot) {
|
|
|
228
273
|
const db = new driver.DatabaseSync(dbFile, { readOnly: true });
|
|
229
274
|
try { allPaths = db.prepare('SELECT DISTINCT workspace_path FROM tasks').all().map((r) => String(r.workspace_path || '')); } finally { db.close(); }
|
|
230
275
|
} else {
|
|
231
|
-
allPaths = runCli(dbFile, 'SELECT DISTINCT workspace_path FROM tasks;').stdout.split(
|
|
276
|
+
allPaths = runCli(dbFile, 'SELECT DISTINCT workspace_path FROM tasks;').stdout.split(/\r?\n/).filter(Boolean);
|
|
232
277
|
}
|
|
233
278
|
} catch { /* 读不到就不带,调用方只有项目路径 */ }
|
|
234
279
|
return {
|
|
@@ -272,7 +317,6 @@ export async function listTaskStatuses(dataRoot, ids) {
|
|
|
272
317
|
}
|
|
273
318
|
}
|
|
274
319
|
|
|
275
|
-
// 已重命名会话的标题表:task_id → title(title_overridden = 1 且未删除)。
|
|
276
320
|
// 状态栏统计用:任务总数(未删除的会话行)
|
|
277
321
|
export async function countTasks(dataRoot) {
|
|
278
322
|
const dbFile = taskIndexPath(dataRoot);
|
|
@@ -301,7 +345,7 @@ export async function listOverriddenTitles(dataRoot) {
|
|
|
301
345
|
const titles = {};
|
|
302
346
|
try {
|
|
303
347
|
if (driver.kind === 'node') {
|
|
304
|
-
const db = new driver.DatabaseSync(dbFile);
|
|
348
|
+
const db = new driver.DatabaseSync(dbFile, { readOnly: true });
|
|
305
349
|
try {
|
|
306
350
|
db.exec(`PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS}`);
|
|
307
351
|
for (const row of db.prepare(
|
|
@@ -350,7 +394,8 @@ export async function isTaskTitleOverridden(dataRoot, sessId) {
|
|
|
350
394
|
// 之后官方自动标题不会再覆盖这条记录。仅在会话未删除、且从未被手动重命名过
|
|
351
395
|
// (title_overridden = 0)时写入——手动重命名永远优先。返回 { written, title };
|
|
352
396
|
// written = false 表示没写(已重命名或会话不在索引中)。库被占用时抛 index-busy。
|
|
353
|
-
|
|
397
|
+
// force:用户显式“自动重命名”已重命名过的会话也照写(改名意图明确,不守旧行)。
|
|
398
|
+
export async function setTaskTitleIfNotOverridden(dataRoot, sessId, title, { force = false } = {}) {
|
|
354
399
|
const dbFile = taskIndexPath(dataRoot);
|
|
355
400
|
if (!existsSync(dbFile)) return { written: false, title };
|
|
356
401
|
const driver = await loadDriver();
|
|
@@ -367,7 +412,8 @@ export async function setTaskTitleIfNotOverridden(dataRoot, sessId, title) {
|
|
|
367
412
|
db.exec('BEGIN IMMEDIATE');
|
|
368
413
|
try {
|
|
369
414
|
const r = db.prepare(
|
|
370
|
-
'UPDATE tasks SET title = ?, title_overridden = 1 WHERE task_id = ? AND deleted = 0
|
|
415
|
+
'UPDATE tasks SET title = ?, title_overridden = 1 WHERE task_id = ? AND deleted = 0'
|
|
416
|
+
+ (force ? '' : ' AND title_overridden = 0')
|
|
371
417
|
).run(title, sessId);
|
|
372
418
|
db.exec('COMMIT');
|
|
373
419
|
return { written: r.changes > 0, title };
|
|
@@ -381,7 +427,7 @@ export async function setTaskTitleIfNotOverridden(dataRoot, sessId, title) {
|
|
|
381
427
|
const r = runCli(dbFile,
|
|
382
428
|
'BEGIN IMMEDIATE;\n'
|
|
383
429
|
+ `UPDATE tasks SET title = ${esc(title)}, title_overridden = 1`
|
|
384
|
-
+ ` WHERE task_id = ${esc(sessId)} AND deleted = 0 AND title_overridden = 0;\n`
|
|
430
|
+
+ ` WHERE task_id = ${esc(sessId)} AND deleted = 0${force ? '' : ' AND title_overridden = 0'};\n`
|
|
385
431
|
+ 'SELECT changes();\nCOMMIT;');
|
|
386
432
|
return { written: Number(r.stdout.trim()) > 0, title };
|
|
387
433
|
} catch (err) {
|
|
@@ -443,7 +489,7 @@ export async function getTaskProviderModel(dataRoot, sessId) {
|
|
|
443
489
|
: 'WHERE deleted = 0 AND model != \'\' ORDER BY updated_at DESC LIMIT 1';
|
|
444
490
|
try {
|
|
445
491
|
if (driver.kind === 'node') {
|
|
446
|
-
const db = new driver.DatabaseSync(dbFile);
|
|
492
|
+
const db = new driver.DatabaseSync(dbFile, { readOnly: true });
|
|
447
493
|
try {
|
|
448
494
|
db.exec(`PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS}`);
|
|
449
495
|
row = db.prepare(`SELECT provider, model FROM tasks ${where}`).get() || null;
|
|
@@ -475,7 +521,7 @@ export async function listTaskWorkspaceMap(dataRoot) {
|
|
|
475
521
|
try {
|
|
476
522
|
let rows = [];
|
|
477
523
|
if (driver.kind === 'node') {
|
|
478
|
-
const db = new driver.DatabaseSync(dbFile);
|
|
524
|
+
const db = new driver.DatabaseSync(dbFile, { readOnly: true });
|
|
479
525
|
try {
|
|
480
526
|
db.exec(`PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS}`);
|
|
481
527
|
rows = db.prepare('SELECT task_id, workspace_path, workspace_key FROM tasks').all();
|
|
@@ -499,7 +545,7 @@ function runCli(dbFile, script) {
|
|
|
499
545
|
windowsHide: true,
|
|
500
546
|
input: `.timeout ${BUSY_TIMEOUT_MS}\n` + script,
|
|
501
547
|
encoding: 'utf8',
|
|
502
|
-
maxBuffer:
|
|
548
|
+
maxBuffer: 16 << 20, // 大会话的 JSON 聚合输出轻松过 1MB,与 helper 的上限对齐
|
|
503
549
|
});
|
|
504
550
|
if (r.error) throw r.error;
|
|
505
551
|
if (r.status !== 0) throw new Error('sqlite3 CLI 执行失败: ' + (r.stderr || r.stdout || ('exit ' + r.status)));
|
|
@@ -525,51 +571,78 @@ export async function reconcileCustomTitles(dataRoot, writtenMap) {
|
|
|
525
571
|
const idxFile = taskIndexPath(dataRoot);
|
|
526
572
|
if (!existsSync(cliFile) || !existsSync(idxFile)) return repaired;
|
|
527
573
|
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
return db.prepare("SELECT title, title_source FROM session WHERE id = ?").get(sessId) || null;
|
|
533
|
-
} finally { db.close(); }
|
|
534
|
-
}
|
|
535
|
-
const r = runCli(cliFile, `SELECT coalesce(json_object('title', title, 'title_source', title_source), 'null') FROM session WHERE id = ${esc(sessId)};`);
|
|
536
|
-
const parsed = JSON.parse(r.stdout.trim() || 'null');
|
|
537
|
-
return parsed && typeof parsed === 'object' ? parsed : null;
|
|
538
|
-
};
|
|
574
|
+
// 会话 id 有 sess_ 与 session_ 两种前缀(新版应用为 session_),两种都认
|
|
575
|
+
const entries = Object.entries(writtenMap)
|
|
576
|
+
.filter(([sessId, rec]) => /^(?:sess|session)_[A-Za-z0-9._-]+$/.test(sessId) && rec && typeof rec.title === 'string');
|
|
577
|
+
if (!entries.length) return repaired;
|
|
539
578
|
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
let
|
|
544
|
-
|
|
545
|
-
// CLI 已不是我们所写的 custom 标题:别人改过(手动改名/官方),不碰
|
|
546
|
-
if (!cli || cli.title_source !== 'custom' || cli.title !== rec.title) continue;
|
|
579
|
+
// 批量处理:一次读 CLI 标题、一次事务写索引。逐条开关库(旧实现)在
|
|
580
|
+
// customWritten 多时(上限 500 条)是上千次同步开库/spawnSync,会卡住事件循环
|
|
581
|
+
if (driver.kind === 'node') {
|
|
582
|
+
let cliDb = null;
|
|
583
|
+
let idxDb = null;
|
|
547
584
|
try {
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
585
|
+
cliDb = new driver.DatabaseSync(cliFile, { readOnly: true });
|
|
586
|
+
const sel = cliDb.prepare('SELECT title, title_source FROM session WHERE id = ?');
|
|
587
|
+
const todo = [];
|
|
588
|
+
for (const [sessId, rec] of entries) {
|
|
589
|
+
let cli;
|
|
590
|
+
try { cli = sel.get(sessId) || null; } catch { continue; }
|
|
591
|
+
// CLI 已不是我们所写的 custom 标题:别人改过(手动改名/官方),不碰
|
|
592
|
+
if (!cli || cli.title_source !== 'custom' || cli.title !== rec.title) continue;
|
|
593
|
+
todo.push([sessId, rec.title]);
|
|
594
|
+
}
|
|
595
|
+
if (!todo.length) return repaired;
|
|
596
|
+
const done = [];
|
|
597
|
+
idxDb = new driver.DatabaseSync(idxFile);
|
|
598
|
+
idxDb.exec(`PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS}`);
|
|
599
|
+
idxDb.exec('BEGIN IMMEDIATE');
|
|
600
|
+
try {
|
|
601
|
+
const upd = idxDb.prepare(
|
|
602
|
+
'UPDATE tasks SET title = ? WHERE task_id = ? AND deleted = 0 AND title_overridden = 1 AND title != ?'
|
|
603
|
+
);
|
|
604
|
+
for (const [sessId, title] of todo) {
|
|
605
|
+
if (upd.run(title, sessId, title).changes > 0) done.push(sessId);
|
|
606
|
+
}
|
|
607
|
+
idxDb.exec('COMMIT');
|
|
608
|
+
} catch (err) {
|
|
609
|
+
try { idxDb.exec('ROLLBACK'); } catch { /* 已回滚 */ }
|
|
610
|
+
throw err;
|
|
570
611
|
}
|
|
612
|
+
repaired.push(...done); // 提交成功才记账,回滚时不虚报
|
|
571
613
|
} catch { /* 占用等:下次再校正 */ }
|
|
614
|
+
finally {
|
|
615
|
+
try { if (cliDb) cliDb.close(); } catch { /* ignore */ }
|
|
616
|
+
try { if (idxDb) idxDb.close(); } catch { /* ignore */ }
|
|
617
|
+
}
|
|
618
|
+
return repaired;
|
|
572
619
|
}
|
|
620
|
+
|
|
621
|
+
// sqlite3 CLI 驱动(缺 node:sqlite 的环境):同样批量——一次读全部标题,
|
|
622
|
+
// 一次事务写全部更新(每次 UPDATE 后 SELECT changes() 输出一行计数)
|
|
623
|
+
try {
|
|
624
|
+
const ids = entries.map(([sessId]) => esc(sessId)).join(', ');
|
|
625
|
+
const r = runCli(cliFile,
|
|
626
|
+
`SELECT coalesce(json_group_array(json_object('id', id, 'title', title, 'title_source', title_source)), '[]') FROM session WHERE id IN (${ids});`);
|
|
627
|
+
const rows = JSON.parse(r.stdout.trim() || '[]');
|
|
628
|
+
const byId = new Map(rows.map((row) => [String(row.id), row]));
|
|
629
|
+
const todo = [];
|
|
630
|
+
for (const [sessId, rec] of entries) {
|
|
631
|
+
const cli = byId.get(sessId);
|
|
632
|
+
if (!cli || cli.title_source !== 'custom' || cli.title !== rec.title) continue;
|
|
633
|
+
todo.push([sessId, rec.title]);
|
|
634
|
+
}
|
|
635
|
+
if (!todo.length) return repaired;
|
|
636
|
+
const sql = ['BEGIN IMMEDIATE;'];
|
|
637
|
+
for (const [sessId, title] of todo) {
|
|
638
|
+
sql.push(`UPDATE tasks SET title = ${esc(title)} WHERE task_id = ${esc(sessId)} AND deleted = 0 AND title_overridden = 1 AND title != ${esc(title)};`);
|
|
639
|
+
sql.push('SELECT changes();');
|
|
640
|
+
}
|
|
641
|
+
sql.push('COMMIT;');
|
|
642
|
+
const w = runCli(idxFile, sql.join('\n'));
|
|
643
|
+
const counts = w.stdout.trim().split(/\r?\n/).filter((s) => s !== '').map(Number);
|
|
644
|
+
todo.forEach(([sessId], i) => { if (counts[i] > 0) repaired.push(sessId); });
|
|
645
|
+
} catch { /* 占用等:下次再校正 */ }
|
|
573
646
|
return repaired;
|
|
574
647
|
}
|
|
575
648
|
|
|
@@ -635,3 +708,62 @@ export async function setCustomSessionTitle(dataRoot, sessId, title) {
|
|
|
635
708
|
throw e;
|
|
636
709
|
}
|
|
637
710
|
}
|
|
711
|
+
|
|
712
|
+
// 手动自动重命名的素材:会话最近 N 轮问答(问/答文本,按时间先后)。一轮 =
|
|
713
|
+
// 一条用户消息 + 其后的助手回答文本;跳过 model-only 的注入消息(agent 列表
|
|
714
|
+
// 等)与没有文本的部分。超 1200 字(generateTitleWith 的素材上限)时从最旧
|
|
715
|
+
// 一轮丢起,保住最新内容。返回 '' = 没有可用问答。
|
|
716
|
+
export async function readRecentQa(dataRoot, sessId, rounds) {
|
|
717
|
+
const dbFile = join(dataRoot, 'cli', 'db', 'db.sqlite');
|
|
718
|
+
if (!existsSync(dbFile)) return '';
|
|
719
|
+
const driver = await loadDriver();
|
|
720
|
+
if (!driver) return '';
|
|
721
|
+
const n = Math.min(20, Math.max(1, Math.round(Number(rounds) || 3)));
|
|
722
|
+
const esc = (v) => "'" + String(v).replace(/'/g, "''") + "'";
|
|
723
|
+
// 单行 JSON 查询:node 驱动与 sqlite3 命令两种驱动共用同一条 SQL
|
|
724
|
+
const one = (sql) => {
|
|
725
|
+
if (driver.kind === 'node') {
|
|
726
|
+
const db = new driver.DatabaseSync(dbFile, { readOnly: true });
|
|
727
|
+
try { return String(db.prepare(sql).get()?.out || ''); } finally { db.close(); }
|
|
728
|
+
}
|
|
729
|
+
return runCli(dbFile, sql).stdout.trim();
|
|
730
|
+
};
|
|
731
|
+
const msgs = JSON.parse(one(
|
|
732
|
+
"SELECT coalesce(json_group_array(json_array(id, data)), '[]') AS out FROM"
|
|
733
|
+
+ ` (SELECT id, data FROM message WHERE session_id = ${esc(sessId)} ORDER BY sequence, time_created);`
|
|
734
|
+
) || '[]');
|
|
735
|
+
if (!Array.isArray(msgs) || !msgs.length) return '';
|
|
736
|
+
const parts = JSON.parse(one(
|
|
737
|
+
"SELECT coalesce(json_group_array(json_array(message_id, data)), '[]') AS out FROM"
|
|
738
|
+
+ ` (SELECT message_id, data FROM part WHERE session_id = ${esc(sessId)}`
|
|
739
|
+
+ " AND json_extract(data, '$.type') = 'text' ORDER BY message_id, sequence);"
|
|
740
|
+
) || '[]');
|
|
741
|
+
const textOf = new Map(); // message_id → 拼接后的文本
|
|
742
|
+
for (const row of (Array.isArray(parts) ? parts : [])) {
|
|
743
|
+
try {
|
|
744
|
+
const text = JSON.parse(row[1])?.text;
|
|
745
|
+
if (typeof text === 'string' && text.trim()) {
|
|
746
|
+
textOf.set(row[0], (textOf.get(row[0]) ? textOf.get(row[0]) + '\n' : '') + text.trim());
|
|
747
|
+
}
|
|
748
|
+
} catch { /* 坏行跳过 */ }
|
|
749
|
+
}
|
|
750
|
+
// 按 sequence 分轮:用户消息开新一轮,助手文本并入当前轮
|
|
751
|
+
const roundsList = [];
|
|
752
|
+
for (const [id, data] of msgs) {
|
|
753
|
+
let m;
|
|
754
|
+
try { m = JSON.parse(data); } catch { continue; }
|
|
755
|
+
const text = textOf.get(id);
|
|
756
|
+
if (!m || !text) continue;
|
|
757
|
+
if (m.role === 'user') {
|
|
758
|
+
if (m.metadata && m.metadata.visibility === 'model-only') continue;
|
|
759
|
+
roundsList.push({ q: text.slice(0, 600), a: '' });
|
|
760
|
+
} else if (m.role === 'assistant' && roundsList.length) {
|
|
761
|
+
const r = roundsList[roundsList.length - 1];
|
|
762
|
+
r.a = ((r.a ? r.a + '\n' : '') + text).slice(0, 600);
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
const sel = roundsList.slice(-n);
|
|
766
|
+
const fmt = (rs) => rs.map((r) => '问:' + r.q + (r.a ? '\n答:' + r.a : '')).join('\n');
|
|
767
|
+
while (sel.length > 1 && fmt(sel).length > 1200) sel.shift();
|
|
768
|
+
return fmt(sel);
|
|
769
|
+
}
|