zcode-pro 1.6.1 → 1.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +31 -21
- package/README.md +20 -12
- package/dist/inject.js +10431 -8836
- package/package.json +2 -1
- package/src/host/cdp.mjs +13 -3
- package/src/host/helper.mjs +1287 -488
- 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 +464 -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 +228 -103
- 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/plugin-updates.js +58 -0
- package/src/inject/features/sandbox-reclaim.js +17 -1
- package/src/inject/features/session-link.js +202 -0
- package/src/inject/features/session-switch.js +67 -30
- package/src/inject/features/settings-dialog.js +323 -124
- package/src/inject/features/status-bar.js +150 -28
- package/src/inject/features/subagent-icon.js +473 -0
- 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 +99 -47
- package/src/inject/features/ws-running.js +28 -13
- package/src/inject/index.js +7 -0
- package/src/inject/provider-fields.js +2 -2
- package/src/inject/ui.js +14 -0
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,272 @@ export async function listTaskStatuses(dataRoot, ids) {
|
|
|
272
317
|
}
|
|
273
318
|
}
|
|
274
319
|
|
|
275
|
-
//
|
|
320
|
+
// 批量查会话最近活动时间:id → time_updated(毫秒,查不到记 0)。子代理运行状态
|
|
321
|
+
// 的新鲜度校验用——应用的 running 记录崩溃/重启后不清理(实测残留数月的僵死记录),
|
|
322
|
+
// 子代理运行时消息不断写入会话库,长时间无动静的按僵死处理(subagent-icon.js)
|
|
323
|
+
export async function listSessionsActivity(dataRoot, ids) {
|
|
324
|
+
const out = {};
|
|
325
|
+
const wanted = [...new Set((ids || []).map(String).filter(Boolean))];
|
|
326
|
+
if (!wanted.length) return out;
|
|
327
|
+
const dbFile = join(dataRoot, 'cli', 'db', 'db.sqlite');
|
|
328
|
+
if (!existsSync(dbFile)) return out;
|
|
329
|
+
const driver = await loadDriver();
|
|
330
|
+
if (!driver) return out;
|
|
331
|
+
const esc = (v) => "'" + String(v).replace(/'/g, "''") + "'";
|
|
332
|
+
const inList = wanted.map((id) => esc(id)).join(', ');
|
|
333
|
+
try {
|
|
334
|
+
let rows;
|
|
335
|
+
if (driver.kind === 'node') {
|
|
336
|
+
const db = new driver.DatabaseSync(dbFile, { readOnly: true });
|
|
337
|
+
try { rows = db.prepare(`SELECT id, time_updated FROM session WHERE id IN (${inList})`).all(); } finally { db.close(); }
|
|
338
|
+
} else {
|
|
339
|
+
const agg = runCli(dbFile,
|
|
340
|
+
`SELECT coalesce(json_group_array(json_object('id', id, 'time_updated', time_updated)), '[]') FROM session WHERE id IN (${inList});`);
|
|
341
|
+
rows = JSON.parse(agg.stdout.trim() || '[]');
|
|
342
|
+
}
|
|
343
|
+
for (const r of rows) out[String(r.id)] = Number(r.time_updated) || 0;
|
|
344
|
+
return out;
|
|
345
|
+
} catch {
|
|
346
|
+
return out; // 读取失败按无活动处理(调用方视为僵死,不亮图标)
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// 指定会话的子代理会话及最近活动时间(含嵌套子代理,根归属到最初的那个会话):
|
|
351
|
+
// [{ id, root, at }]。子代理判活以这里写入会话库的活动时间为准——应用的运行记录两头都
|
|
352
|
+
// 不可靠:长跑子代理会被误记为失败/结束(实测 48 分钟、60 分钟的都在跑着时被
|
|
353
|
+
// 记 end),崩溃残留的又永远挂"运行中"(subagent-icon.js)
|
|
354
|
+
export async function listSubagentChildrenActivity(dataRoot, ids) {
|
|
355
|
+
const out = [];
|
|
356
|
+
const wanted = [...new Set((ids || []).map(String).filter(Boolean))];
|
|
357
|
+
if (!wanted.length) return out;
|
|
358
|
+
const dbFile = join(dataRoot, 'cli', 'db', 'db.sqlite');
|
|
359
|
+
if (!existsSync(dbFile)) return out;
|
|
360
|
+
const driver = await loadDriver();
|
|
361
|
+
if (!driver) return out;
|
|
362
|
+
const esc = (v) => "'" + String(v).replace(/'/g, "''") + "'";
|
|
363
|
+
const inList = wanted.map((id) => esc(id)).join(', ');
|
|
364
|
+
const sql = `WITH RECURSIVE fam(id, root) AS (
|
|
365
|
+
SELECT id, parent_id FROM session WHERE parent_id IN (${inList})
|
|
366
|
+
UNION
|
|
367
|
+
SELECT s.id, f.root FROM session s JOIN fam f ON s.parent_id = f.id
|
|
368
|
+
) SELECT fam.root AS root, s.id AS id, s.time_updated AS at
|
|
369
|
+
FROM session s JOIN fam ON s.id = fam.id
|
|
370
|
+
WHERE s.task_type = 'subagent_child'`;
|
|
371
|
+
try {
|
|
372
|
+
let rows;
|
|
373
|
+
if (driver.kind === 'node') {
|
|
374
|
+
const db = new driver.DatabaseSync(dbFile, { readOnly: true });
|
|
375
|
+
try { rows = db.prepare(sql).all(); } finally { db.close(); }
|
|
376
|
+
} else {
|
|
377
|
+
const agg = runCli(dbFile,
|
|
378
|
+
`SELECT coalesce(json_group_array(json_object('root', root, 'id', id, 'at', at)), '[]') FROM (${sql});`);
|
|
379
|
+
rows = JSON.parse(agg.stdout.trim() || '[]');
|
|
380
|
+
}
|
|
381
|
+
for (const r of rows) out.push({ id: String(r.id), root: String(r.root), at: Number(r.at) || 0 });
|
|
382
|
+
return out;
|
|
383
|
+
} catch {
|
|
384
|
+
return out;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
// 状态栏统计用:会话 → trace_id。父子会话(含子代理)共享同一 trace,
|
|
389
|
+
// 状态栏据此把子代理的模型调用算进父会话的输出速率
|
|
390
|
+
export async function listSessionsTrace(dataRoot, ids) {
|
|
391
|
+
const out = {};
|
|
392
|
+
const wanted = [...new Set((ids || []).map(String).filter(Boolean))];
|
|
393
|
+
if (!wanted.length) return out;
|
|
394
|
+
const dbFile = join(dataRoot, 'cli', 'db', 'db.sqlite');
|
|
395
|
+
if (!existsSync(dbFile)) return out;
|
|
396
|
+
const driver = await loadDriver();
|
|
397
|
+
if (!driver) return out;
|
|
398
|
+
const esc = (v) => "'" + String(v).replace(/'/g, "''") + "'";
|
|
399
|
+
const inList = wanted.map((id) => esc(id)).join(', ');
|
|
400
|
+
try {
|
|
401
|
+
let rows;
|
|
402
|
+
if (driver.kind === 'node') {
|
|
403
|
+
const db = new driver.DatabaseSync(dbFile, { readOnly: true });
|
|
404
|
+
try { rows = db.prepare(`SELECT id, trace_id FROM session WHERE id IN (${inList})`).all(); } finally { db.close(); }
|
|
405
|
+
} else {
|
|
406
|
+
const agg = runCli(dbFile,
|
|
407
|
+
`SELECT coalesce(json_group_array(json_object('id', id, 'trace_id', trace_id)), '[]') FROM session WHERE id IN (${inList});`);
|
|
408
|
+
rows = JSON.parse(agg.stdout.trim() || '[]');
|
|
409
|
+
}
|
|
410
|
+
for (const r of rows) out[String(r.id)] = String(r.trace_id || '');
|
|
411
|
+
return out;
|
|
412
|
+
} catch {
|
|
413
|
+
return out; // 读取失败按无 trace 处理(速率退化为只算本会话)
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
// 官方口径的每轮用量(Token 调试同源数据与公式):主轮请求逐条返回 + 会话汇总。
|
|
418
|
+
// TPS = 输出 ÷(耗时 − 首 token 时机)= 官方“Output tokens ÷ 首个输出 token 到
|
|
419
|
+
// 请求结束的秒数”;命中率 = 缓存读 ÷ 输入(输入含缓存读,官方同语义)。
|
|
420
|
+
// query_source 只算 main_turn:起名等辅助小调用不进主轮统计(官方同款口径)。
|
|
421
|
+
// treeTrace 给出时 summary.tps 按会话树(本会话+同 trace 子代理)的最近请求算
|
|
422
|
+
// 60 秒窗净生成速率(窗口锚定最近一笔完成,锚不随请求时刻移动)
|
|
423
|
+
export async function listSessionModelUsage(dataRoot, sessionId, treeTrace = '') {
|
|
424
|
+
const empty = { rounds: [], summary: { requests: 0, totalIn: 0, totalOut: 0, totalCacheRead: 0, hitRate: null, tps: null } };
|
|
425
|
+
const sid = String(sessionId || '');
|
|
426
|
+
if (!sid) return empty;
|
|
427
|
+
const dbFile = join(dataRoot, 'cli', 'db', 'db.sqlite');
|
|
428
|
+
if (!existsSync(dbFile)) return empty;
|
|
429
|
+
const driver = await loadDriver();
|
|
430
|
+
if (!driver) return empty;
|
|
431
|
+
const esc = (v) => "'" + String(v).replace(/'/g, "''") + "'";
|
|
432
|
+
const sql = `SELECT completed_at, duration_ms, time_to_first_token_ms, input_tokens, output_tokens,`
|
|
433
|
+
+ ` reasoning_tokens, cache_read_input_tokens, cache_creation_input_tokens, computed_total_tokens`
|
|
434
|
+
+ ` FROM model_usage WHERE session_id = ${esc(sid)} AND query_source = 'main_turn'`
|
|
435
|
+
+ ` AND status = 'completed' AND completed_at IS NOT NULL ORDER BY completed_at ASC`;
|
|
436
|
+
try {
|
|
437
|
+
let rows;
|
|
438
|
+
if (driver.kind === 'node') {
|
|
439
|
+
const db = new driver.DatabaseSync(dbFile, { readOnly: true });
|
|
440
|
+
try { rows = db.prepare(sql).all(); } finally { db.close(); }
|
|
441
|
+
} else {
|
|
442
|
+
const agg = runCli(dbFile,
|
|
443
|
+
`SELECT coalesce(json_group_array(json_object('completed_at', completed_at, 'duration_ms', duration_ms,`
|
|
444
|
+
+ ` 'time_to_first_token_ms', time_to_first_token_ms, 'input_tokens', input_tokens, 'output_tokens', output_tokens,`
|
|
445
|
+
+ ` 'reasoning_tokens', reasoning_tokens, 'cache_read_input_tokens', cache_read_input_tokens,`
|
|
446
|
+
+ ` 'cache_creation_input_tokens', cache_creation_input_tokens, 'computed_total_tokens', computed_total_tokens)), '[]')`
|
|
447
|
+
+ ` FROM (${sql});`);
|
|
448
|
+
rows = JSON.parse(agg.stdout.trim() || '[]');
|
|
449
|
+
}
|
|
450
|
+
const num = (v) => Number(v) || 0;
|
|
451
|
+
// 净生成时长 = 耗时 − 首 token 时机。两种情形按全程(耗时)算生成时长:
|
|
452
|
+
// 1. 非流式/整段返回:首 token 时机贴着结束(实测只差 20-30ms),扣出来是
|
|
453
|
+
// 毫秒级会把速率顶到几万 tok/s(首 token 占耗时 8 成以上即判定);
|
|
454
|
+
// 2. 首 token 时机缺失(部分供应商不回传,如 glm-5.3 占近三成):排除掉会
|
|
455
|
+
// 让整段速率消失。只有耗时也没有时留 null
|
|
456
|
+
const genMsOf = (dur, ttft) => (dur > 0 ? (ttft > 0 && ttft < dur * 0.8 ? dur - ttft : dur) : null);
|
|
457
|
+
const rounds = rows.map((r, i) => {
|
|
458
|
+
const inp = num(r.input_tokens);
|
|
459
|
+
const cacheRead = num(r.cache_read_input_tokens);
|
|
460
|
+
const ttft = num(r.time_to_first_token_ms);
|
|
461
|
+
const dur = num(r.duration_ms);
|
|
462
|
+
const genMs = genMsOf(dur, ttft);
|
|
463
|
+
const out = num(r.output_tokens);
|
|
464
|
+
return {
|
|
465
|
+
idx: i + 1,
|
|
466
|
+
at: num(r.completed_at),
|
|
467
|
+
in: inp,
|
|
468
|
+
out,
|
|
469
|
+
total: num(r.computed_total_tokens),
|
|
470
|
+
reasoning: num(r.reasoning_tokens),
|
|
471
|
+
cacheRead,
|
|
472
|
+
cacheWrite: num(r.cache_creation_input_tokens),
|
|
473
|
+
hitRate: inp > 0 ? cacheRead / inp : null,
|
|
474
|
+
genMs,
|
|
475
|
+
tps: genMs ? out / (genMs / 1000) : null,
|
|
476
|
+
};
|
|
477
|
+
});
|
|
478
|
+
const summary = { requests: rounds.length, totalIn: 0, totalOut: 0, totalCacheRead: 0, hitRate: null };
|
|
479
|
+
for (const r of rounds) {
|
|
480
|
+
summary.totalIn += r.in;
|
|
481
|
+
summary.totalOut += r.out;
|
|
482
|
+
summary.totalCacheRead += r.cacheRead;
|
|
483
|
+
}
|
|
484
|
+
summary.hitRate = summary.totalIn > 0 ? summary.totalCacheRead / summary.totalIn : null;
|
|
485
|
+
// 会话树最近请求的净生成速率:单独一条查询(trace 索引),取最近 30 笔里落在
|
|
486
|
+
// “最近完成时刻前 60 秒”的请求,Σ输出 ÷ Σ净生成秒数;没有可用行留 null
|
|
487
|
+
summary.tps = null;
|
|
488
|
+
try {
|
|
489
|
+
const tSql = `SELECT output_tokens, duration_ms, time_to_first_token_ms, completed_at FROM model_usage`
|
|
490
|
+
+ ` WHERE (session_id = ${esc(sid)}${treeTrace ? ` OR trace_id = ${esc(treeTrace)}` : ''})`
|
|
491
|
+
+ ` AND query_source = 'main_turn' AND status = 'completed' AND completed_at IS NOT NULL`
|
|
492
|
+
+ ` ORDER BY completed_at DESC LIMIT 30`;
|
|
493
|
+
let tRows;
|
|
494
|
+
if (driver.kind === 'node') {
|
|
495
|
+
const db = new driver.DatabaseSync(dbFile, { readOnly: true });
|
|
496
|
+
try { tRows = db.prepare(tSql).all(); } finally { db.close(); }
|
|
497
|
+
} else {
|
|
498
|
+
const agg = runCli(dbFile,
|
|
499
|
+
`SELECT coalesce(json_group_array(json_object('output_tokens', output_tokens, 'duration_ms', duration_ms,`
|
|
500
|
+
+ ` 'time_to_first_token_ms', time_to_first_token_ms, 'completed_at', completed_at)), '[]') FROM (${tSql});`);
|
|
501
|
+
tRows = JSON.parse(agg.stdout.trim() || '[]');
|
|
502
|
+
}
|
|
503
|
+
if (tRows.length) {
|
|
504
|
+
const anchorT = num(tRows[0].completed_at);
|
|
505
|
+
let outSum = 0;
|
|
506
|
+
let genSum = 0;
|
|
507
|
+
for (const r of tRows) {
|
|
508
|
+
if (num(r.completed_at) < anchorT - 60_000) break;
|
|
509
|
+
const genMs = genMsOf(num(r.duration_ms), num(r.time_to_first_token_ms));
|
|
510
|
+
if (genMs) { outSum += num(r.output_tokens); genSum += genMs; }
|
|
511
|
+
}
|
|
512
|
+
if (genSum > 0) summary.tps = outSum / (genSum / 1000);
|
|
513
|
+
}
|
|
514
|
+
} catch { /* 速率取不到留 null,其它汇总不受影响 */ }
|
|
515
|
+
return { rounds, summary };
|
|
516
|
+
} catch {
|
|
517
|
+
return empty; // 读取失败按无数据处理(每轮标注与状态栏项自然隐藏)
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
// 项目里"真未读"的任务数(未读但排除错误态):项目行蓝色未读徽标的判据——
|
|
522
|
+
// 错误态任务行显示的是红色错误点(应用图标优先级 错误>未读),它的未读不该再
|
|
523
|
+
// 把项目徽标点亮成蓝色(subagent-icon.js)
|
|
524
|
+
export async function listProjectsUnread(dataRoot, projectIds) {
|
|
525
|
+
const out = {};
|
|
526
|
+
const wanted = [...new Set((projectIds || []).map(String).filter(Boolean))];
|
|
527
|
+
if (!wanted.length) return out;
|
|
528
|
+
const dbFile = taskIndexPath(dataRoot);
|
|
529
|
+
if (!existsSync(dbFile)) return out;
|
|
530
|
+
const driver = await loadDriver();
|
|
531
|
+
if (!driver) return out;
|
|
532
|
+
const esc = (v) => "'" + String(v).replace(/'/g, "''") + "'";
|
|
533
|
+
const inList = wanted.map((id) => esc(id)).join(', ');
|
|
534
|
+
const sql = `SELECT project_id, sum(CASE WHEN task_status = 'error' THEN 0 ELSE 1 END) AS n
|
|
535
|
+
FROM tasks WHERE project_id IN (${inList}) AND unread_at IS NOT NULL
|
|
536
|
+
AND deleted = 0 AND coalesce(cli_deleted, 0) = 0
|
|
537
|
+
GROUP BY project_id`;
|
|
538
|
+
try {
|
|
539
|
+
let rows;
|
|
540
|
+
if (driver.kind === 'node') {
|
|
541
|
+
const db = new driver.DatabaseSync(dbFile, { readOnly: true });
|
|
542
|
+
try { rows = db.prepare(sql).all(); } finally { db.close(); }
|
|
543
|
+
} else {
|
|
544
|
+
const agg = runCli(dbFile,
|
|
545
|
+
`SELECT coalesce(json_group_array(json_object('project_id', project_id, 'n', n)), '[]') FROM (${sql});`);
|
|
546
|
+
rows = JSON.parse(agg.stdout.trim() || '[]');
|
|
547
|
+
}
|
|
548
|
+
for (const r of rows) out[String(r.project_id)] = Number(r.n) || 0;
|
|
549
|
+
return out;
|
|
550
|
+
} catch {
|
|
551
|
+
return null; // 读取失败返回 null,调用方不干预徽标
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
// 某工作区的任务会话 id(最近更新在前,7 天内有动静的取 30 个):折叠项目行扫
|
|
556
|
+
// 子代理运行状态的候选清单——行折叠后会话 id 不在 DOM 里,只能从任务索引反查。
|
|
557
|
+
// 7 天窗:长跑子代理的父会话最晚在派出子代理那一趟被写过,超过 7 天的会话里
|
|
558
|
+
// 还挂着子代理的实测都是僵死记录(shortcut: 超长后台子代理会漏,等用户反馈再放宽)
|
|
559
|
+
export async function listWorkspaceTaskIds(dataRoot, wsPath) {
|
|
560
|
+
const dbFile = taskIndexPath(dataRoot);
|
|
561
|
+
if (!existsSync(dbFile)) return [];
|
|
562
|
+
const driver = await loadDriver();
|
|
563
|
+
if (!driver) return [];
|
|
564
|
+
const esc = (v) => "'" + String(v).replace(/'/g, "''") + "'";
|
|
565
|
+
// 任务行的工作区路径可能带尾分隔符(实测两种都有),两侧都归一后比较
|
|
566
|
+
const target = esc(String(wsPath || '').replace(/[\\/]+$/, ''));
|
|
567
|
+
const where = `rtrim(rtrim(workspace_path, '/'), char(92)) = ${target}`;
|
|
568
|
+
const since = Date.now() - 7 * 86400_000;
|
|
569
|
+
const sql = `SELECT task_id FROM tasks WHERE ${where} AND deleted = 0 AND updated_at >= ${since} ORDER BY updated_at DESC LIMIT 30`;
|
|
570
|
+
try {
|
|
571
|
+
let rows;
|
|
572
|
+
if (driver.kind === 'node') {
|
|
573
|
+
const db = new driver.DatabaseSync(dbFile, { readOnly: true });
|
|
574
|
+
try { rows = db.prepare(sql).all(); } finally { db.close(); }
|
|
575
|
+
} else {
|
|
576
|
+
const agg = runCli(dbFile,
|
|
577
|
+
`SELECT coalesce(json_group_array(json_object('task_id', task_id)), '[]') FROM (${sql});`);
|
|
578
|
+
rows = JSON.parse(agg.stdout.trim() || '[]');
|
|
579
|
+
}
|
|
580
|
+
return rows.map((r) => String(r.task_id)).filter(Boolean);
|
|
581
|
+
} catch {
|
|
582
|
+
return [];
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
|
|
276
586
|
// 状态栏统计用:任务总数(未删除的会话行)
|
|
277
587
|
export async function countTasks(dataRoot) {
|
|
278
588
|
const dbFile = taskIndexPath(dataRoot);
|
|
@@ -301,7 +611,7 @@ export async function listOverriddenTitles(dataRoot) {
|
|
|
301
611
|
const titles = {};
|
|
302
612
|
try {
|
|
303
613
|
if (driver.kind === 'node') {
|
|
304
|
-
const db = new driver.DatabaseSync(dbFile);
|
|
614
|
+
const db = new driver.DatabaseSync(dbFile, { readOnly: true });
|
|
305
615
|
try {
|
|
306
616
|
db.exec(`PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS}`);
|
|
307
617
|
for (const row of db.prepare(
|
|
@@ -350,7 +660,8 @@ export async function isTaskTitleOverridden(dataRoot, sessId) {
|
|
|
350
660
|
// 之后官方自动标题不会再覆盖这条记录。仅在会话未删除、且从未被手动重命名过
|
|
351
661
|
// (title_overridden = 0)时写入——手动重命名永远优先。返回 { written, title };
|
|
352
662
|
// written = false 表示没写(已重命名或会话不在索引中)。库被占用时抛 index-busy。
|
|
353
|
-
|
|
663
|
+
// force:用户显式“自动重命名”已重命名过的会话也照写(改名意图明确,不守旧行)。
|
|
664
|
+
export async function setTaskTitleIfNotOverridden(dataRoot, sessId, title, { force = false } = {}) {
|
|
354
665
|
const dbFile = taskIndexPath(dataRoot);
|
|
355
666
|
if (!existsSync(dbFile)) return { written: false, title };
|
|
356
667
|
const driver = await loadDriver();
|
|
@@ -367,7 +678,8 @@ export async function setTaskTitleIfNotOverridden(dataRoot, sessId, title) {
|
|
|
367
678
|
db.exec('BEGIN IMMEDIATE');
|
|
368
679
|
try {
|
|
369
680
|
const r = db.prepare(
|
|
370
|
-
'UPDATE tasks SET title = ?, title_overridden = 1 WHERE task_id = ? AND deleted = 0
|
|
681
|
+
'UPDATE tasks SET title = ?, title_overridden = 1 WHERE task_id = ? AND deleted = 0'
|
|
682
|
+
+ (force ? '' : ' AND title_overridden = 0')
|
|
371
683
|
).run(title, sessId);
|
|
372
684
|
db.exec('COMMIT');
|
|
373
685
|
return { written: r.changes > 0, title };
|
|
@@ -381,7 +693,7 @@ export async function setTaskTitleIfNotOverridden(dataRoot, sessId, title) {
|
|
|
381
693
|
const r = runCli(dbFile,
|
|
382
694
|
'BEGIN IMMEDIATE;\n'
|
|
383
695
|
+ `UPDATE tasks SET title = ${esc(title)}, title_overridden = 1`
|
|
384
|
-
+ ` WHERE task_id = ${esc(sessId)} AND deleted = 0 AND title_overridden = 0;\n`
|
|
696
|
+
+ ` WHERE task_id = ${esc(sessId)} AND deleted = 0${force ? '' : ' AND title_overridden = 0'};\n`
|
|
385
697
|
+ 'SELECT changes();\nCOMMIT;');
|
|
386
698
|
return { written: Number(r.stdout.trim()) > 0, title };
|
|
387
699
|
} catch (err) {
|
|
@@ -443,7 +755,7 @@ export async function getTaskProviderModel(dataRoot, sessId) {
|
|
|
443
755
|
: 'WHERE deleted = 0 AND model != \'\' ORDER BY updated_at DESC LIMIT 1';
|
|
444
756
|
try {
|
|
445
757
|
if (driver.kind === 'node') {
|
|
446
|
-
const db = new driver.DatabaseSync(dbFile);
|
|
758
|
+
const db = new driver.DatabaseSync(dbFile, { readOnly: true });
|
|
447
759
|
try {
|
|
448
760
|
db.exec(`PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS}`);
|
|
449
761
|
row = db.prepare(`SELECT provider, model FROM tasks ${where}`).get() || null;
|
|
@@ -475,7 +787,7 @@ export async function listTaskWorkspaceMap(dataRoot) {
|
|
|
475
787
|
try {
|
|
476
788
|
let rows = [];
|
|
477
789
|
if (driver.kind === 'node') {
|
|
478
|
-
const db = new driver.DatabaseSync(dbFile);
|
|
790
|
+
const db = new driver.DatabaseSync(dbFile, { readOnly: true });
|
|
479
791
|
try {
|
|
480
792
|
db.exec(`PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS}`);
|
|
481
793
|
rows = db.prepare('SELECT task_id, workspace_path, workspace_key FROM tasks').all();
|
|
@@ -499,7 +811,7 @@ function runCli(dbFile, script) {
|
|
|
499
811
|
windowsHide: true,
|
|
500
812
|
input: `.timeout ${BUSY_TIMEOUT_MS}\n` + script,
|
|
501
813
|
encoding: 'utf8',
|
|
502
|
-
maxBuffer:
|
|
814
|
+
maxBuffer: 16 << 20, // 大会话的 JSON 聚合输出轻松过 1MB,与 helper 的上限对齐
|
|
503
815
|
});
|
|
504
816
|
if (r.error) throw r.error;
|
|
505
817
|
if (r.status !== 0) throw new Error('sqlite3 CLI 执行失败: ' + (r.stderr || r.stdout || ('exit ' + r.status)));
|
|
@@ -525,51 +837,78 @@ export async function reconcileCustomTitles(dataRoot, writtenMap) {
|
|
|
525
837
|
const idxFile = taskIndexPath(dataRoot);
|
|
526
838
|
if (!existsSync(cliFile) || !existsSync(idxFile)) return repaired;
|
|
527
839
|
|
|
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
|
-
};
|
|
840
|
+
// 会话 id 有 sess_ 与 session_ 两种前缀(新版应用为 session_),两种都认
|
|
841
|
+
const entries = Object.entries(writtenMap)
|
|
842
|
+
.filter(([sessId, rec]) => /^(?:sess|session)_[A-Za-z0-9._-]+$/.test(sessId) && rec && typeof rec.title === 'string');
|
|
843
|
+
if (!entries.length) return repaired;
|
|
539
844
|
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
let
|
|
544
|
-
|
|
545
|
-
// CLI 已不是我们所写的 custom 标题:别人改过(手动改名/官方),不碰
|
|
546
|
-
if (!cli || cli.title_source !== 'custom' || cli.title !== rec.title) continue;
|
|
845
|
+
// 批量处理:一次读 CLI 标题、一次事务写索引。逐条开关库(旧实现)在
|
|
846
|
+
// customWritten 多时(上限 500 条)是上千次同步开库/spawnSync,会卡住事件循环
|
|
847
|
+
if (driver.kind === 'node') {
|
|
848
|
+
let cliDb = null;
|
|
849
|
+
let idxDb = null;
|
|
547
850
|
try {
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
851
|
+
cliDb = new driver.DatabaseSync(cliFile, { readOnly: true });
|
|
852
|
+
const sel = cliDb.prepare('SELECT title, title_source FROM session WHERE id = ?');
|
|
853
|
+
const todo = [];
|
|
854
|
+
for (const [sessId, rec] of entries) {
|
|
855
|
+
let cli;
|
|
856
|
+
try { cli = sel.get(sessId) || null; } catch { continue; }
|
|
857
|
+
// CLI 已不是我们所写的 custom 标题:别人改过(手动改名/官方),不碰
|
|
858
|
+
if (!cli || cli.title_source !== 'custom' || cli.title !== rec.title) continue;
|
|
859
|
+
todo.push([sessId, rec.title]);
|
|
860
|
+
}
|
|
861
|
+
if (!todo.length) return repaired;
|
|
862
|
+
const done = [];
|
|
863
|
+
idxDb = new driver.DatabaseSync(idxFile);
|
|
864
|
+
idxDb.exec(`PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS}`);
|
|
865
|
+
idxDb.exec('BEGIN IMMEDIATE');
|
|
866
|
+
try {
|
|
867
|
+
const upd = idxDb.prepare(
|
|
868
|
+
'UPDATE tasks SET title = ? WHERE task_id = ? AND deleted = 0 AND title_overridden = 1 AND title != ?'
|
|
869
|
+
);
|
|
870
|
+
for (const [sessId, title] of todo) {
|
|
871
|
+
if (upd.run(title, sessId, title).changes > 0) done.push(sessId);
|
|
872
|
+
}
|
|
873
|
+
idxDb.exec('COMMIT');
|
|
874
|
+
} catch (err) {
|
|
875
|
+
try { idxDb.exec('ROLLBACK'); } catch { /* 已回滚 */ }
|
|
876
|
+
throw err;
|
|
570
877
|
}
|
|
878
|
+
repaired.push(...done); // 提交成功才记账,回滚时不虚报
|
|
571
879
|
} catch { /* 占用等:下次再校正 */ }
|
|
880
|
+
finally {
|
|
881
|
+
try { if (cliDb) cliDb.close(); } catch { /* ignore */ }
|
|
882
|
+
try { if (idxDb) idxDb.close(); } catch { /* ignore */ }
|
|
883
|
+
}
|
|
884
|
+
return repaired;
|
|
572
885
|
}
|
|
886
|
+
|
|
887
|
+
// sqlite3 CLI 驱动(缺 node:sqlite 的环境):同样批量——一次读全部标题,
|
|
888
|
+
// 一次事务写全部更新(每次 UPDATE 后 SELECT changes() 输出一行计数)
|
|
889
|
+
try {
|
|
890
|
+
const ids = entries.map(([sessId]) => esc(sessId)).join(', ');
|
|
891
|
+
const r = runCli(cliFile,
|
|
892
|
+
`SELECT coalesce(json_group_array(json_object('id', id, 'title', title, 'title_source', title_source)), '[]') FROM session WHERE id IN (${ids});`);
|
|
893
|
+
const rows = JSON.parse(r.stdout.trim() || '[]');
|
|
894
|
+
const byId = new Map(rows.map((row) => [String(row.id), row]));
|
|
895
|
+
const todo = [];
|
|
896
|
+
for (const [sessId, rec] of entries) {
|
|
897
|
+
const cli = byId.get(sessId);
|
|
898
|
+
if (!cli || cli.title_source !== 'custom' || cli.title !== rec.title) continue;
|
|
899
|
+
todo.push([sessId, rec.title]);
|
|
900
|
+
}
|
|
901
|
+
if (!todo.length) return repaired;
|
|
902
|
+
const sql = ['BEGIN IMMEDIATE;'];
|
|
903
|
+
for (const [sessId, title] of todo) {
|
|
904
|
+
sql.push(`UPDATE tasks SET title = ${esc(title)} WHERE task_id = ${esc(sessId)} AND deleted = 0 AND title_overridden = 1 AND title != ${esc(title)};`);
|
|
905
|
+
sql.push('SELECT changes();');
|
|
906
|
+
}
|
|
907
|
+
sql.push('COMMIT;');
|
|
908
|
+
const w = runCli(idxFile, sql.join('\n'));
|
|
909
|
+
const counts = w.stdout.trim().split(/\r?\n/).filter((s) => s !== '').map(Number);
|
|
910
|
+
todo.forEach(([sessId], i) => { if (counts[i] > 0) repaired.push(sessId); });
|
|
911
|
+
} catch { /* 占用等:下次再校正 */ }
|
|
573
912
|
return repaired;
|
|
574
913
|
}
|
|
575
914
|
|
|
@@ -635,3 +974,62 @@ export async function setCustomSessionTitle(dataRoot, sessId, title) {
|
|
|
635
974
|
throw e;
|
|
636
975
|
}
|
|
637
976
|
}
|
|
977
|
+
|
|
978
|
+
// 手动自动重命名的素材:会话最近 N 轮问答(问/答文本,按时间先后)。一轮 =
|
|
979
|
+
// 一条用户消息 + 其后的助手回答文本;跳过 model-only 的注入消息(agent 列表
|
|
980
|
+
// 等)与没有文本的部分。超 1200 字(generateTitleWith 的素材上限)时从最旧
|
|
981
|
+
// 一轮丢起,保住最新内容。返回 '' = 没有可用问答。
|
|
982
|
+
export async function readRecentQa(dataRoot, sessId, rounds) {
|
|
983
|
+
const dbFile = join(dataRoot, 'cli', 'db', 'db.sqlite');
|
|
984
|
+
if (!existsSync(dbFile)) return '';
|
|
985
|
+
const driver = await loadDriver();
|
|
986
|
+
if (!driver) return '';
|
|
987
|
+
const n = Math.min(20, Math.max(1, Math.round(Number(rounds) || 3)));
|
|
988
|
+
const esc = (v) => "'" + String(v).replace(/'/g, "''") + "'";
|
|
989
|
+
// 单行 JSON 查询:node 驱动与 sqlite3 命令两种驱动共用同一条 SQL
|
|
990
|
+
const one = (sql) => {
|
|
991
|
+
if (driver.kind === 'node') {
|
|
992
|
+
const db = new driver.DatabaseSync(dbFile, { readOnly: true });
|
|
993
|
+
try { return String(db.prepare(sql).get()?.out || ''); } finally { db.close(); }
|
|
994
|
+
}
|
|
995
|
+
return runCli(dbFile, sql).stdout.trim();
|
|
996
|
+
};
|
|
997
|
+
const msgs = JSON.parse(one(
|
|
998
|
+
"SELECT coalesce(json_group_array(json_array(id, data)), '[]') AS out FROM"
|
|
999
|
+
+ ` (SELECT id, data FROM message WHERE session_id = ${esc(sessId)} ORDER BY sequence, time_created);`
|
|
1000
|
+
) || '[]');
|
|
1001
|
+
if (!Array.isArray(msgs) || !msgs.length) return '';
|
|
1002
|
+
const parts = JSON.parse(one(
|
|
1003
|
+
"SELECT coalesce(json_group_array(json_array(message_id, data)), '[]') AS out FROM"
|
|
1004
|
+
+ ` (SELECT message_id, data FROM part WHERE session_id = ${esc(sessId)}`
|
|
1005
|
+
+ " AND json_extract(data, '$.type') = 'text' ORDER BY message_id, sequence);"
|
|
1006
|
+
) || '[]');
|
|
1007
|
+
const textOf = new Map(); // message_id → 拼接后的文本
|
|
1008
|
+
for (const row of (Array.isArray(parts) ? parts : [])) {
|
|
1009
|
+
try {
|
|
1010
|
+
const text = JSON.parse(row[1])?.text;
|
|
1011
|
+
if (typeof text === 'string' && text.trim()) {
|
|
1012
|
+
textOf.set(row[0], (textOf.get(row[0]) ? textOf.get(row[0]) + '\n' : '') + text.trim());
|
|
1013
|
+
}
|
|
1014
|
+
} catch { /* 坏行跳过 */ }
|
|
1015
|
+
}
|
|
1016
|
+
// 按 sequence 分轮:用户消息开新一轮,助手文本并入当前轮
|
|
1017
|
+
const roundsList = [];
|
|
1018
|
+
for (const [id, data] of msgs) {
|
|
1019
|
+
let m;
|
|
1020
|
+
try { m = JSON.parse(data); } catch { continue; }
|
|
1021
|
+
const text = textOf.get(id);
|
|
1022
|
+
if (!m || !text) continue;
|
|
1023
|
+
if (m.role === 'user') {
|
|
1024
|
+
if (m.metadata && m.metadata.visibility === 'model-only') continue;
|
|
1025
|
+
roundsList.push({ q: text.slice(0, 600), a: '' });
|
|
1026
|
+
} else if (m.role === 'assistant' && roundsList.length) {
|
|
1027
|
+
const r = roundsList[roundsList.length - 1];
|
|
1028
|
+
r.a = ((r.a ? r.a + '\n' : '') + text).slice(0, 600);
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
const sel = roundsList.slice(-n);
|
|
1032
|
+
const fmt = (rs) => rs.map((r) => '问:' + r.q + (r.a ? '\n答:' + r.a : '')).join('\n');
|
|
1033
|
+
while (sel.length > 1 && fmt(sel).length > 1200) sel.shift();
|
|
1034
|
+
return fmt(sel);
|
|
1035
|
+
}
|