Files
metona-ai-desktop/electron/harness/agent-loop/__tests__/engine.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

165 lines
7.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* AgentLoopEngine 单元测试(P1-14 测试基线)
* 覆盖:完成终止、死循环检测、最大迭代、Provider 故障转移(P1
*/
import { describe, it, expect, vi } from 'vitest';
vi.mock('electron-log', () => ({
default: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
}));
import { AgentLoopEngine } from '../engine';
import { AgentLoopState, TerminationReason } from '../types';
import type { IMetonaProviderAdapter, MetonaResponse, MetonaStreamEvent } from '../../types';
import { MetonaStreamEventType } from '../../types';
/** 构造 Mock AdaptersendStream 按脚本产出事件 */
function createMockAdapter(scripts: MetonaStreamEvent[][], opts?: { failWith?: Error }): IMetonaProviderAdapter {
let call = 0;
return {
providerId: 'mock',
supportedModels: ['mock-model'],
supportsToolCalling: true,
supportsThinking: false,
getContextWindow: () => 1_000_000,
send: vi.fn(async (): Promise<MetonaResponse> => ({
meta: { requestId: 'r_test', provider: 'mock', model: 'mock-model', latencyMs: 1, timestamp: Date.now() },
content: 'ok',
usage: { inputTokens: 10, outputTokens: 5, totalTokens: 15 },
finishReason: 'stop' as never,
})),
sendStream: vi.fn(async function* (): AsyncIterable<MetonaStreamEvent> {
if (opts?.failWith) throw opts.failWith;
const script = scripts[call % scripts.length];
call++;
for (const ev of script) yield ev;
}),
setAbortSignal: vi.fn(),
healthCheck: async () => true,
};
}
function textDoneEvent(text: string): MetonaStreamEvent[] {
return [
{ type: MetonaStreamEventType.TEXT_DELTA, requestId: 'r1', sessionId: 's1', iteration: 1, seq: 0, timestamp: Date.now(), delta: text },
{ type: MetonaStreamEventType.DONE, requestId: 'r1', sessionId: 's1', iteration: 1, seq: 1, timestamp: Date.now() },
];
}
function toolCallEvent(name: string, args: Record<string, unknown>): MetonaStreamEvent[] {
return [
{
type: MetonaStreamEventType.TOOL_CALL_COMPLETE,
requestId: 'r1', sessionId: 's1', iteration: 1, seq: 0, timestamp: Date.now(),
toolCall: { id: 'tc_test', name, args, iteration: 1, timestamp: Date.now() },
},
{ type: MetonaStreamEventType.DONE, requestId: 'r1', sessionId: 's1', iteration: 1, seq: 1, timestamp: Date.now() },
];
}
const userMessage = { role: 'user' as const, content: 'hello', timestamp: Date.now() };
const systemPrompt = { roleDefinition: '', outputConstraints: '', safetyGuidelines: '' };
describe('AgentLoopEngine', () => {
it('无工具调用时正常完成(COMPLETED', async () => {
const adapter = createMockAdapter([textDoneEvent('final answer')]);
const engine = new AgentLoopEngine({}, adapter);
const output = await engine.runStream(userMessage, 's1', [], systemPrompt);
expect(output.terminationReason).toBe(TerminationReason.COMPLETED);
expect(output.finalAnswer).toBe('final answer');
});
it('死循环检测:连续 3 轮相同工具调用触发 DEAD_LOOP', async () => {
// 每轮都返回相同的工具调用(read_file + 相同参数)
const adapter = createMockAdapter([toolCallEvent('read_file', { file_path: 'same.ts' })]);
const engine = new AgentLoopEngine({ maxIterations: 10 }, adapter);
const deadLoopEvents: unknown[] = [];
engine.on('deadLoop', (d) => deadLoopEvents.push(d));
const output = await engine.runStream(userMessage, 's1', [], systemPrompt);
expect(output.terminationReason).toBe(TerminationReason.DEAD_LOOP);
expect(deadLoopEvents.length).toBe(1);
});
it('参数不同的相同工具不触发死循环(签名不同)', async () => {
const scripts = [
toolCallEvent('read_file', { file_path: 'a.ts' }),
toolCallEvent('read_file', { file_path: 'b.ts' }),
];
const adapter = createMockAdapter(scripts);
const engine = new AgentLoopEngine({ maxIterations: 3 }, adapter);
const output = await engine.runStream(userMessage, 's1', [], systemPrompt);
// 3 轮工具调用后达到 MAX_ITERATIONS(非 DEAD_LOOP
expect(output.terminationReason).toBe(TerminationReason.MAX_ITERATIONS);
});
it('达到最大迭代次数触发 MAX_ITERATIONS', async () => {
// 交替不同的工具调用避免死循环
const scripts = [
toolCallEvent('read_file', { file_path: 'a.ts' }),
toolCallEvent('read_file', { file_path: 'b.ts' }),
];
const adapter = createMockAdapter(scripts);
const engine = new AgentLoopEngine({ maxIterations: 2 }, adapter);
const output = await engine.runStream(userMessage, 's1', [], systemPrompt);
expect(output.terminationReason).toBe(TerminationReason.MAX_ITERATIONS);
expect(output.iterations.length).toBe(2);
});
it('状态机经过 THINKING → PARSING → OBSERVING', async () => {
const adapter = createMockAdapter([textDoneEvent('answer')]);
const engine = new AgentLoopEngine({}, adapter);
const states: string[] = [];
engine.on('stateChange', (d: { current?: string }) => {
if (d.current) states.push(d.current);
});
await engine.runStream(userMessage, 's1', [], systemPrompt);
expect(states).toContain(AgentLoopState.THINKING);
expect(states).toContain(AgentLoopState.PARSING);
expect(states).toContain(AgentLoopState.OBSERVING);
expect(states[states.length - 1]).toBe(AgentLoopState.TERMINATED);
});
it('不可重试错误直接 ERROR(无 fallback 时)', async () => {
const adapter = createMockAdapter([], { failWith: Object.assign(new Error('401 unauthorized'), { status: 401 }) });
const engine = new AgentLoopEngine({ retryCount: 0 }, adapter);
const output = await engine.runStream(userMessage, 's1', [], systemPrompt);
expect(output.terminationReason).toBe(TerminationReason.ERROR);
});
it('P1 故障转移:主 Provider 失败后切换到 fallback Provider', async () => {
// 主 adapter 每次都失败(401 不可重试)
const primary = createMockAdapter([], { failWith: Object.assign(new Error('401 invalid key'), { status: 401 }) });
// fallback 正常返回
const fallback = createMockAdapter([textDoneEvent('fallback answer')]);
const engine = new AgentLoopEngine({ retryCount: 0 }, primary);
engine.setFallbackAdapter(fallback);
const switchEvents: Array<{ from?: string; to?: string }> = [];
engine.on('providerSwitched', (d) => switchEvents.push(d));
const output = await engine.runStream(userMessage, 's1', [], systemPrompt);
expect(output.terminationReason).toBe(TerminationReason.COMPLETED);
expect(output.finalAnswer).toBe('fallback answer');
expect(switchEvents.length).toBe(1);
expect(switchEvents[0].from).toBe('mock');
expect(switchEvents[0].to).toBe('mock');
// fallback 的 sendStream 被调用
expect(fallback.sendStream).toHaveBeenCalled();
});
it('P1 故障转移仅触发一次(fallback 也失败不回切)', async () => {
const primary = createMockAdapter([], { failWith: Object.assign(new Error('401'), { status: 401 }) });
const fallback = createMockAdapter([], { failWith: Object.assign(new Error('500'), { status: 500 }) });
const engine = new AgentLoopEngine({ retryCount: 0 }, primary);
engine.setFallbackAdapter(fallback);
const output = await engine.runStream(userMessage, 's1', [], systemPrompt);
// fallback 失败 → ERROR(不回切 primary
expect(output.terminationReason).toBe(TerminationReason.ERROR);
});
});