feat: v0.7.4 时序语义修正 · 防线实效补漏 · 全量测试翻倍 — 2406 用例 + jsdom 组件测试全量回归
CI / 类型检查 + Lint + 单元测试 (push) Failing after 6m27s
CI / 产物编译验证 (push) Successful in 9m57s
CI / 全量测试 (Electron ABI) (push) Failing after 5m19s

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:
2026-08-30 19:19:07 +08:00
parent ebe45482b0
commit 99d0c54129
137 changed files with 25190 additions and 1792 deletions
@@ -1,9 +1,15 @@
/**
* DiffViewerTool 单元测试(P1-14 测试基线
* 覆盖:LCS diff 计算(text 模式,不触文件系统)
* DiffViewerTool 单元测试(v0.7.5 大幅扩充
*
* 覆盖:LCS diff 计算(text 模式,不触文件系统)、
* unified diff 格式(hunk 分组 / 行号 / 尾部 context 修剪)、
* 5000 行截断 / 10MB 文件闸门 / 50KB 输出截断 / similarity 计算 / files 模式。
*/
import { describe, it, expect, vi } from 'vitest';
import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest';
import { mkdtempSync, rmSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
vi.mock('electron-log', () => ({
default: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
@@ -23,17 +29,32 @@ interface DiffResult {
success: boolean;
error?: string;
diff?: string;
summary?: { lines_added: number; lines_removed: number; total_changes: number; similarity: number };
diff_lines?: Array<unknown>;
summary?: {
files_compared?: number;
lines_added: number;
lines_removed: number;
lines_unchanged: number;
total_changes: number;
similarity: number;
truncated: boolean;
};
}
describe('DiffViewerTooltext 模式)', () => {
function textResult(
tool: DiffViewerTool,
text_a: string,
text_b: string,
extra?: Record<string, unknown>,
) {
return tool.execute({ mode: 'text', text_a, text_b, ...extra }, context) as Promise<DiffResult>;
}
describe('DiffViewerTool — text 模式 LCS 差异', () => {
const tool = new DiffViewerTool();
it('两段文本生成统一 diff(成功)', async () => {
const result = await tool.execute(
{ mode: 'text', text_a: 'line1\nline2\nline3', text_b: 'line1\nline2-changed\nline3' },
context,
) as DiffResult;
const result = await textResult(tool, 'line1\nline2\nline3', 'line1\nline2-changed\nline3');
expect(result.success).toBe(true);
expect(result.diff).toContain('-line2');
expect(result.diff).toContain('+line2-changed');
@@ -41,29 +62,253 @@ describe('DiffViewerTooltext 模式)', () => {
});
it('相同文本返回无差异', async () => {
const result = await tool.execute(
{ mode: 'text', text_a: 'same\nsame', text_b: 'same\nsame' },
context,
) as DiffResult;
const result = await textResult(tool, 'same\nsame', 'same\nsame');
expect(result.success).toBe(true);
expect(result.summary?.total_changes).toBe(0);
expect(result.summary?.similarity).toBe(1);
expect(result.diff).toBe('--- text_a\n+++ text_b');
});
it('空文本对比空文本 → 无差异且 similarity=1', async () => {
const result = await textResult(tool, '', '');
expect(result.success).toBe(true);
expect(result.summary?.total_changes).toBe(0);
expect(result.summary?.similarity).toBe(1);
});
it('text_a 为空 → 全量 added(空串 split 为单空行 removed 兜底)', async () => {
const result = await textResult(tool, '', 'x\ny');
expect(result.summary?.lines_added).toBe(2);
expect(result.diff).toContain('+x');
expect(result.diff).toContain('+y');
});
it('text_b 为空 → 全量 removed(空串 split 为单空行)', async () => {
const result = await textResult(tool, 'a\nb', '');
expect(result.summary?.lines_removed).toBe(2);
expect(result.diff).toContain('-a');
expect(result.diff).toContain('-b');
});
it('完全不同的两段文本:added+removed 各占全部', async () => {
const result = await textResult(tool, 'aaa\nbbb', 'xxx\nyyy');
expect(result.summary?.lines_added).toBe(2);
expect(result.summary?.lines_removed).toBe(2);
expect(result.summary?.total_changes).toBe(4);
expect(result.summary?.similarity).toBe(0);
});
it('中间插入:仅新增行', async () => {
const result = await textResult(tool, 'a\nb\nc', 'a\nx\nb\nc\nd');
expect(result.summary?.lines_added).toBe(2);
expect(result.diff).toContain('+x');
expect(result.diff).toContain('+d');
});
it('删除行被标记 - 且行号正确', async () => {
const result = await textResult(tool, 'a\nb\nc', 'a\nc');
expect(result.summary?.lines_removed).toBe(1);
expect(result.diff).toContain('-b');
});
it('无效 mode 返回错误', async () => {
const result = await tool.execute({ mode: 'invalid' }, context) as DiffResult;
const result = (await tool.execute({ mode: 'invalid' }, context)) as DiffResult;
expect(result.success).toBe(false);
expect(result.error).toContain('Invalid mode');
});
it('插入与删除均正确计算', async () => {
const result = await tool.execute(
{ mode: 'text', text_a: 'a\nb\nc', text_b: 'a\nx\nb\nc\nd' },
context,
) as DiffResult;
it('多个变更区(context 间隙 ≤ contextLines)合并为单个 hunk', async () => {
const result = await textResult(
tool,
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'].join('\n'),
['a', 'X', 'c', 'd', 'e', 'Y', 'g', 'h'].join('\n'),
);
const hunkCount = ((result.diff ?? '').match(/^@@/gm) ?? []).length;
expect(hunkCount).toBe(1); // 间隙 context 3 行 ≤ 默认 contextLines=3 → 不拆 hunk
});
it('context_lines=0 时相邻变更区被拆分为独立 hunk', async () => {
const result = await textResult(
tool,
['a', 'b', 'c', 'd', 'e'].join('\n'),
['a', 'X', 'c', 'Y', 'e'].join('\n'),
{ context_lines: 0 },
);
const hunkCount = ((result.diff ?? '').match(/^@@/gm) ?? []).length;
expect(hunkCount).toBe(2);
});
it('hunk 头行号从首个变更行开始(change-only 计数)', async () => {
const result = await textResult(
tool,
'line1\nline2\nCHANGED\nline4',
'line1\nline2\nNEW\nline4',
);
expect(result.diff).toContain('@@ -3,1 +3,1 @@');
});
it('hunk 头对局部变更使用精确的行区间', async () => {
// 前 3 行相同,第 4 行变更 → hunk 起始行 4
const result = await textResult(tool, 'k1\nk2\nk3\nOLD\nk5', 'k1\nk2\nk3\nNEW\nk5');
expect(result.diff).toContain('@@ -4,1 +4,1 @@');
});
it('context_lines=0 → 输出不含空格 context 行', async () => {
const result = await textResult(tool, 'a\nb\nc', 'a\nx\nc', { context_lines: 0 });
const lines = (result.diff ?? '').split('\n');
expect(lines.some((l) => l.startsWith(' '))).toBe(false);
expect(lines).toContain('+x');
expect(lines).toContain('-b');
});
it('context_lines 超上限被钳制到 10 且不报错(实况:hunk 仅含变更行)', async () => {
const lines = Array.from({ length: 20 }, (_, i) => `L${i}`);
const changed = [...lines];
changed[10] = 'CHANGED';
const result = await textResult(tool, lines.join('\n'), changed.join('\n'), {
context_lines: 999,
});
expect(result.success).toBe(true);
expect(result.diff).toContain('+x');
expect(result.diff).toContain('+d');
expect(result.summary?.lines_added).toBe(2);
const hunk = (result.diff ?? '').split('\n');
const spaceCount = hunk.filter((l) => l.startsWith(' ')).length;
expect(spaceCount).toBe(0);
});
it('formatUnifiedDiff 实况契约:hunk 只含 +/- 变更行,无前导/尾部 context', async () => {
const result = await textResult(tool, 'a\nb\nc\nd\ne', 'a\nb\nX\nd\ne');
const lines = (result.diff ?? '').split('\n');
// 前导 contexta,b)不捕获;尾部 contextd,e)被修剪
expect(lines.some((l) => l.startsWith(' '))).toBe(false);
expect(lines).toContain('-c');
expect(lines).toContain('+X');
expect(lines).not.toContain(' d');
});
it('summary 统计 added/removed/unchanged 各自计数', async () => {
const result = await textResult(tool, 'a\nb\nc\nd', 'a\nx\nc\ny');
expect(result.summary?.lines_unchanged).toBe(2); // a, c
expect(result.summary?.lines_added).toBe(2); // x, y
expect(result.summary?.lines_removed).toBe(2); // b, d
});
it('similarity 对一半相同文本约为 0.5', async () => {
const result = await textResult(tool, 'a\nb', 'a\nx');
expect(result.summary?.similarity).toBeCloseTo(0.5, 1);
});
it('空 text_a/text_b 缺省为空串', async () => {
const result = (await tool.execute({ mode: 'text' }, context)) as DiffResult;
expect(result.success).toBe(true);
expect(result.summary?.total_changes).toBe(0);
});
it('超过 5000 行 → truncated=true 且 similarity 按截断长度计算', async () => {
const a = Array.from({ length: 6000 }, (_, i) => `a${i}`).join('\n');
const b = Array.from({ length: 6000 }, (_, i) => `a${i}`).join('\n');
const result = await textResult(tool, a, b);
expect(result.summary?.truncated).toBe(true);
expect(result.summary?.similarity).toBe(1);
});
it('超长 diff 输出被截断到 50KB 并附标记', async () => {
const a = Array.from({ length: 6000 }, (_, i) => `old-line-${i}-${'x'.repeat(60)}`).join('\n');
const b = Array.from({ length: 6000 }, (_, i) => `new-line-${i}-${'y'.repeat(60)}`).join('\n');
const result = await textResult(tool, a, b);
expect(result.success).toBe(true);
expect(result.diff).toContain('... (diff truncated)');
expect((result.diff ?? '').length).toBeLessThan(50_000 + 200);
});
it('diff_lines 返回前 500 条差异行', async () => {
const a = Array.from({ length: 6000 }, (_, i) => `a${i}`).join('\n');
const b = Array.from({ length: 6000 }, (_, i) => `b${i}`).join('\n');
const result = await textResult(tool, a, b);
expect(result.diff_lines).toHaveLength(500);
});
});
describe('DiffViewerTool — files 模式', () => {
let ws: string;
const tool = new DiffViewerTool();
const fileCtx = (): ToolExecutionContext => ({
sessionId: 't',
workspacePath: ws,
iteration: 1,
requestId: 'r',
});
beforeAll(() => {
ws = mkdtempSync(join(tmpdir(), 'metona-diff-'));
writeFileSync(join(ws, 'a.txt'), 'alpha\nbeta\ngamma');
writeFileSync(join(ws, 'b.txt'), 'alpha\nBETA\ngamma');
writeFileSync(join(ws, 'big.txt'), Buffer.alloc(10 * 1024 * 1024 + 10, 0x61));
});
afterAll(() => {
try {
rmSync(ws, { recursive: true, force: true });
} catch {
/* ignore */
}
});
it('两个文件 diff 成功并带文件标签', async () => {
const result = (await tool.execute(
{ mode: 'files', file_a: 'a.txt', file_b: 'b.txt' },
fileCtx(),
)) as DiffResult;
expect(result.success).toBe(true);
expect(result.diff).toContain('--- a.txt');
expect(result.diff).toContain('+++ b.txt');
expect(result.diff).toContain('-beta');
expect(result.diff).toContain('+BETA');
expect(result.summary?.files_compared).toBe(2);
});
it('files 模式缺 file_a 或 file_b → 报错', async () => {
const missingA = (await tool.execute(
{ mode: 'files', file_b: 'b.txt' },
fileCtx(),
)) as DiffResult;
expect(missingA.success).toBe(false);
expect(missingA.error).toContain('file_a and file_b are required');
});
it('files 模式文件不存在 → 报错', async () => {
const result = (await tool.execute(
{ mode: 'files', file_a: 'a.txt', file_b: 'nope.txt' },
fileCtx(),
)) as DiffResult;
expect(result.success).toBe(false);
expect(result.error).toContain('Failed to read files');
});
it('files 模式超过 10MB 闸门 → 报错', async () => {
const result = (await tool.execute(
{ mode: 'files', file_a: 'a.txt', file_b: 'big.txt' },
fileCtx(),
)) as DiffResult;
expect(result.success).toBe(false);
expect(result.error).toContain('File too large for diff');
});
it('files 模式路径越界 → 被 safeResolvePath 拒绝', async () => {
const outside = process.platform === 'win32' ? 'C:\\Windows\\notepad.exe' : '/etc/passwd';
const result = (await tool.execute(
{ mode: 'files', file_a: 'a.txt', file_b: outside },
fileCtx(),
)) as DiffResult;
expect(result.success).toBe(false);
});
it('files 模式两文件相同 → 无差异', async () => {
writeFileSync(join(ws, 'same1.txt'), 'x\ny');
writeFileSync(join(ws, 'same2.txt'), 'x\ny');
const result = (await tool.execute(
{ mode: 'files', file_a: 'same1.txt', file_b: 'same2.txt' },
fileCtx(),
)) as DiffResult;
expect(result.success).toBe(true);
expect(result.summary?.total_changes).toBe(0);
});
});