Files
metona-ai-desktop/electron/harness/tools/__tests__/registry.test.ts
T
thzxx 2230bcec3f feat: v0.4.0 四阶段迭代 — 安全加固 + 工程基线 + 架构重构 + 双 Provider 扩展
P0 安全修复:
- API Key 加密存储(safeStorage 密钥链,版本化前缀,历史明文平滑兼容)
- 间接提示注入防护(SecurityScanHook 工具结果深扫描,网络工具脱敏/本地工具警示分级)
- error:report IPC 断链修复(渲染进程错误上报落 electron-log + 审计)
- abort 信号贯通工具层(run_command/dev-tools 子进程随会话中断终止)
- run_command 沙箱加固(cd 系统目录/敏感文件读取拦截 + chcp 前缀剥离防解析退化)
- .env 真实生效(dotenv 回退加载,应用内配置优先)

P1 工程基础:
- ESLint 9 flat config + 全部 34 条存量 warnings 清零(零容忍基线)
- 测试基线 118 用例 11 文件(token/文件防护/权限/沙箱/注入/命令/引擎/注册表/审计链/摘要分层)
- test:electron 双模式(ELECTRON_RUN_AS_NODE 跑 Electron ABI,SQLite 套件全执行)
- SessionRecorder 多会话隔离 + 9 种 TRACE 事件补全(含最终轮 iteration_end)
- Provider 故障转移(重试耗尽/不可重试一次性切换 fallback + 前端通知)
- MCP 真就绪(等待全部连接完成再广播 tools:ready)
- SLO/HealthChecker 真实接入(60s 巡检 + 托盘状态)
- CONFIG_DEFAULTS 单一来源(消除 SEED 双源漂移)

P2 架构升级:
- handlers.ts 1940 行拆分为 13 个 IPC 域模块(防重入注册 + 多窗口广播)
- AgentEngineManager 每会话独立引擎(LRU 30 + adapter 工厂隔离 abort 信号)
- TaskOrchestrator EngineProvider 改造 + abortByParent 联动中断 SubAgent
- 会话摘要分层上下文(session_summaries 滚动摘要 + 截断游标清理防因果污染)
- 消息编辑重发/重新生成(truncateAfter IPC + store 动作 + UI)
- Markdown 导出 / WebSearch 并行抓取(并发 3)/ 记忆 TF 缓存 / 版本构建期注入

P3 能力扩展:
- OpenAI Adapter(o 系列推理模型 reasoning_effort/max_completion_tokens)
- Anthropic Adapter(原生 Messages API:tool_use 块/角色合并/thinking budget/图片 base64/SSE 事件机)
- 设置页/Onboarding 六 Provider 全链路接入
2026-08-20 23:17:02 +08:00

116 lines
3.8 KiB
TypeScript

/**
* ToolRegistry 单元测试(P1-14 测试基线)
* 覆盖:truncateResult 截断、未知工具错误、工具超时
*/
import { describe, it, expect } from 'vitest';
import { ToolRegistry } from '../registry';
import type { IMetonaTool, ToolExecutionContext } from '../../types/metona-tool';
function createContext(overrides?: Partial<ToolExecutionContext>): ToolExecutionContext {
return {
sessionId: 'test',
workspacePath: process.cwd(),
iteration: 1,
requestId: 'req_test',
...overrides,
};
}
describe('ToolRegistry.truncateResult', () => {
const registry = new ToolRegistry();
// 访问私有方法
const truncate = (result: unknown) =>
(registry as unknown as { truncateResult: (r: unknown) => unknown }).truncateResult(result);
it('小结果原样返回', () => {
const small = { data: 'x'.repeat(100) };
expect(truncate(small)).toBe(small);
});
it('大字符串结果被截断并附加 _truncated 标记', () => {
const big = 'a'.repeat(500_000);
const truncated = truncate(big) as { _preview: string; _original_size: number; _truncated: boolean };
expect(truncated._truncated).toBe(true);
expect(truncated._original_size).toBe(500_000);
expect(truncated._preview.length).toBeLessThan(big.length);
});
it('大对象结果被截断', () => {
const bigObj = { content: 'a'.repeat(400_000), extra: 'b'.repeat(200_000) };
const truncated = truncate(bigObj) as { _truncated: boolean };
expect(truncated._truncated).toBe(true);
});
it('view_image 的 dataUrl 白名单不截断(原对象引用返回)', () => {
const obj = { dataUrl: `data:image/png;base64,${'a'.repeat(200_000)}` };
expect(truncate(obj)).toBe(obj);
});
it('null/undefined/number 安全返回', () => {
expect(truncate(null)).toBe(null);
expect(truncate(undefined)).toBe(undefined);
expect(truncate(42)).toBe(42);
});
});
describe('ToolRegistry.execute', () => {
it('未知工具返回错误结果', async () => {
const registry = new ToolRegistry();
const result = await registry.execute(
{ id: 'tc_1', name: 'not_exist', args: {}, iteration: 1, timestamp: Date.now() },
createContext(),
);
expect(result.success).toBe(false);
expect(result.error).toContain('Unknown tool');
});
it('工具超时返回错误结果', async () => {
const registry = new ToolRegistry();
const slowTool: IMetonaTool = {
definition: {
name: 'slow_tool',
description: 'slows',
parameters: { type: 'object', properties: {} },
category: 'CODE_EXECUTION' as never,
riskLevel: 'SAFE' as never,
requiresPermission: false,
timeoutMs: 20,
},
execute: async () => {
await new Promise((r) => setTimeout(r, 200));
return 'too late';
},
};
registry.registerBuiltin(slowTool);
const result = await registry.execute(
{ id: 'tc_2', name: 'slow_tool', args: {}, iteration: 1, timestamp: Date.now() },
createContext(),
);
expect(result.success).toBe(false);
expect(result.error).toContain('timed out');
});
it('正常执行返回结果', async () => {
const registry = new ToolRegistry();
registry.registerBuiltin({
definition: {
name: 'fast_tool',
description: 'fast',
parameters: { type: 'object', properties: {} },
category: 'CODE_EXECUTION' as never,
riskLevel: 'SAFE' as never,
requiresPermission: false,
timeoutMs: 5_000,
},
execute: async () => 'done',
});
const result = await registry.execute(
{ id: 'tc_3', name: 'fast_tool', args: {}, iteration: 1, timestamp: Date.now() },
createContext(),
);
expect(result.success).toBe(true);
expect(result.result).toBe('done');
});
});