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 零跳过
147 lines
5.3 KiB
TypeScript
147 lines
5.3 KiB
TypeScript
/**
|
||
* truncateMessagesAfter × TRACE metadata 联动测试(v0.7.3 P1-2)
|
||
*
|
||
* 根治契约:编辑重发/重新生成截断消息时,sessions.metadata 中的 traceSteps
|
||
* 必须按 startedAt <= 锚点消息 created_at 同步过滤,否则 Trace 面板出现
|
||
* "幽灵步骤"(v0.7.2 A1 只修了 /clear 路径的 metadata 残留)。
|
||
*
|
||
* 运行要求:better-sqlite3 为 Electron ABI 构建,需 test:electron 模式执行;
|
||
* 系统 Node 下自动跳过。
|
||
*/
|
||
|
||
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
|
||
|
||
vi.mock('electron-log', () => ({
|
||
default: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
|
||
}));
|
||
|
||
let dbAvailable = true;
|
||
let Database: typeof import('better-sqlite3');
|
||
try {
|
||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||
Database = require('better-sqlite3');
|
||
const probe = new Database(':memory:');
|
||
probe.close();
|
||
} catch {
|
||
dbAvailable = false;
|
||
}
|
||
|
||
describe.skipIf(!dbAvailable)('truncateMessagesAfter × TRACE metadata 过滤(P1-2)', () => {
|
||
let db: import('better-sqlite3').Database;
|
||
// 测试域宽松类型:SessionService 依赖 Electron ABI 的 better-sqlite3 实例,
|
||
// 直接持有真实实例即可(同 session-summary.test.ts 的既有写法)
|
||
// eslint(next-line 无需禁用:测试文件未启用 no-explicit-any)
|
||
let sessionService: any;
|
||
|
||
beforeAll(async () => {
|
||
const { SessionService } = await import('../session.service');
|
||
db = new Database(':memory:');
|
||
db.exec(`
|
||
CREATE TABLE sessions (
|
||
id TEXT PRIMARY KEY,
|
||
title TEXT DEFAULT '新会话',
|
||
created_at INTEGER NOT NULL,
|
||
updated_at INTEGER NOT NULL,
|
||
message_count INTEGER DEFAULT 0,
|
||
pinned INTEGER DEFAULT 0,
|
||
archived INTEGER DEFAULT 0,
|
||
metadata TEXT DEFAULT '{}'
|
||
);
|
||
CREATE TABLE messages (
|
||
id TEXT PRIMARY KEY,
|
||
session_id TEXT NOT NULL,
|
||
role TEXT NOT NULL,
|
||
content TEXT,
|
||
reasoning_content TEXT,
|
||
tool_calls TEXT,
|
||
tool_result TEXT,
|
||
attachments TEXT,
|
||
iteration INTEGER,
|
||
created_at INTEGER NOT NULL
|
||
);
|
||
CREATE TABLE session_summaries (
|
||
session_id TEXT PRIMARY KEY,
|
||
summary TEXT NOT NULL,
|
||
summarized_until_rowid INTEGER NOT NULL,
|
||
updated_at INTEGER NOT NULL DEFAULT (unixepoch() * 1000)
|
||
);
|
||
`);
|
||
db.prepare(
|
||
'INSERT INTO sessions (id, created_at, updated_at, message_count) VALUES (?, ?, ?, 0)',
|
||
).run('s_trace', Date.now(), Date.now());
|
||
sessionService = new SessionService(() => db);
|
||
});
|
||
|
||
afterAll(() => {
|
||
try {
|
||
db?.close();
|
||
} catch {
|
||
/* ignore */
|
||
}
|
||
});
|
||
|
||
const insertMessage = (id: string, content: string, createdAt: number): number => {
|
||
db.prepare(
|
||
`INSERT INTO messages (id, session_id, role, content, created_at) VALUES (?, ?, 'user', ?, ?)`,
|
||
).run(id, 's_trace', content, createdAt);
|
||
const row = db.prepare('SELECT rowid AS rid FROM messages WHERE id = ?').get(id) as {
|
||
rid: number;
|
||
};
|
||
return row.rid;
|
||
};
|
||
|
||
const saveMetadata = (steps: Array<{ runId?: string; startedAt: number }>): void => {
|
||
db.prepare('UPDATE sessions SET metadata = ? WHERE id = ?').run(
|
||
JSON.stringify({ traceSteps: steps, tokenUsage: { totalTokens: 10 } }),
|
||
's_trace',
|
||
);
|
||
};
|
||
|
||
const loadMetadataSteps = (): Array<{ runId?: string; startedAt: number }> => {
|
||
const row = db.prepare('SELECT metadata FROM sessions WHERE id = ?').get('s_trace') as {
|
||
metadata: string;
|
||
};
|
||
const parsed = JSON.parse(row.metadata) as {
|
||
traceSteps?: Array<{ runId?: string; startedAt: number }>;
|
||
};
|
||
return parsed.traceSteps ?? [];
|
||
};
|
||
|
||
it('截断后:晚于锚点消息的 traceSteps 被过滤,早于/等于的保留', () => {
|
||
const anchorTs = 1_000_000;
|
||
const anchorId = 'm_anchor';
|
||
insertMessage('m_before', '更早的消息', anchorTs - 10_000);
|
||
insertMessage(anchorId, '锚点消息', anchorTs);
|
||
insertMessage('m_after', '锚点后的消息', anchorTs + 10_000);
|
||
|
||
saveMetadata([
|
||
{ runId: 'r_before', startedAt: anchorTs - 9_000 },
|
||
{ runId: 'r_anchor', startedAt: anchorTs }, // 锚点触发的 run(将被截)
|
||
{ runId: 'r_after', startedAt: anchorTs + 11_000 },
|
||
]);
|
||
|
||
const truncated = sessionService.truncateMessagesAfter('s_trace', anchorId, true);
|
||
expect(truncated).toBe(true);
|
||
|
||
const kept = loadMetadataSteps();
|
||
expect(kept.map((s) => s.runId)).toEqual(['r_before']);
|
||
});
|
||
|
||
it('metadata 缺失/损坏时不阻断截断主流程', () => {
|
||
db.prepare("UPDATE sessions SET metadata = 'not-json' WHERE id = ?").run('s_trace');
|
||
const anchorTs = 2_000_000;
|
||
const anchorId = 'm2';
|
||
insertMessage(anchorId, '锚点消息 2', anchorTs);
|
||
insertMessage('m2_after', '锚点 2 之后的消息', anchorTs + 1000);
|
||
|
||
expect(() => sessionService.truncateMessagesAfter('s_trace', anchorId, true)).not.toThrow();
|
||
expect(sessionService.truncateMessagesAfter('s_trace', anchorId, true)).toBe(false); // 已被上一句删过,无行可删
|
||
});
|
||
|
||
it('锚点不存在时返回 false 且不触碰 metadata', () => {
|
||
saveMetadata([{ runId: 'r_keep', startedAt: Date.now() }]);
|
||
expect(sessionService.truncateMessagesAfter('s_trace', 'm_missing', true)).toBe(false);
|
||
expect(loadMetadataSteps()).toHaveLength(1);
|
||
});
|
||
});
|