P1 修复面收口: - 超时三态区分(aborted→USER_INTERRUPT / ETIMEDOUT→TIMEOUT / 其余→ERROR), 根治"真实网络超时被误报为用户中断" - 流空闲超时统一(SSE/Ollama/Anthropic 读循环 60s 无数据抛 504 进重试通道) - 同会话并发 sendMessage 防重入(isRunning 守卫)+ 会话存在性预检 + 前置调用移入 try(ERROR+DONE 双事件保证,根治 isStreaming 假死) - 清空审计后 resetChainCache(根治 verifyChain 误报 TAMPERED) - DONE 不再提前清理 TRACE(TERMINATED 统一收尾,补全最终迭代录制) - IME 合成回车不发送(普通 Enter + Cmd/Ctrl+Enter 双分支)+ handleSend 闭包修复 P2 安全纵深: - preload 移除原始 electronAPI 暴露(渲染层零使用,关掉 XSS invoke 任意通道单点风险) - CORS 同源回显根治(仅当前浏览页面 Origin,did-navigate 同步) - MEMORY.md 命令保护正则扩展(括号/$/反引号/< 重定向边界 + 前导路径) - write_file append TOCTOU 统一(open 后 realpath 校验,新文件分支补漏) - 敏感键归一化(authKey 驼峰/连字符命中)+ MCP headers 鉴权值加密落库 - ReDoS 检测共享化(search_files/file_editor 统一拦截) - run_tests/lint_code 升风险 + 需确认 + npx --no-install(执行边界对齐 run_command) - MCP/SearXNG/llm.baseURL/updateFeedUrl 配置类 URL 高危目标校验(IPv6 去括号 + 十六进制映射解析 + 尾点剥离) P3 架构还债: - temperature/maxTokens 热生效(引擎/编排器/SubAgent 三处接线)+ setBatch 单事务落盘 - SessionRecorder flush 竞态根治(flushPromise 等待 + 超限内联落盘 + stopRecording async) - 内存收口(lastConsolidationBySession LRU / subTraces 清理 / 会话删除 disposeEngine) - i18n 全量收口(28 组件 + 353 key 双字典,状态标签改渲染时函数) - 死代码清理(updateTraceStep/HEADER_HEIGHT/void preA/失实注释) - 斜杠菜单 MUI 化 + 删除逻辑收敛 resetSessionState + Blob URL 统一释放 + 用户消息"仅保存"落库(saveMessage 透传前端 id 修复 id 错位) P4 能力演进: - 死循环检测拆分(驻留前置 + 乒乓后置带进度信号,合法交替不误报) - run-lock 30s 超时强制 abort(旧 run 卡死不无限排队) - RETRY 双通道 stream_reset(前端按 run 归属精确清空,根治重试文本重复) - FTS5 trigram 中文子串搜索(迁移 9 版本化 SCHEMA_VERSION=2,≤2 字符 LIKE 回退) - getContextWindow 兜底 1M→128K(未知模型防 413) 测试: - 855 → 2406 用例(+1551,2.8 倍):服务层 +325(含 MemoryManager 51 新用例)、 工具实体 +483、IPC/适配器 +390(含 OpenAI/Anthropic/Ollama 独立套件)、 纯函数表格化 +330;引入 jsdom + @testing-library(14 组件测试文件 249 用例) - 修复 R1(saveMessage id 透传)/ R2(stream_reset 精确归属)两个回归缺陷 - 遗留低危项清零:git-tools 顺序耦合 / web-fetch 真实时间退避 / slo 内存断言 / mcp-security 多余 skipIf / deepseek-balance 命名误导 / 组件 mock 注入脆弱性 版本: 0.7.4; README 同步(工具风险表/版本徽章); 依赖: 移除 @electron-toolkit/preload, 新增 jsdom/@testing-library(devDependencies 不打包) 回归: typecheck 双端 0 错误; ESLint 0/0; Electron ABI 全量 2406/2406 零跳过; 系统 Node 2110 通过 296 跳过(better-sqlite3 ABI)
211 lines
8.6 KiB
TypeScript
211 lines
8.6 KiB
TypeScript
/**
|
||
* Title Generator — 会话标题 LLM 自动生成(v0.7.3 P4-1)
|
||
*
|
||
* 背景:首轮消息后前端仅以"用户首条消息截前 30 字符"作为会话标题
|
||
* (agent-store.sendMessage),中文长句体验差且语义压缩生硬。
|
||
*
|
||
* 本服务在会话首个完成的 run 之后(terminationReason === 'completed')用主
|
||
* Provider adapter 发起一次极小的非流式请求(maxTokens 32 / temperature 0.3 /
|
||
* thinking 关闭),生成 ≤16 字的精炼标题并写回 sessions 表。生成失败(网络 /
|
||
* 配额 / 解析失败)静默回退——前端首 30 字符截断标题保持有效,无损可用性。
|
||
*
|
||
* 契约:
|
||
* - 每个会话生命周期内仅生成一次(内存 Set 幂等,进程重启后自然重置——
|
||
* 已有非默认标题的会话通过 hasCustomTitle 判定跳过,不会重复生成);
|
||
* - 标题经 sanitizeTitle 清洗:剥离 markdown/引号/换行/前后缀冒号,
|
||
* 折叠空白,超长截断,空结果返回 null(调用方保持原标题不变)。
|
||
*/
|
||
|
||
import { nanoid } from 'nanoid';
|
||
import log from 'electron-log';
|
||
import type { IMetonaProviderAdapter, MetonaRequest } from '../harness/types';
|
||
import type { SessionService } from './session.service';
|
||
|
||
/** 生成标题的最大长度(字符)——超过即截断 */
|
||
const MAX_TITLE_LENGTH = 40;
|
||
|
||
/** 传给 LLM 的用户消息 / 回答摘录长度 */
|
||
const EXCERPT_LENGTH = 600;
|
||
|
||
/** LLM 调用超时(标题生成不应阻塞任何主流程) */
|
||
const TITLE_TIMEOUT_MS = 15_000;
|
||
|
||
/**
|
||
* 清洗 LLM 返回的标题文本。
|
||
*
|
||
* 规则(按序应用):
|
||
* 1. 剥离 markdown 代码围栏与首尾 `#`/`-`/`*` 列表标记;
|
||
* 2. 剥离成对包裹引号(中英文单双引号);
|
||
* 3. 剥离 "标题:"/"Title:" 这类自述前缀;
|
||
* 4. 折叠全部空白(含换行)为单个空格并 trim;
|
||
* 5. 超过 maxLen 截断;
|
||
* 6. 空结果返回 null(调用方保持原标题)。
|
||
*/
|
||
export function sanitizeTitle(raw: string, maxLen: number = MAX_TITLE_LENGTH): string | null {
|
||
if (!raw || typeof raw !== 'string') return null;
|
||
|
||
let title = raw.trim();
|
||
// 1/2. markdown 围栏、列表标记与包裹引号 —— 循环应用直至稳定(处理嵌套包装
|
||
// 如 ```"标题"``` / 多层引号;剥除全部首尾引号字符而非仅成对项,
|
||
// 使 '"""' 这类纯符号输入收敛为空 → null)
|
||
for (let i = 0; i < 3; i++) {
|
||
const before = title;
|
||
title = title
|
||
.replace(/^```(?:[a-z]*)\s*/i, '')
|
||
.replace(/\s*```$/i, '')
|
||
.replace(/^[#\-*>]+\s*/, '')
|
||
.replace(/^["'“”『』「"]+/, '')
|
||
.replace(/["'“”『』「"]+$/, '');
|
||
if (title === before) break;
|
||
}
|
||
// 3. 自述前缀(标题:/Title:/会话标题: 等)
|
||
title = title.replace(/^(?:标题|会话标题|题目|title)\s*[::]\s*/i, '');
|
||
// 4. 折叠空白(换行合并——LLM 偶发多行输出时取首行语义)
|
||
title = title.replace(/\s+/g, ' ').trim();
|
||
// 5. 截断
|
||
if (title.length > maxLen) title = title.slice(0, maxLen).trimEnd();
|
||
// 6. 空结果
|
||
return title.length > 0 ? title : null;
|
||
}
|
||
|
||
export class TitleGenerator {
|
||
/** 已生成过标题的会话(进程级幂等) */
|
||
private generated = new Set<string>();
|
||
/** 进行中的生成任务(防并发重复调用) */
|
||
private running = new Map<string, Promise<string | null>>();
|
||
|
||
constructor(
|
||
private getAdapter: () => IMetonaProviderAdapter,
|
||
private sessionService: SessionService,
|
||
) {}
|
||
|
||
/**
|
||
* 为会话生成标题(fire-and-forget 调用;失败静默)。
|
||
*
|
||
* @param sessionId 会话 ID
|
||
* @param userMessage 用户原始消息(干净版本,不含注入前缀)
|
||
* @param assistantAnswer Agent 最终回答
|
||
* @returns 生成的标题(未生成/失败返回 null)
|
||
*/
|
||
async maybeGenerateTitle(
|
||
sessionId: string,
|
||
userMessage: string,
|
||
assistantAnswer: string,
|
||
): Promise<string | null> {
|
||
if (!sessionId || typeof sessionId !== 'string') return null;
|
||
// 输入门控:双向内容均为空无生成意义
|
||
if (!userMessage?.trim() && !assistantAnswer?.trim()) return null;
|
||
|
||
// 并发去重先于幂等短路 —— 同一会话进行中的生成必须复用同一 Promise,
|
||
// 而不能被"已占位"的幂等判断吞掉(否则并发第二调用拿到 null)
|
||
const existing = this.running.get(sessionId);
|
||
if (existing) return existing;
|
||
// 幂等:每会话仅一次(占位同步完成,先于任何 await)
|
||
if (this.generated.has(sessionId)) return null;
|
||
|
||
this.generated.add(sessionId);
|
||
const task = this.generate(sessionId, userMessage, assistantAnswer).finally(() => {
|
||
this.running.delete(sessionId);
|
||
});
|
||
this.running.set(sessionId, task);
|
||
return task;
|
||
}
|
||
|
||
private async generate(
|
||
sessionId: string,
|
||
userMessage: string,
|
||
assistantAnswer: string,
|
||
): Promise<string | null> {
|
||
try {
|
||
const adapter = this.getAdapter();
|
||
if (!adapter) return null;
|
||
|
||
// 前端 agent-store.sendMessage 会在首条消息后把会话标题设为
|
||
// 「用户消息前 30 字符 + '...'」的截断标题(即时反馈,非用户主动命名)。
|
||
// 该截断标题必须被 LLM 标题覆盖 —— 旧实现只判断 `title !== '新会话'`,
|
||
// 把截断标题误判为"自定义标题"而跳过,导致 LLM 标题永不生成(v0.7.4 修复)。
|
||
// 仅当标题是"用户手动重命名"(非新会话且非自动截断标题)时才跳过。
|
||
// 用 getSession(含归档会话)替代 list()(默认排除归档)——
|
||
// 避免归档会话的标题判断查不到 current 而误覆盖。
|
||
const current = this.sessionService.getSession(sessionId);
|
||
const autoFallbackTitle =
|
||
userMessage.trim().length > 30
|
||
? userMessage.trim().slice(0, 30) + '...'
|
||
: userMessage.trim();
|
||
if (current && current.title !== '新会话' && current.title !== autoFallbackTitle) {
|
||
log.debug(
|
||
`[TitleGenerator] session ${sessionId} has custom title "${current.title}" — skip`,
|
||
);
|
||
return null;
|
||
}
|
||
|
||
const request: MetonaRequest = {
|
||
meta: {
|
||
sessionId: 'title-generation',
|
||
iteration: 0,
|
||
requestId: `tg_${nanoid(12)}`,
|
||
timestamp: Date.now(),
|
||
agentVersion: '1.0.0',
|
||
},
|
||
systemPrompt: {
|
||
roleDefinition:
|
||
'You generate concise conversation titles for an AI assistant desktop app.',
|
||
outputConstraints:
|
||
'Given the first user message and the assistant reply, output ONE title of at most 16 characters ' +
|
||
'in the same language as the user message. The title must capture the core topic or task. ' +
|
||
'No quotes, no markdown, no ending punctuation, no explanations — output the title text ONLY.',
|
||
safetyGuidelines:
|
||
'Do not include sensitive data (passwords, keys, personal info) in the title.',
|
||
},
|
||
messages: [
|
||
{
|
||
role: 'user',
|
||
content:
|
||
`User message: ${userMessage.slice(0, EXCERPT_LENGTH)}\n\n` +
|
||
`Assistant reply: ${assistantAnswer.slice(0, EXCERPT_LENGTH)}\n\n` +
|
||
`Output the title only.`,
|
||
timestamp: Date.now(),
|
||
},
|
||
],
|
||
params: {
|
||
maxTokens: 32,
|
||
temperature: 0.3,
|
||
stream: false,
|
||
thinkingEnabled: false,
|
||
thinkingEffort: 'low',
|
||
},
|
||
};
|
||
|
||
// 超时保护:标题生成绝不能拖慢会话收尾
|
||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||
try {
|
||
const timeoutPromise = new Promise<never>((_, reject) => {
|
||
timer = setTimeout(() => reject(new Error('title generation timeout')), TITLE_TIMEOUT_MS);
|
||
});
|
||
const response = await Promise.race([adapter.send(request), timeoutPromise]);
|
||
const title = sanitizeTitle(response.content);
|
||
if (!title) {
|
||
log.debug(
|
||
`[TitleGenerator] session ${sessionId}: empty/unsanitizable title, keeping fallback`,
|
||
);
|
||
return null;
|
||
}
|
||
const renamed = this.sessionService.rename(sessionId, title);
|
||
if (renamed) {
|
||
log.info(`[TitleGenerator] session ${sessionId} titled: "${title}"`);
|
||
}
|
||
return renamed ? title : null;
|
||
} finally {
|
||
if (timer) clearTimeout(timer);
|
||
}
|
||
} catch (err) {
|
||
// 静默回退:标题失败不影响会话可用性(前端首条截断标题仍在)
|
||
log.debug(
|
||
`[TitleGenerator] session ${sessionId} title generation failed:`,
|
||
(err as Error).message,
|
||
);
|
||
return null;
|
||
}
|
||
}
|
||
}
|