/** * 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> { 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); } 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; 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; 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 => { 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); }); });