P1 修复面收口: /clear 全链路根治(前端清空联动 DB messages+摘要游标+TRACE 快照, IPC 语义改"操作完成"; 流式中拒绝); web_browser open 补 SSRF 校验(Chromium 旁路关闭, 与 web_fetch/http_request 同源 validateSSRF); MCP 工具结果纳入注入扫描(mcp_* 前缀 按网络来源同级 full 模式, 收敛 resolveScanMode 单点); Trace 落库/入 store 双重瘦身 (tool_result base64/超长字段剥离, metadata 防 MB 级膨胀); 文本附件 512KB 闸门 (file.slice 首段读取+truncated 标志随消息持久化+主进程附件提示感知截断); 单实例锁(requestSingleInstanceLock + second-instance 聚焦已有窗口) P2 安全纵深: ConfirmationHook 多窗口化(确认请求/超时提示改全窗口广播, getAllWindows 空时回退 mainWindow, fail-closed 判定升级双通道); mcp_servers.headers 全链路接线(safeParseHeaders 容错解析+SSE/StreamableHTTP requestInit 注入+IPC 逐项 校验+设置页 JSON 输入, 远程 MCP 鉴权头可用) P3 断链接线: llm:listModels IPC(六家 adapter 动态模型发现首次接线, 配置完整性 前置校验); Ollama pullModel IPC+设置页下载卡片(进度/取消/能力徽标, v0.7.0 死代码 激活); 后台会话运行指示(sessionRunStates 图+Sidebar 状态点, 多会话并发可见); IR 卫生(移除 THINKING_START/END 死枚举, constraints 标注预留) P4 质量与文档: i18n 第二阶段(确认弹框/侧栏/状态栏/AgentMonitor/终止原因出层, 外观设置 zh-CN/en-US 切换, ui.locale 持久化, 渲染时求值规避异步注册); README/D1 文档对齐(http_request 风险等级/用例数/实现状态注记); 版本号 0.7.2 测试: 507 → 737 用例(+230, 11 个新文件)。覆盖补齐: context-builder/consolidator/ orchestrator/workspace.service/session-recorder/config-layering/secure-config/ network-proxy + IPC mcp/tasks/memory/app/data 域 + 渲染层 store 与流事件管线纯函数。 测试驱动修复: workspace.appendMemory 中文分区 \b 词边界失效(JS \b 不含 CJK), 固化条目恒追加文件末尾产生重复分区头 → (?=\n|$) 前瞻断言根治 回归: typecheck 双端 0 错误; ESLint 0/0; 系统 Node 687 通过 50 跳过; Electron ABI 全量 737/737 零跳过
252 lines
8.2 KiB
TypeScript
252 lines
8.2 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();
|
||
});
|
||
});
|