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 零跳过
310 lines
11 KiB
TypeScript
310 lines
11 KiB
TypeScript
/**
|
||
* SessionRecorder 测试(v0.7.2 覆盖补齐 —— 此前零测试)
|
||
*
|
||
* 锁定 TRACE 层录制契约(P1-6 重构的回归防线):
|
||
* 1. startRecording 建文件并写 session_start;stopRecording 同步 flush + session_end
|
||
* 2. 多会话隔离(P1-6:每会话独立文件/seq,并发录制互不串扰)
|
||
* 3. setEnabled(false) 总开关丢弃事件(F-8 接通契约)
|
||
* 4. 缓冲上限(MAX_BUFFER_SIZE)强制同步落盘防 OOM
|
||
* 5. 事件 seq 递增与 9 类事件的载荷形状
|
||
*/
|
||
|
||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||
import { mkdtempSync, readFileSync, existsSync, rmSync, readdirSync } from 'fs';
|
||
import { join } from 'path';
|
||
import { tmpdir } from 'os';
|
||
|
||
vi.mock('electron-log', () => ({
|
||
default: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
|
||
}));
|
||
|
||
import { SessionRecorder } from '../session-recorder.service';
|
||
|
||
let wsRoot: string;
|
||
let recorder: SessionRecorder;
|
||
|
||
beforeEach(() => {
|
||
wsRoot = mkdtempSync(join(tmpdir(), 'metona-rec-'));
|
||
recorder = new SessionRecorder(wsRoot);
|
||
});
|
||
|
||
afterEach(() => {
|
||
try {
|
||
rmSync(wsRoot, { recursive: true, force: true });
|
||
} catch {
|
||
/* ignore */
|
||
}
|
||
});
|
||
|
||
function readLines(sessionId: string): Array<Record<string, unknown>> {
|
||
const dir = join(wsRoot, 'logs');
|
||
const files = readdirSync(dir) as string[];
|
||
const target = files.filter((f) => f.includes(`session_${sessionId}_`));
|
||
expect(target.length).toBeGreaterThan(0);
|
||
const content = readFileSync(join(dir, target[0]), 'utf-8');
|
||
return content
|
||
.split('\n')
|
||
.filter((l) => l.trim())
|
||
.map((l) => JSON.parse(l) as Record<string, unknown>);
|
||
}
|
||
|
||
describe('SessionRecorder — 基本录制链路', () => {
|
||
it('startRecording 会话开启后首条事件即 session_start(seq 0,经 flush 落盘)', () => {
|
||
recorder.startRecording('s1');
|
||
// 事件先进缓冲(100ms 定时 flush),stopRecording 的 flushSync 保证落盘后断言
|
||
recorder.stopRecording('s1', {
|
||
totalIterations: 0,
|
||
totalTokens: 0,
|
||
durationMs: 0,
|
||
terminationReason: 'completed',
|
||
});
|
||
const lines = readLines('s1');
|
||
expect(lines).toHaveLength(2); // session_start + session_end
|
||
expect(lines[0]).toMatchObject({ event: 'session_start', sessionId: 's1' });
|
||
expect(lines[0].ts).toBeDefined();
|
||
expect(lines[0].seq).toBe(0);
|
||
expect(lines[1].event).toBe('session_end');
|
||
});
|
||
|
||
it('stopRecording 同步 flush 全部缓冲并写 session_end(#35 契约)', () => {
|
||
recorder.startRecording('s1');
|
||
recorder.recordToolCall({
|
||
sessionId: 's1',
|
||
iteration: 1,
|
||
toolName: 'read_file',
|
||
args: { p: 'x' },
|
||
});
|
||
recorder.recordIterationStart('s1', 1);
|
||
recorder.stopRecording('s1', {
|
||
totalIterations: 1,
|
||
totalTokens: 100,
|
||
durationMs: 50,
|
||
terminationReason: 'completed',
|
||
});
|
||
|
||
const lines = readLines('s1');
|
||
const events = lines.map((l) => l.event);
|
||
expect(events).toEqual(['session_start', 'tool_call', 'iteration_start', 'session_end']);
|
||
const end = lines[lines.length - 1];
|
||
expect(end).toMatchObject({
|
||
totalIterations: 1,
|
||
totalTokens: 100,
|
||
terminationReason: 'completed',
|
||
});
|
||
});
|
||
|
||
it('事件 seq 在会话内单调递增', () => {
|
||
recorder.startRecording('s1');
|
||
recorder.recordIterationStart('s1', 1);
|
||
recorder.recordIterationStart('s1', 2);
|
||
recorder.stopRecording('s1', {
|
||
totalIterations: 2,
|
||
totalTokens: 0,
|
||
durationMs: 1,
|
||
terminationReason: 'completed',
|
||
});
|
||
|
||
// session_start(0) + iteration_start×2(1,2) + session_end(3)
|
||
const seqs = readLines('s1').map((l) => l.seq as number);
|
||
expect(seqs).toEqual([0, 1, 2, 3]);
|
||
});
|
||
|
||
it('recordLLMResponse 载荷:content 截断 200 字符', () => {
|
||
recorder.startRecording('s1');
|
||
recorder.recordLLMResponse({
|
||
sessionId: 's1',
|
||
iteration: 1,
|
||
content: 'y'.repeat(500),
|
||
finishReason: 'stop',
|
||
tokenUsage: { input: 10, output: 20, total: 30 },
|
||
});
|
||
recorder.stopRecording('s1', {
|
||
totalIterations: 1,
|
||
totalTokens: 30,
|
||
durationMs: 1,
|
||
terminationReason: 'completed',
|
||
});
|
||
|
||
const llm = readLines('s1').find((l) => l.event === 'llm_response') as Record<string, unknown>;
|
||
expect((llm.contentPreview as string).length).toBe(200);
|
||
expect(llm.tokenUsage).toEqual({ input: 10, output: 20, total: 30 });
|
||
});
|
||
|
||
it('recordToolResult 载荷:success/durationMs/resultPreview 截断 500/error', () => {
|
||
recorder.startRecording('s1');
|
||
recorder.recordToolResult({
|
||
sessionId: 's1',
|
||
iteration: 1,
|
||
toolName: 'web_fetch',
|
||
success: false,
|
||
durationMs: 42,
|
||
resultPreview: 'z'.repeat(800),
|
||
error: 'HTTP 403',
|
||
});
|
||
recorder.stopRecording('s1', {
|
||
totalIterations: 1,
|
||
totalTokens: 0,
|
||
durationMs: 1,
|
||
terminationReason: 'error',
|
||
});
|
||
|
||
const tr = readLines('s1').find((l) => l.event === 'tool_result') as Record<string, unknown>;
|
||
expect(tr.success).toBe(false);
|
||
expect(tr.durationMs).toBe(42);
|
||
expect((tr.resultPreview as string).length).toBe(500);
|
||
expect(tr.error).toBe('HTTP 403');
|
||
});
|
||
});
|
||
|
||
describe('SessionRecorder — 多会话隔离(P1-6)', () => {
|
||
it('并发录制:每会话独立文件与独立 seq,互不串扰', () => {
|
||
recorder.startRecording('s1');
|
||
recorder.startRecording('s2');
|
||
|
||
recorder.recordToolCall({ sessionId: 's1', iteration: 1, toolName: 'tool_a', args: {} });
|
||
recorder.recordToolCall({ sessionId: 's2', iteration: 1, toolName: 'tool_b', args: {} });
|
||
|
||
recorder.stopRecording('s1', {
|
||
totalIterations: 1,
|
||
totalTokens: 0,
|
||
durationMs: 1,
|
||
terminationReason: 'completed',
|
||
});
|
||
recorder.stopRecording('s2', {
|
||
totalIterations: 1,
|
||
totalTokens: 0,
|
||
durationMs: 1,
|
||
terminationReason: 'completed',
|
||
});
|
||
|
||
const s1Tools = readLines('s1').filter((l) => l.event === 'tool_call');
|
||
const s2Tools = readLines('s2').filter((l) => l.event === 'tool_call');
|
||
expect(s1Tools[0].tool).toBe('tool_a');
|
||
expect(s2Tools[0].tool).toBe('tool_b');
|
||
// seq 各自从 0 起算(s1: start=0, tool=1, end=2;s2 同构)
|
||
expect(s1Tools[0].seq).toBe(1);
|
||
expect(s2Tools[0].seq).toBe(1);
|
||
});
|
||
|
||
it('未 startRecording 的会话事件被静默丢弃', () => {
|
||
recorder.recordToolCall({ sessionId: 'ghost', iteration: 1, toolName: 'x', args: {} });
|
||
expect(recorder.getFilePath('ghost')).toBeNull();
|
||
});
|
||
|
||
it('stopRecording 幂等安全(未开始也会话状态不崩)', () => {
|
||
expect(() =>
|
||
recorder.stopRecording('ghost', {
|
||
totalIterations: 0,
|
||
totalTokens: 0,
|
||
durationMs: 0,
|
||
terminationReason: 'error',
|
||
}),
|
||
).not.toThrow();
|
||
});
|
||
});
|
||
|
||
describe('SessionRecorder — 总开关与缓冲上限', () => {
|
||
it('setEnabled(false) 后事件全部丢弃(logging.traceEnabled 契约)', () => {
|
||
recorder.setEnabled(false);
|
||
recorder.startRecording('s1');
|
||
recorder.recordToolCall({ sessionId: 's1', iteration: 1, toolName: 'x', args: {} });
|
||
recorder.stopRecording('s1', {
|
||
totalIterations: 1,
|
||
totalTokens: 0,
|
||
durationMs: 1,
|
||
terminationReason: 'completed',
|
||
});
|
||
|
||
const dir = join(wsRoot, 'logs');
|
||
const files = existsSync(dir) ? readdirSync(dir) : [];
|
||
expect(files.filter((f) => f.startsWith('session_s1_'))).toEqual([]);
|
||
});
|
||
|
||
it('缓冲超过 MAX_BUFFER_SIZE 强制同步落盘(防 OOM)', () => {
|
||
recorder.startRecording('s1');
|
||
// MAX_BUFFER_SIZE = 1000 —— 写入超限触发 flushSync(文件应提前出现在磁盘)
|
||
for (let i = 0; i < 1001; i++) {
|
||
recorder.recordIterationStart('s1', i);
|
||
}
|
||
recorder.stopRecording('s1', {
|
||
totalIterations: 1001,
|
||
totalTokens: 0,
|
||
durationMs: 1,
|
||
terminationReason: 'completed',
|
||
});
|
||
|
||
const lines = readLines('s1');
|
||
expect(lines.length).toBe(1003); // 1001 iterations + session_start + session_end
|
||
});
|
||
|
||
it('getFilePath 返回活动会话的录制文件路径;stop 后清除', () => {
|
||
recorder.startRecording('s1');
|
||
expect(recorder.getFilePath('s1')).toContain('session_s1_');
|
||
recorder.stopRecording('s1', {
|
||
totalIterations: 0,
|
||
totalTokens: 0,
|
||
durationMs: 0,
|
||
terminationReason: 'completed',
|
||
});
|
||
expect(recorder.getFilePath('s1')).toBeNull();
|
||
});
|
||
});
|
||
|
||
// ===== v0.7.3 P3-3: JSONL 录制文件生命周期(stats + prune) =====
|
||
|
||
describe('SessionRecorder — 录制文件统计与清理(P3-3)', () => {
|
||
const writeRecording = async (name: string, ageHours: number): Promise<void> => {
|
||
const fs = await import('node:fs');
|
||
const logsDir = join(wsRoot, 'logs');
|
||
if (!existsSync(logsDir)) fs.mkdirSync(logsDir, { recursive: true });
|
||
const filePath = join(logsDir, name);
|
||
fs.writeFileSync(filePath, '{"event":"session_start"}\n', 'utf-8');
|
||
const mtime = new Date(Date.now() - ageHours * 3600_000);
|
||
fs.utimesSync(filePath, mtime, mtime);
|
||
};
|
||
|
||
it('getRecordingStats:统计 count 与 totalBytes;目录不存在返回零值', async () => {
|
||
expect(recorder.getRecordingStats()).toEqual({ count: 0, totalBytes: 0 });
|
||
|
||
await writeRecording('session_s1_2026-01-01.jsonl', 1);
|
||
await writeRecording('session_s2_2026-01-02.jsonl', 2);
|
||
// 非 session_*.jsonl 命名的文件不受治理(用户自放文件)
|
||
await writeRecording('user-notes.txt', 3);
|
||
|
||
const stats = recorder.getRecordingStats();
|
||
expect(stats.count).toBe(2);
|
||
expect(stats.totalBytes).toBeGreaterThan(0);
|
||
});
|
||
|
||
it('pruneOldRecordings:按 mtime 保留最近 N 个,删除其余', async () => {
|
||
for (let i = 0; i < 6; i++) {
|
||
await writeRecording(`session_s${i}_f.jsonl`, i + 1); // s0 最旧
|
||
}
|
||
const deleted = recorder.pruneOldRecordings(3);
|
||
expect(deleted).toBe(3);
|
||
|
||
const remaining = (readdirSync(join(wsRoot, 'logs')) as string[]).filter((f) =>
|
||
f.startsWith('session_'),
|
||
);
|
||
expect(remaining).toHaveLength(3);
|
||
// 保留的应是最新的 3 个(s0/s1/s2 —— 年龄 1/2/3 小时,s0 最新)
|
||
for (const keep of ['session_s0_f.jsonl', 'session_s1_f.jsonl', 'session_s2_f.jsonl']) {
|
||
expect(remaining).toContain(keep);
|
||
}
|
||
});
|
||
|
||
it('pruneOldRecordings:仅治理 session_*.jsonl 命名,用户文件不受影响', async () => {
|
||
await writeRecording('session_a.jsonl', 100);
|
||
await writeRecording('my-data.jsonl', 100);
|
||
const deleted = recorder.pruneOldRecordings(0);
|
||
expect(deleted).toBe(1);
|
||
expect(existsSync(join(wsRoot, 'logs', 'my-data.jsonl'))).toBe(true);
|
||
});
|
||
|
||
it('pruneOldRecordings:未超限返回 0 且不删除任何文件', async () => {
|
||
await writeRecording('session_x.jsonl', 1);
|
||
expect(recorder.pruneOldRecordings(200)).toBe(0);
|
||
expect(existsSync(join(wsRoot, 'logs', 'session_x.jsonl'))).toBe(true);
|
||
});
|
||
});
|