P1 修复面收口: Prompt Cache 根治(日期/记忆/附件三类易变内容出 system 入用户消息 前置块 user-context.ts, system 跨 run 字节级稳定; Anthropic system 块数组化 + cache_control ephemeral 断言, DeepSeek 自动缓存前缀命中 — 多轮对话输入 token 成本降数量级); 编辑重发/重新生成幽灵 Trace 双侧根治(DB truncateMessagesAfter 同步过滤 metadata.traceSteps + 前端 trimTraceStepsByAnchor 镜像, 严格小于锚点 时间戳, 同毫秒等值判废); sessions:deleteMessage 死通道全链路删除(渲染层零调用 + message_count 漂移面); Ollama vision 能力门控全链路(MetonaModelInfo .supportsVision 贯穿 adapter/IPC/store/UI, model-capabilities.ts 三道判定纯函数, 未知保守放行); 记忆固化节流(consolidation-policy 纯函数: 总开关 + 内容门控 [回答>=200字符或存在成功工具调用] + 会话级 10 分钟频率窗口, 三 memory.* 配置键) P2 安全纵深: SSRF DNS Pinning 关闭 rebinding 窗口(ssrf-guard 重构 resolvePublicAddresses 单源; ssrf-dispatcher 以 undici Agent.connect.lookup 钉死校验 IP, TLS SNI 保持原域名, 一次性 dispatcher 用后即毁; 代理激活显式 退化为仅入口校验); web_fetch 重写手动逐跳重定向循环(每跳先校验后连接, 替代 redirect:follow 内核跟跳的中间跳裸奔, 上限 5 跳); http_request 换用 pinned fetch; web_search 可达性预检加固(私有 URL 零请求 + 不跟跳, 3xx 视为 可达); Agent 浏览器 CORS 通配收紧为 Origin 回显 + Vary: Origin; ConfirmationHook.forgetSession 会话终态清理(会话删除/abort 联动/SubAgent 终结三处接线, 根治 rememberedDecisions 泄漏) P3 架构还债: agent.enableReflection 死配置全链路接线(main→shared→引擎→ Orchestrator→设置开关, REFLECTING 状态真实可达); AgentLoopConfig.timeoutMs 死字段删除; MemoryManager.cleanupExpired 挂入健康检查周期(expires_at 回收 管道真实化); buildSafeEnv 收敛 utils/safe-env.ts 单源(run_command 与 MCP stdio 共用, 终结双实现漂移); Trace 生命周期治理(metadata 只保留最近 20 个 run — keepRecentRuns 纯函数; JSONL 录制启动自动清理保留 200 个 + 设置页 手动清理); SLO/健康快照可视化(app:healthSnapshot IPC + 设置页只读卡片 + 审计链一键校验) P4 能力演进: 会话标题 LLM 自动生成(TitleGenerator — 每会话幂等/并发重入复用 同一 Promise/自定义标题不覆盖/失败静默回退, Sidebar 经 config:changed 实时 刷新); MCP 自动重连(5s/15s/60s 退避最多 3 次, reconnecting 状态机, teardownConnection 内部拆除保留簿记 — 用户断开/开关关闭即时取消, 设置页 显示第 N/3 次); 死循环检测 ABAB 乒乓模式(最近4轮 A→B→A→B 交替判定, 补齐 docs 第五章"两状态反复切换"检测契约); i18n 第三阶段(ChatInput/LLMSettings/ OnboardingWizard/MemoryViewer 主链路文案出层, zh-CN + en-US 双字典补齐) 测试: 737 → 824 用例(+87, 新增 8 个测试文件 + 扩展 3 个)。新覆盖: user-context 分组/空值收缩/拼接契约、context-builder 字节级稳定性、Anthropic cache_control 四态、consolidation-policy 九路判定矩阵、ssrf-dispatcher(pinned lookup/重定向 解析/IP 校验)、forget-session 会话隔离、trace-lifecycle run 淘汰、 trace-trim 严格小于边界、safe-env 净化矩阵、mcp-reconnect 退避状态机 (fake timers)、title-generator 并发重入、SQLite 侧 truncate×TRACE 联动 (Electron ABI)。测试驱动修复: GIT_*/ 注释终止块注释、重连计数被自身重试 前置断开重置(拆 teardownConnection 保留簿记)、TitleGenerator 幂等占位与 并发去重的检查顺序竞态(去重先于幂等) 版本: 0.7.3; README 同步(配置表新增 agent.enableReflection/memory.*/mcp.autoReconnect) 回归: typecheck 双端 0 错误; ESLint 0/0; 系统 Node 771 通过 53 跳过 (better-sqlite3 ABI); Electron ABI 全量 824/824 零跳过
201 lines
7.9 KiB
TypeScript
201 lines
7.9 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;
|
||
|
||
// 已有自定义标题(用户手动重命名 / 前端首条截断标题)时不覆盖,
|
||
// 避免用户主动命名被 LLM 标题冲掉
|
||
const sessions = this.sessionService.list();
|
||
const current = sessions.find((s) => s.id === sessionId);
|
||
if (current && current.title !== '新会话') {
|
||
log.debug(`[TitleGenerator] session ${sessionId} already titled "${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;
|
||
}
|
||
}
|
||
}
|