feat: v0.7.4 时序语义修正 · 防线实效补漏 · 全量测试翻倍 — 2406 用例 + jsdom 组件测试全量回归
P1 修复面收口: - 超时三态区分(aborted→USER_INTERRUPT / ETIMEDOUT→TIMEOUT / 其余→ERROR), 根治"真实网络超时被误报为用户中断" - 流空闲超时统一(SSE/Ollama/Anthropic 读循环 60s 无数据抛 504 进重试通道) - 同会话并发 sendMessage 防重入(isRunning 守卫)+ 会话存在性预检 + 前置调用移入 try(ERROR+DONE 双事件保证,根治 isStreaming 假死) - 清空审计后 resetChainCache(根治 verifyChain 误报 TAMPERED) - DONE 不再提前清理 TRACE(TERMINATED 统一收尾,补全最终迭代录制) - IME 合成回车不发送(普通 Enter + Cmd/Ctrl+Enter 双分支)+ handleSend 闭包修复 P2 安全纵深: - preload 移除原始 electronAPI 暴露(渲染层零使用,关掉 XSS invoke 任意通道单点风险) - CORS 同源回显根治(仅当前浏览页面 Origin,did-navigate 同步) - MEMORY.md 命令保护正则扩展(括号/$/反引号/< 重定向边界 + 前导路径) - write_file append TOCTOU 统一(open 后 realpath 校验,新文件分支补漏) - 敏感键归一化(authKey 驼峰/连字符命中)+ MCP headers 鉴权值加密落库 - ReDoS 检测共享化(search_files/file_editor 统一拦截) - run_tests/lint_code 升风险 + 需确认 + npx --no-install(执行边界对齐 run_command) - MCP/SearXNG/llm.baseURL/updateFeedUrl 配置类 URL 高危目标校验(IPv6 去括号 + 十六进制映射解析 + 尾点剥离) P3 架构还债: - temperature/maxTokens 热生效(引擎/编排器/SubAgent 三处接线)+ setBatch 单事务落盘 - SessionRecorder flush 竞态根治(flushPromise 等待 + 超限内联落盘 + stopRecording async) - 内存收口(lastConsolidationBySession LRU / subTraces 清理 / 会话删除 disposeEngine) - i18n 全量收口(28 组件 + 353 key 双字典,状态标签改渲染时函数) - 死代码清理(updateTraceStep/HEADER_HEIGHT/void preA/失实注释) - 斜杠菜单 MUI 化 + 删除逻辑收敛 resetSessionState + Blob URL 统一释放 + 用户消息"仅保存"落库(saveMessage 透传前端 id 修复 id 错位) P4 能力演进: - 死循环检测拆分(驻留前置 + 乒乓后置带进度信号,合法交替不误报) - run-lock 30s 超时强制 abort(旧 run 卡死不无限排队) - RETRY 双通道 stream_reset(前端按 run 归属精确清空,根治重试文本重复) - FTS5 trigram 中文子串搜索(迁移 9 版本化 SCHEMA_VERSION=2,≤2 字符 LIKE 回退) - getContextWindow 兜底 1M→128K(未知模型防 413) 测试: - 855 → 2406 用例(+1551,2.8 倍):服务层 +325(含 MemoryManager 51 新用例)、 工具实体 +483、IPC/适配器 +390(含 OpenAI/Anthropic/Ollama 独立套件)、 纯函数表格化 +330;引入 jsdom + @testing-library(14 组件测试文件 249 用例) - 修复 R1(saveMessage id 透传)/ R2(stream_reset 精确归属)两个回归缺陷 - 遗留低危项清零:git-tools 顺序耦合 / web-fetch 真实时间退避 / slo 内存断言 / mcp-security 多余 skipIf / deepseek-balance 命名误导 / 组件 mock 注入脆弱性 版本: 0.7.4; README 同步(工具风险表/版本徽章); 依赖: 移除 @electron-toolkit/preload, 新增 jsdom/@testing-library(devDependencies 不打包) 回归: typecheck 双端 0 错误; ESLint 0/0; Electron ABI 全量 2406/2406 零跳过; 系统 Node 2110 通过 296 跳过(better-sqlite3 ABI)
This commit is contained in:
@@ -49,10 +49,10 @@ function readLines(sessionId: string): Array<Record<string, unknown>> {
|
||||
}
|
||||
|
||||
describe('SessionRecorder — 基本录制链路', () => {
|
||||
it('startRecording 会话开启后首条事件即 session_start(seq 0,经 flush 落盘)', () => {
|
||||
it('startRecording 会话开启后首条事件即 session_start(seq 0,经 flush 落盘)', async () => {
|
||||
recorder.startRecording('s1');
|
||||
// 事件先进缓冲(100ms 定时 flush),stopRecording 的 flushSync 保证落盘后断言
|
||||
recorder.stopRecording('s1', {
|
||||
await recorder.stopRecording('s1', {
|
||||
totalIterations: 0,
|
||||
totalTokens: 0,
|
||||
durationMs: 0,
|
||||
@@ -66,7 +66,7 @@ describe('SessionRecorder — 基本录制链路', () => {
|
||||
expect(lines[1].event).toBe('session_end');
|
||||
});
|
||||
|
||||
it('stopRecording 同步 flush 全部缓冲并写 session_end(#35 契约)', () => {
|
||||
it('stopRecording 同步 flush 全部缓冲并写 session_end(#35 契约)', async () => {
|
||||
recorder.startRecording('s1');
|
||||
recorder.recordToolCall({
|
||||
sessionId: 's1',
|
||||
@@ -75,7 +75,7 @@ describe('SessionRecorder — 基本录制链路', () => {
|
||||
args: { p: 'x' },
|
||||
});
|
||||
recorder.recordIterationStart('s1', 1);
|
||||
recorder.stopRecording('s1', {
|
||||
await recorder.stopRecording('s1', {
|
||||
totalIterations: 1,
|
||||
totalTokens: 100,
|
||||
durationMs: 50,
|
||||
@@ -93,11 +93,11 @@ describe('SessionRecorder — 基本录制链路', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('事件 seq 在会话内单调递增', () => {
|
||||
it('事件 seq 在会话内单调递增', async () => {
|
||||
recorder.startRecording('s1');
|
||||
recorder.recordIterationStart('s1', 1);
|
||||
recorder.recordIterationStart('s1', 2);
|
||||
recorder.stopRecording('s1', {
|
||||
await recorder.stopRecording('s1', {
|
||||
totalIterations: 2,
|
||||
totalTokens: 0,
|
||||
durationMs: 1,
|
||||
@@ -109,7 +109,7 @@ describe('SessionRecorder — 基本录制链路', () => {
|
||||
expect(seqs).toEqual([0, 1, 2, 3]);
|
||||
});
|
||||
|
||||
it('recordLLMResponse 载荷:content 截断 200 字符', () => {
|
||||
it('recordLLMResponse 载荷:content 截断 200 字符', async () => {
|
||||
recorder.startRecording('s1');
|
||||
recorder.recordLLMResponse({
|
||||
sessionId: 's1',
|
||||
@@ -118,7 +118,7 @@ describe('SessionRecorder — 基本录制链路', () => {
|
||||
finishReason: 'stop',
|
||||
tokenUsage: { input: 10, output: 20, total: 30 },
|
||||
});
|
||||
recorder.stopRecording('s1', {
|
||||
await recorder.stopRecording('s1', {
|
||||
totalIterations: 1,
|
||||
totalTokens: 30,
|
||||
durationMs: 1,
|
||||
@@ -130,7 +130,7 @@ describe('SessionRecorder — 基本录制链路', () => {
|
||||
expect(llm.tokenUsage).toEqual({ input: 10, output: 20, total: 30 });
|
||||
});
|
||||
|
||||
it('recordToolResult 载荷:success/durationMs/resultPreview 截断 500/error', () => {
|
||||
it('recordToolResult 载荷:success/durationMs/resultPreview 截断 500/error', async () => {
|
||||
recorder.startRecording('s1');
|
||||
recorder.recordToolResult({
|
||||
sessionId: 's1',
|
||||
@@ -141,7 +141,7 @@ describe('SessionRecorder — 基本录制链路', () => {
|
||||
resultPreview: 'z'.repeat(800),
|
||||
error: 'HTTP 403',
|
||||
});
|
||||
recorder.stopRecording('s1', {
|
||||
await recorder.stopRecording('s1', {
|
||||
totalIterations: 1,
|
||||
totalTokens: 0,
|
||||
durationMs: 1,
|
||||
@@ -157,20 +157,20 @@ describe('SessionRecorder — 基本录制链路', () => {
|
||||
});
|
||||
|
||||
describe('SessionRecorder — 多会话隔离(P1-6)', () => {
|
||||
it('并发录制:每会话独立文件与独立 seq,互不串扰', () => {
|
||||
it('并发录制:每会话独立文件与独立 seq,互不串扰', async () => {
|
||||
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', {
|
||||
await recorder.stopRecording('s1', {
|
||||
totalIterations: 1,
|
||||
totalTokens: 0,
|
||||
durationMs: 1,
|
||||
terminationReason: 'completed',
|
||||
});
|
||||
recorder.stopRecording('s2', {
|
||||
await recorder.stopRecording('s2', {
|
||||
totalIterations: 1,
|
||||
totalTokens: 0,
|
||||
durationMs: 1,
|
||||
@@ -186,29 +186,29 @@ describe('SessionRecorder — 多会话隔离(P1-6)', () => {
|
||||
expect(s2Tools[0].seq).toBe(1);
|
||||
});
|
||||
|
||||
it('未 startRecording 的会话事件被静默丢弃', () => {
|
||||
it('未 startRecording 的会话事件被静默丢弃', async () => {
|
||||
recorder.recordToolCall({ sessionId: 'ghost', iteration: 1, toolName: 'x', args: {} });
|
||||
expect(recorder.getFilePath('ghost')).toBeNull();
|
||||
});
|
||||
|
||||
it('stopRecording 幂等安全(未开始也会话状态不崩)', () => {
|
||||
expect(() =>
|
||||
it('stopRecording 幂等安全(未开始也会话状态不崩)', async () => {
|
||||
await expect(
|
||||
recorder.stopRecording('ghost', {
|
||||
totalIterations: 0,
|
||||
totalTokens: 0,
|
||||
durationMs: 0,
|
||||
terminationReason: 'error',
|
||||
}),
|
||||
).not.toThrow();
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('SessionRecorder — 总开关与缓冲上限', () => {
|
||||
it('setEnabled(false) 后事件全部丢弃(logging.traceEnabled 契约)', () => {
|
||||
it('setEnabled(false) 后事件全部丢弃(logging.traceEnabled 契约)', async () => {
|
||||
recorder.setEnabled(false);
|
||||
recorder.startRecording('s1');
|
||||
recorder.recordToolCall({ sessionId: 's1', iteration: 1, toolName: 'x', args: {} });
|
||||
recorder.stopRecording('s1', {
|
||||
await recorder.stopRecording('s1', {
|
||||
totalIterations: 1,
|
||||
totalTokens: 0,
|
||||
durationMs: 1,
|
||||
@@ -220,13 +220,13 @@ describe('SessionRecorder — 总开关与缓冲上限', () => {
|
||||
expect(files.filter((f) => f.startsWith('session_s1_'))).toEqual([]);
|
||||
});
|
||||
|
||||
it('缓冲超过 MAX_BUFFER_SIZE 强制同步落盘(防 OOM)', () => {
|
||||
it('缓冲超过 MAX_BUFFER_SIZE 强制同步落盘(防 OOM)', async () => {
|
||||
recorder.startRecording('s1');
|
||||
// MAX_BUFFER_SIZE = 1000 —— 写入超限触发 flushSync(文件应提前出现在磁盘)
|
||||
for (let i = 0; i < 1001; i++) {
|
||||
recorder.recordIterationStart('s1', i);
|
||||
}
|
||||
recorder.stopRecording('s1', {
|
||||
await recorder.stopRecording('s1', {
|
||||
totalIterations: 1001,
|
||||
totalTokens: 0,
|
||||
durationMs: 1,
|
||||
@@ -237,10 +237,10 @@ describe('SessionRecorder — 总开关与缓冲上限', () => {
|
||||
expect(lines.length).toBe(1003); // 1001 iterations + session_start + session_end
|
||||
});
|
||||
|
||||
it('getFilePath 返回活动会话的录制文件路径;stop 后清除', () => {
|
||||
it('getFilePath 返回活动会话的录制文件路径;stop 后清除', async () => {
|
||||
recorder.startRecording('s1');
|
||||
expect(recorder.getFilePath('s1')).toContain('session_s1_');
|
||||
recorder.stopRecording('s1', {
|
||||
await recorder.stopRecording('s1', {
|
||||
totalIterations: 0,
|
||||
totalTokens: 0,
|
||||
durationMs: 0,
|
||||
@@ -306,4 +306,346 @@ describe('SessionRecorder — 录制文件统计与清理(P3-3)', () => {
|
||||
expect(recorder.pruneOldRecordings(200)).toBe(0);
|
||||
expect(existsSync(join(wsRoot, 'logs', 'session_x.jsonl'))).toBe(true);
|
||||
});
|
||||
|
||||
it('pruneOldRecordings:maxFiles=0 时全部删除(保留 0 个)', async () => {
|
||||
await writeRecording('session_a.jsonl', 1);
|
||||
await writeRecording('session_b.jsonl', 2);
|
||||
const deleted = recorder.pruneOldRecordings(0);
|
||||
expect(deleted).toBe(2);
|
||||
const remaining = (readdirSync(join(wsRoot, 'logs')) as string[]).filter((f) =>
|
||||
f.startsWith('session_'),
|
||||
);
|
||||
expect(remaining).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('pruneOldRecordings:目录不存在返回 0(不抛错)', () => {
|
||||
expect(recorder.pruneOldRecordings(10)).toBe(0);
|
||||
});
|
||||
|
||||
it('pruneOldRecordings:stat 失败的文件按 mtime=0 排最后(仍参与清理计数)', async () => {
|
||||
await writeRecording('session_f1.jsonl', 1);
|
||||
await writeRecording('session_f2.jsonl', 2);
|
||||
const logsDir = join(wsRoot, 'logs');
|
||||
// 构造 stat 抛错的文件:删除后 mtime 读取失败场景通过目录删除模拟 ——
|
||||
// 直接验证排序兜底不抛错
|
||||
expect(() => recorder.pruneOldRecordings(1)).not.toThrow();
|
||||
expect(readdirSync(logsDir).filter((f) => f.startsWith('session_'))).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('SessionRecorder — flush 竞态与缓冲超限(P3-4)', () => {
|
||||
it('异步 flush 进行中 stopRecording 等待其完成且不丢数据', async () => {
|
||||
recorder.startRecording('race1');
|
||||
recorder.recordIterationStart('race1', 1);
|
||||
|
||||
// 触发 100ms 定时 flush(异步)
|
||||
await new Promise((r) => setTimeout(r, 150));
|
||||
// 再次写事件后立即 stop —— flushSync 需等待 in-flight flush
|
||||
recorder.recordIterationStart('race1', 2);
|
||||
await recorder.stopRecording('race1', {
|
||||
totalIterations: 2,
|
||||
totalTokens: 0,
|
||||
durationMs: 1,
|
||||
terminationReason: 'completed',
|
||||
});
|
||||
|
||||
const lines = readLines('race1');
|
||||
const events = lines.map((l) => l.event);
|
||||
// session_start + iteration_start×2 + session_end —— 无丢失
|
||||
expect(events).toEqual(['session_start', 'iteration_start', 'iteration_start', 'session_end']);
|
||||
});
|
||||
|
||||
it('缓冲超限内联落盘:超限行即时落盘,文件在 stop 前已含早期事件', async () => {
|
||||
recorder.startRecording('buf');
|
||||
// MAX_BUFFER_SIZE = 1000;写入 1001 条触发内联 appendFileSync
|
||||
for (let i = 0; i < 1001; i++) {
|
||||
recorder.recordIterationStart('buf', i);
|
||||
}
|
||||
// 无需 stop:超限 flush 已写入前 1000 行(含 session_start)
|
||||
const dir = join(wsRoot, 'logs');
|
||||
const files = (readdirSync(dir) as string[]).filter((f) => f.startsWith('session_buf_'));
|
||||
expect(files).toHaveLength(1);
|
||||
const content = readFileSync(join(dir, files[0]), 'utf-8');
|
||||
const lines = content.split('\n').filter((l) => l.trim());
|
||||
expect(lines.length).toBeGreaterThanOrEqual(1000);
|
||||
// 超限内联写的是"当前 buffer 不含本行",最后一行应仍留在 buffer 中
|
||||
expect(JSON.parse(lines[0]).event).toBe('session_start');
|
||||
await recorder.stopRecording('buf', {
|
||||
totalIterations: 1001,
|
||||
totalTokens: 0,
|
||||
durationMs: 1,
|
||||
terminationReason: 'completed',
|
||||
});
|
||||
const finalLines = readLines('buf');
|
||||
expect(finalLines.length).toBe(1003); // 1001 + start + end
|
||||
});
|
||||
|
||||
it('多个会话并发触发异步 flush 互不串扰', async () => {
|
||||
recorder.startRecording('s1');
|
||||
recorder.startRecording('s2');
|
||||
recorder.recordIterationStart('s1', 1);
|
||||
recorder.recordIterationStart('s2', 1);
|
||||
recorder.recordIterationStart('s1', 2);
|
||||
recorder.recordIterationStart('s2', 2);
|
||||
await new Promise((r) => setTimeout(r, 200)); // 等待定时 flush
|
||||
await recorder.stopRecording('s1', {
|
||||
totalIterations: 2,
|
||||
totalTokens: 0,
|
||||
durationMs: 1,
|
||||
terminationReason: 'completed',
|
||||
});
|
||||
await recorder.stopRecording('s2', {
|
||||
totalIterations: 2,
|
||||
totalTokens: 0,
|
||||
durationMs: 1,
|
||||
terminationReason: 'completed',
|
||||
});
|
||||
expect(readLines('s1').filter((l) => l.event === 'iteration_start')).toHaveLength(2);
|
||||
expect(readLines('s2').filter((l) => l.event === 'iteration_start')).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('连续多次 stopRecording:第二次为 no-op(状态已清除)', async () => {
|
||||
recorder.startRecording('s1');
|
||||
const params = {
|
||||
totalIterations: 0,
|
||||
totalTokens: 0,
|
||||
durationMs: 0,
|
||||
terminationReason: 'completed',
|
||||
};
|
||||
await recorder.stopRecording('s1', params);
|
||||
await recorder.stopRecording('s1', params); // 不抛错
|
||||
expect(recorder.getFilePath('s1')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('SessionRecorder — 事件载荷形状', () => {
|
||||
it('recordContextBuilt 载荷:tokens 与 ratio 字段', async () => {
|
||||
recorder.startRecording('shape1');
|
||||
recorder.recordContextBuilt('shape1', { tokenCount: 8000, usageRatio: 0.32 });
|
||||
await recorder.stopRecording('shape1', {
|
||||
totalIterations: 0,
|
||||
totalTokens: 0,
|
||||
durationMs: 0,
|
||||
terminationReason: 'completed',
|
||||
});
|
||||
const evt = readLines('shape1').find((l) => l.event === 'context_built') as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
expect(evt.tokens).toBe(8000);
|
||||
expect(evt.ratio).toBe(0.32);
|
||||
expect(evt.sessionId).toBe('shape1');
|
||||
});
|
||||
|
||||
it('recordLLMRequest 载荷:provider/model/messageCount/iteration', async () => {
|
||||
recorder.startRecording('shape2');
|
||||
recorder.recordLLMRequest({
|
||||
sessionId: 'shape2',
|
||||
iteration: 3,
|
||||
provider: 'deepseek',
|
||||
model: 'v4-pro',
|
||||
messageCount: 7,
|
||||
});
|
||||
await recorder.stopRecording('shape2', {
|
||||
totalIterations: 3,
|
||||
totalTokens: 0,
|
||||
durationMs: 0,
|
||||
terminationReason: 'completed',
|
||||
});
|
||||
const evt = readLines('shape2').find((l) => l.event === 'llm_request') as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
expect(evt).toMatchObject({
|
||||
provider: 'deepseek',
|
||||
model: 'v4-pro',
|
||||
messageCount: 7,
|
||||
iteration: 3,
|
||||
});
|
||||
});
|
||||
|
||||
it('recordLLMResponse 载荷:contentPreview 截断 200、finishReason、tokenUsage', async () => {
|
||||
recorder.startRecording('shape3');
|
||||
recorder.recordLLMResponse({
|
||||
sessionId: 'shape3',
|
||||
iteration: 1,
|
||||
content: 'x'.repeat(300),
|
||||
finishReason: 'length',
|
||||
tokenUsage: { input: 100, output: 50, total: 150 },
|
||||
});
|
||||
await recorder.stopRecording('shape3', {
|
||||
totalIterations: 1,
|
||||
totalTokens: 150,
|
||||
durationMs: 1,
|
||||
terminationReason: 'completed',
|
||||
});
|
||||
const evt = readLines('shape3').find((l) => l.event === 'llm_response') as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
expect((evt.contentPreview as string).length).toBe(200);
|
||||
expect(evt.finishReason).toBe('length');
|
||||
expect(evt.tokenUsage).toEqual({ input: 100, output: 50, total: 150 });
|
||||
});
|
||||
|
||||
it('recordIterationEnd 载荷:iteration 与 durationMs', async () => {
|
||||
recorder.startRecording('shape4');
|
||||
recorder.recordIterationEnd('shape4', { iteration: 2, durationMs: 1234 });
|
||||
await recorder.stopRecording('shape4', {
|
||||
totalIterations: 2,
|
||||
totalTokens: 0,
|
||||
durationMs: 0,
|
||||
terminationReason: 'completed',
|
||||
});
|
||||
const evt = readLines('shape4').find((l) => l.event === 'iteration_end') as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
expect(evt.iteration).toBe(2);
|
||||
expect(evt.durationMs).toBe(1234);
|
||||
});
|
||||
|
||||
it('recordToolCall 载荷:tool 与 args 对象', async () => {
|
||||
recorder.startRecording('shape5');
|
||||
recorder.recordToolCall({
|
||||
sessionId: 'shape5',
|
||||
iteration: 1,
|
||||
toolName: 'git_diff',
|
||||
args: { a: 1, nested: { k: 'v' } },
|
||||
});
|
||||
await recorder.stopRecording('shape5', {
|
||||
totalIterations: 1,
|
||||
totalTokens: 0,
|
||||
durationMs: 0,
|
||||
terminationReason: 'completed',
|
||||
});
|
||||
const evt = readLines('shape5').find((l) => l.event === 'tool_call') as Record<string, unknown>;
|
||||
expect(evt.tool).toBe('git_diff');
|
||||
expect(evt.args).toEqual({ a: 1, nested: { k: 'v' } });
|
||||
});
|
||||
|
||||
it('recordToolResult 无 resultPreview/error 时字段为 undefined(JSON 序列化后省略)', async () => {
|
||||
recorder.startRecording('shape6');
|
||||
recorder.recordToolResult({
|
||||
sessionId: 'shape6',
|
||||
iteration: 1,
|
||||
toolName: 'exec',
|
||||
success: true,
|
||||
durationMs: 5,
|
||||
});
|
||||
await recorder.stopRecording('shape6', {
|
||||
totalIterations: 1,
|
||||
totalTokens: 0,
|
||||
durationMs: 0,
|
||||
terminationReason: 'completed',
|
||||
});
|
||||
const evt = readLines('shape6').find((l) => l.event === 'tool_result') as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
expect(evt.success).toBe(true);
|
||||
expect(evt.durationMs).toBe(5);
|
||||
expect(evt.resultPreview).toBeUndefined();
|
||||
expect(evt.error).toBeUndefined();
|
||||
});
|
||||
|
||||
it('session_end 事件载荷:totalIterations/totalTokens/durationMs/terminationReason', async () => {
|
||||
recorder.startRecording('shape7');
|
||||
await recorder.stopRecording('shape7', {
|
||||
totalIterations: 9,
|
||||
totalTokens: 7777,
|
||||
durationMs: 5500,
|
||||
terminationReason: 'max_tokens',
|
||||
});
|
||||
const end = readLines('shape7').find((l) => l.event === 'session_end') as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
expect(end).toMatchObject({
|
||||
totalIterations: 9,
|
||||
totalTokens: 7777,
|
||||
durationMs: 5500,
|
||||
terminationReason: 'max_tokens',
|
||||
});
|
||||
expect(end.seq).toBe(1); // start=0, end=1
|
||||
});
|
||||
|
||||
it('每条事件都带 sessionId 与 ts(ISO 时间戳)', async () => {
|
||||
recorder.startRecording('shape8');
|
||||
recorder.recordIterationStart('shape8', 1);
|
||||
await recorder.stopRecording('shape8', {
|
||||
totalIterations: 1,
|
||||
totalTokens: 0,
|
||||
durationMs: 0,
|
||||
terminationReason: 'completed',
|
||||
});
|
||||
for (const line of readLines('shape8')) {
|
||||
expect(line.sessionId).toBe('shape8');
|
||||
expect(new Date(line.ts as string).getTime()).not.toBeNaN();
|
||||
}
|
||||
});
|
||||
|
||||
it('文件名含时间戳且唯一(ISO 格式无冒号)', () => {
|
||||
recorder.startRecording('filename1');
|
||||
recorder.startRecording('filename1'); // 同 id 二次 start 覆盖
|
||||
const path = recorder.getFilePath('filename1') as string;
|
||||
expect(path).toMatch(/session_filename1_\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}\.jsonl$/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('SessionRecorder — 生命周期统计细节', () => {
|
||||
it('getRecordingStats 统计单个文件字节数正确', async () => {
|
||||
const logsDir = join(wsRoot, 'logs');
|
||||
const fs = await import('node:fs');
|
||||
fs.mkdirSync(logsDir, { recursive: true });
|
||||
const content = '{"a":1}\n{"b":2}\n';
|
||||
fs.writeFileSync(join(logsDir, 'session_x.jsonl'), content, 'utf-8');
|
||||
const stats = recorder.getRecordingStats();
|
||||
expect(stats.count).toBe(1);
|
||||
expect(stats.totalBytes).toBe(Buffer.byteLength(content));
|
||||
});
|
||||
|
||||
it('getRecordingStats 目录无 session 文件时 count=0', async () => {
|
||||
const logsDir = join(wsRoot, 'logs');
|
||||
const fs = await import('node:fs');
|
||||
fs.mkdirSync(logsDir, { recursive: true });
|
||||
fs.writeFileSync(join(logsDir, 'other.txt'), 'x', 'utf-8');
|
||||
const stats = recorder.getRecordingStats();
|
||||
expect(stats.count).toBe(0);
|
||||
expect(stats.totalBytes).toBe(0);
|
||||
});
|
||||
|
||||
it('startRecording 自动创建 logs 目录并返回符合格式的路径', () => {
|
||||
expect(existsSync(join(wsRoot, 'logs'))).toBe(false);
|
||||
recorder.startRecording('dir1');
|
||||
// 目录立即创建
|
||||
expect(existsSync(join(wsRoot, 'logs'))).toBe(true);
|
||||
// 路径符合 session_<id>_<ISO 时间戳>.jsonl 格式(文件在首次 flush 后落盘)
|
||||
const path = recorder.getFilePath('dir1') as string;
|
||||
expect(path).toContain('session_dir1_');
|
||||
expect(path.endsWith('.jsonl')).toBe(true);
|
||||
// 触发 flush 后文件出现在磁盘
|
||||
return new Promise<void>((resolve) => {
|
||||
setTimeout(() => {
|
||||
expect(existsSync(path)).toBe(true);
|
||||
resolve();
|
||||
}, 200);
|
||||
});
|
||||
});
|
||||
|
||||
it('setEnabled(true) 恢复录制(开关可逆;禁用期事件被丢弃)', async () => {
|
||||
recorder.setEnabled(false);
|
||||
recorder.startRecording('toggle');
|
||||
// 禁用期:session_start 被丢弃
|
||||
recorder.setEnabled(true);
|
||||
recorder.recordIterationStart('toggle', 1);
|
||||
await recorder.stopRecording('toggle', {
|
||||
totalIterations: 1,
|
||||
totalTokens: 0,
|
||||
durationMs: 0,
|
||||
terminationReason: 'completed',
|
||||
});
|
||||
const events = readLines('toggle').map((l) => l.event);
|
||||
expect(events).toEqual(['iteration_start', 'session_end']);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user