Files
metona-ai-desktop/electron/harness/hooks/__tests__/confirmation-hook.test.ts
T
thzxx 7e8b4882a0
CI / 类型检查 + Lint + 单元测试 (push) Failing after 5m38s
CI / 产物编译验证 (push) Successful in 10m15s
CI / 全量测试 (Electron ABI) (push) Failing after 5m27s
feat: v0.5.0 审计修复版 — 类型基线重建 + 会话隔离 + SubAgent 可观测性 + 三项功能补全
P0 安全与工程基线(止血):
- .npmrc 移除硬编码 Gitea npm 凭据,改为 GITEA_NPM_AUTH 环境变量注入(已验证未设变量时 401)
- 修复 typecheck 空操作缺陷:solution-style 根 tsconfig 改为双工程真检查(node + web),
  pre-commit 与 CI 门禁恢复拦截能力
- 修复 4 处 v0.4.1 遗留类型错误:confirmation-hook.test 枚举名 FILE_SYSTEM→FILESYSTEM、
  agent.ts VALIDATION 事件 severity 类型谓词收窄、ContextMenu.tsx 导出 attachments 类型
- 补装 v0.4.1 声明但未安装的 node-html-parser 依赖

P1 逻辑缺陷修复(跨模块边界):
- ConfirmationHook 会话隔离:rememberedDecisions 与 pendingConfirmations 按 sessionId 隔离,
  abortSession 只清本会话 pending(修复 A 会话中断误杀 B 会话确认、拒绝记忆跨会话污染)
- SubAgent 可观测性:orchestrator 六个事件此前全项目零消费者,现接入
  ① subagent:event 生命周期广播(AgentMonitor 新增 SubAgent 状态区)
  ② SubEngine 流事件独立 TRACE 录制(sessionId=taskId 的 JSONL 文件)
- main.ts 启动链路异常兜底:初始化失败时记录日志 + 系统错误对话框 + 退出(原为白屏挂起)

P2 工程强化:
- CI:typecheck 双工程真检查;electron-test 从 experimental(continue-on-error)转正为阻塞门禁;
  GITEA_NPM_AUTH secret 注入说明
- 渲染 bundle 代码分割:单 2630KB chunk 拆为 main 557KB + vendor-react/mui/markdown/icons
  (业务代码变更不再使 vendor 缓存失效)
- database 建表 mcp_servers CHECK 直接含 streamable-http(新库不再依赖迁移 6 立即重建)

P3 功能补全:
- DeepSeek 余额显示:新增 llm:getBalance IPC + LLMSettings 余额卡片(复用适配器原死代码 getBalance)
- FTS5 会话内容搜索:messages_fts 虚表 + INSERT/UPDATE/DELETE 触发器实时同步 +
  存量库 rebuild 迁移 + sessions:searchContent IPC + Sidebar 搜索框标题∪内容联合搜索
  (短语转义防 FTS 运算符注入,按会话聚合展示 snippet)
- 审计日志导出:audit:export IPC(JSONL / CSV RFC 4180 转义)+ LogsSettings 导出按钮

文档一致性大扫除:
- README:工具数统一为 28(原 26/27/30 三口径)、handlers.ts→ipc/、录制事件名更正、
  删除虚构的审计导出/归档宣称与 Schema 虚构字段、MCP 三种传输、配置 key 更正、
  项目结构树对齐实际(settings 10 文件/lib 6 文件/react-virtuoso)、clone 地址改为 Gitea、
  新增 GITEA_NPM_AUTH 配置说明、测试数 207
- 架构/构建指南/UI UX/IR 标准 4 份 HTML 设计文档同步修正(工具数、表数 10、
  磁盘文件 2 个现状注记、ipc/*.ts 路径)
- eslint.config.js 与开发规范.md 注释对齐零容忍基线与 better-sqlite3 选型

测试: 199→207 用例(新增 ConfirmationHook 跨会话隔离 5 用例 + FTS5 搜索/审计导出 8 用例)
验证: lint 0 problems / typecheck 双工程 0 errors / test:electron 207 全过 / build 成功
2026-08-21 21:07:01 +08:00

425 lines
17 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.
/**
* ConfirmationHook 单元测试(v0.4.1 测试补齐)
* 覆盖:自动执行放行、会话内记忆(批准/拒绝)、拒绝记忆 TTL 过期、
* 超时拒绝、用户批准、批量审批、pending 管理、恢复询问接口
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import type { BrowserWindow } from 'electron';
import { ConfirmationHook } from '../confirmation-hook';
import type { MetonaToolCall, MetonaToolDef } from '../../types';
import { MetonaToolCategory, MetonaRiskLevel } from '../../types';
/** 需要确认的高风险工具定义 */
const HIGH_RISK_DEF: MetonaToolDef = {
name: 'run_command',
description: 'Execute shell command (test fixture)',
parameters: { type: 'object', properties: {}, required: [] },
category: MetonaToolCategory.CODE_EXECUTION,
riskLevel: MetonaRiskLevel.HIGH,
requiresPermission: true,
timeoutMs: 1_000,
};
/** 低风险工具定义(无需确认) */
const SAFE_DEF: MetonaToolDef = {
name: 'read_file',
description: 'Read file (test fixture)',
parameters: { type: 'object', properties: {}, required: [] },
category: MetonaToolCategory.FILESYSTEM,
riskLevel: MetonaRiskLevel.SAFE,
requiresPermission: false,
timeoutMs: 1_000,
};
/** 第二个需确认的高风险工具(用于记忆互不干扰的测试) */
const HIGH_RISK_DEF_2: MetonaToolDef = {
name: 'delete_file',
description: 'Delete file (test fixture)',
parameters: { type: 'object', properties: {}, required: [] },
category: MetonaToolCategory.FILESYSTEM,
riskLevel: MetonaRiskLevel.HIGH,
requiresPermission: true,
timeoutMs: 1_000,
};
let idCounter = 0;
function makeToolCall(name = 'run_command'): MetonaToolCall {
return {
id: `tc_${++idCounter}`,
name,
args: { command: 'ls' },
iteration: 1,
timestamp: Date.now(),
};
}
function makeMockWindow(): BrowserWindow {
return {
isDestroyed: () => false,
webContents: { send: vi.fn() },
} as unknown as BrowserWindow;
}
describe('ConfirmationHook — 免确认路径', () => {
it('未注册工具定义时放行(由 ToolRegistry 处理未知工具错误)', async () => {
const hook = new ConfirmationHook(null, null);
const result = await hook.beforeExecute(makeToolCall('unknown_tool'), 'sess');
expect(result.blocked).toBe(false);
});
it('无需确认的工具直接放行', async () => {
const hook = new ConfirmationHook(null, null);
hook.setToolDefs([SAFE_DEF]);
const result = await hook.beforeExecute(makeToolCall('read_file'), 'sess');
expect(result.blocked).toBe(false);
});
it('持久化自动执行(autoExecute)的工具放行', async () => {
const hook = new ConfirmationHook(null, null);
hook.setToolDefs([HIGH_RISK_DEF]);
hook.setAutoExecute('run_command', true);
const result = await hook.beforeExecute(makeToolCall(), 'sess');
expect(result.blocked).toBe(false);
expect(hook.getAutoExecuteList()).toContain('run_command');
});
it('记住批准(remember approved)后同会话放行', async () => {
const hook = new ConfirmationHook(makeMockWindow(), null);
hook.setToolDefs([HIGH_RISK_DEF]);
// 第一次调用 → 等待确认 → 用户批准并记住
const p1 = hook.beforeExecute(makeToolCall(), 'sess');
const pending = hook.getPendingConfirmations();
expect(pending).toHaveLength(1);
hook.resolveConfirmation(pending[0].toolCallId, true, true, false);
expect((await p1).blocked).toBe(false);
// 第二次调用 — 记住的批准直接放行
const result = await hook.beforeExecute(makeToolCall(), 'sess');
expect(result.blocked).toBe(false);
});
});
describe('ConfirmationHook — 拒绝与阻断', () => {
it('记住拒绝后同会话阻断(reason 含 previously denied', async () => {
const hook = new ConfirmationHook(makeMockWindow(), null);
hook.setToolDefs([HIGH_RISK_DEF]);
const p1 = hook.beforeExecute(makeToolCall(), 'sess');
const pending = hook.getPendingConfirmations();
hook.resolveConfirmation(pending[0].toolCallId, false, true, false);
expect((await p1).blocked).toBe(true);
const result = await hook.beforeExecute(makeToolCall(), 'sess');
expect(result.blocked).toBe(true);
expect(result.reason).toContain('previously denied');
});
it('拒绝记忆 TTL 过期后恢复询问(v0.4.1', async () => {
vi.useFakeTimers();
try {
const hook = new ConfirmationHook(makeMockWindow(), null);
hook.setToolDefs([HIGH_RISK_DEF]);
// 记住拒绝
const p1 = hook.beforeExecute(makeToolCall(), 'sess');
const pending1 = hook.getPendingConfirmations();
hook.resolveConfirmation(pending1[0].toolCallId, false, true, false);
await p1;
// 拒绝记忆立即生效
const blockedNow = await hook.beforeExecute(makeToolCall(), 'sess');
expect(blockedNow.blocked).toBe(true);
expect(blockedNow.reason).toContain('previously denied');
// 快进 11 分钟(TTL 10 分钟)→ 拒绝记忆过期,恢复询问流程
vi.setSystemTime(Date.now() + 11 * 60 * 1000);
// 撤掉主窗口,使询问流程以 'no main window' 阻断(证明走到了询问分支而非记忆分支)
hook.setMainWindow(null as unknown as BrowserWindow);
const result = await hook.beforeExecute(makeToolCall(), 'sess');
expect(result.blocked).toBe(true);
expect(result.reason).toContain('no main window available');
// 过期记忆已被清理
expect(hook.getRememberedDenials()).toHaveLength(0);
} finally {
vi.useRealTimers();
}
});
it('无主窗口时安全阻断(fail-closed', async () => {
const hook = new ConfirmationHook(null, null);
hook.setToolDefs([HIGH_RISK_DEF]);
const result = await hook.beforeExecute(makeToolCall(), 'sess');
expect(result.blocked).toBe(true);
expect(result.reason).toContain('no main window available');
});
it('用户拒绝单次调用 → blocked 且 reason 含 User denied', async () => {
const hook = new ConfirmationHook(makeMockWindow(), null);
hook.setToolDefs([HIGH_RISK_DEF]);
const p = hook.beforeExecute(makeToolCall(), 'sess');
const pending = hook.getPendingConfirmations();
hook.resolveConfirmation(pending[0].toolCallId, false, false, false);
const result = await p;
expect(result.blocked).toBe(true);
expect(result.reason).toContain('User denied');
});
});
describe('ConfirmationHook — 超时行为', () => {
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
it('确认超时视为拒绝(blocked', async () => {
const hook = new ConfirmationHook(makeMockWindow(), null);
hook.setToolDefs([HIGH_RISK_DEF]);
hook.setConfirmationTimeout(30_000); // 最小值 30s
const p = hook.beforeExecute(makeToolCall(), 'sess');
// 快进超过超时时间
vi.advanceTimersByTime(31_000);
const result = await p;
expect(result.blocked).toBe(true);
expect(result.reason).toContain('User denied');
// pending 已被超时清理
expect(hook.getPendingConfirmations()).toHaveLength(0);
});
it('确认超时与用户点击的竞态:先到者赢(settled 标志)', async () => {
const hook = new ConfirmationHook(makeMockWindow(), null);
hook.setToolDefs([HIGH_RISK_DEF]);
hook.setConfirmationTimeout(30_000);
const p = hook.beforeExecute(makeToolCall(), 'sess');
// timer 回调已入队但未执行时,用户点击批准
vi.advanceTimersByTime(30_000);
// 超时已 resolve(false) — 后续 resolveConfirmation 无效果
const pending = hook.getPendingConfirmations();
expect(pending).toHaveLength(0);
const result = await p;
expect(result.blocked).toBe(true);
});
});
describe('ConfirmationHook — 批量审批(v0.3.2', () => {
it('批量批准并行工具调用', async () => {
const hook = new ConfirmationHook(makeMockWindow(), null);
hook.setToolDefs([HIGH_RISK_DEF]);
const p1 = hook.beforeExecute(makeToolCall(), 'sess');
const p2 = hook.beforeExecute(makeToolCall(), 'sess');
expect(hook.getPendingConfirmations()).toHaveLength(2);
const ids = hook.getPendingConfirmations().map((r) => r.toolCallId);
const resolved = hook.resolveConfirmationsBatch(ids, true, false, false);
expect(resolved).toHaveLength(2);
expect((await p1).blocked).toBe(false);
expect((await p2).blocked).toBe(false);
});
it('批量拒绝 + 记住 → 同工具后续调用被记忆阻断', async () => {
const hook = new ConfirmationHook(makeMockWindow(), null);
hook.setToolDefs([HIGH_RISK_DEF]);
const p1 = hook.beforeExecute(makeToolCall(), 'sess');
const p2 = hook.beforeExecute(makeToolCall(), 'sess');
const ids = hook.getPendingConfirmations().map((r) => r.toolCallId);
hook.resolveConfirmationsBatch(ids, false, true, false);
expect((await p1).blocked).toBe(true);
expect((await p2).blocked).toBe(true);
const after = await hook.beforeExecute(makeToolCall(), 'sess');
expect(after.blocked).toBe(true);
expect(after.reason).toContain('previously denied');
});
it('批量批准 + autoExecute → 写入持久化自动执行列表', async () => {
const hook = new ConfirmationHook(makeMockWindow(), null);
hook.setToolDefs([HIGH_RISK_DEF]);
const p = hook.beforeExecute(makeToolCall(), 'sess');
const ids = hook.getPendingConfirmations().map((r) => r.toolCallId);
hook.resolveConfirmationsBatch(ids, true, false, true);
expect((await p).blocked).toBe(false);
expect(hook.getAutoExecuteList()).toContain('run_command');
});
});
describe('ConfirmationHook — 拒绝记忆管理接口(v0.4.1', () => {
it('getRememberedDenials 只返回拒绝记忆(含剩余时间)', async () => {
const hook = new ConfirmationHook(makeMockWindow(), null);
hook.setToolDefs([HIGH_RISK_DEF, HIGH_RISK_DEF_2]);
// 记住一个批准(run_command)、一个拒绝(delete_file
const pApprove = hook.beforeExecute(makeToolCall('run_command'), 'sess');
hook.resolveConfirmation(hook.getPendingConfirmations()[0].toolCallId, true, true, false);
await pApprove;
const pDeny = hook.beforeExecute(makeToolCall('delete_file'), 'sess');
hook.resolveConfirmation(hook.getPendingConfirmations()[0].toolCallId, false, true, false);
await pDeny;
const denials = hook.getRememberedDenials();
expect(denials).toHaveLength(1);
expect(denials[0].toolName).toBe('delete_file');
expect(denials[0].expiresInSeconds).toBeGreaterThan(0);
expect(denials[0].expiresInSeconds).toBeLessThanOrEqual(600);
});
it('resetRememberedDenial 重置后恢复询问', async () => {
const hook = new ConfirmationHook(makeMockWindow(), null);
hook.setToolDefs([HIGH_RISK_DEF]);
const p = hook.beforeExecute(makeToolCall(), 'sess');
hook.resolveConfirmation(hook.getPendingConfirmations()[0].toolCallId, false, true, false);
await p;
expect(hook.getRememberedDenials()).toHaveLength(1);
// 重置 → 拒绝记忆清空
expect(hook.resetRememberedDenial('run_command')).toBe(true);
expect(hook.getRememberedDenials()).toHaveLength(0);
// 后续调用恢复询问(有窗口 → 产生新 pending)
const p2 = hook.beforeExecute(makeToolCall(), 'sess');
expect(hook.getPendingConfirmations()).toHaveLength(1);
hook.resolveConfirmation(hook.getPendingConfirmations()[0].toolCallId, true, false, false);
expect((await p2).blocked).toBe(false);
});
it('resetRememberedDenial 对无拒绝记忆的工具返回 false', () => {
const hook = new ConfirmationHook(null, null);
expect(hook.resetRememberedDenial('run_command')).toBe(false);
});
});
describe('ConfirmationHook — clearPending', () => {
it('清空所有等待中的确认(全部视为拒绝)', async () => {
const hook = new ConfirmationHook(makeMockWindow(), null);
hook.setToolDefs([HIGH_RISK_DEF]);
const p1 = hook.beforeExecute(makeToolCall(), 'sess');
const p2 = hook.beforeExecute(makeToolCall(), 'sess');
hook.clearPending();
expect((await p1).blocked).toBe(true);
expect((await p2).blocked).toBe(true);
expect(hook.getPendingConfirmations()).toHaveLength(0);
});
});
describe('ConfirmationHook — 跨会话隔离(v0.5.0', () => {
it('A 会话记住拒绝,B 会话同工具仍正常询问(产生新 pending)', async () => {
const hook = new ConfirmationHook(makeMockWindow(), null);
hook.setToolDefs([HIGH_RISK_DEF]);
// A 会话记住拒绝
const pA = hook.beforeExecute(makeToolCall(), 'sess-a');
hook.resolveConfirmation(hook.getPendingConfirmations()[0].toolCallId, false, true, false);
expect((await pA).blocked).toBe(true);
// B 会话同工具 — 不受 A 会话拒绝记忆影响,进入询问流程(产生新 pending)
const pB = hook.beforeExecute(makeToolCall(), 'sess-b');
const pendingB = hook.getPendingConfirmations();
expect(pendingB).toHaveLength(1);
hook.resolveConfirmation(pendingB[0].toolCallId, true, false, false);
expect((await pB).blocked).toBe(false);
// A 会话的拒绝记忆仍在(getRememberedDenials 限定 A 会话可见)
expect(hook.getRememberedDenials('sess-a')).toHaveLength(1);
expect(hook.getRememberedDenials('sess-b')).toHaveLength(0);
});
it('A 会话记住批准,B 会话同工具仍需确认', async () => {
const hook = new ConfirmationHook(makeMockWindow(), null);
hook.setToolDefs([HIGH_RISK_DEF]);
// A 会话记住批准
const pA = hook.beforeExecute(makeToolCall(), 'sess-a');
hook.resolveConfirmation(hook.getPendingConfirmations()[0].toolCallId, true, true, false);
expect((await pA).blocked).toBe(false);
// A 会话后续调用直接放行(无新 pending)
const again = await hook.beforeExecute(makeToolCall(), 'sess-a');
expect(again.blocked).toBe(false);
expect(hook.getPendingConfirmations()).toHaveLength(0);
// B 会话同工具 — 进入询问流程(批准记忆不跨会话共享)
const pB = hook.beforeExecute(makeToolCall(), 'sess-b');
expect(hook.getPendingConfirmations()).toHaveLength(1);
hook.resolveConfirmation(hook.getPendingConfirmations()[0].toolCallId, true, false, false);
expect((await pB).blocked).toBe(false);
});
it('中断 A 会话(clearPending 按会话)不影响 B 会话等待中的确认', async () => {
const hook = new ConfirmationHook(makeMockWindow(), null);
hook.setToolDefs([HIGH_RISK_DEF]);
// 两个会话各有一个等待中的确认
const pA = hook.beforeExecute(makeToolCall(), 'sess-a');
const pB = hook.beforeExecute(makeToolCall(), 'sess-b');
expect(hook.getPendingConfirmations()).toHaveLength(2);
// 中断 A 会话 — 只拒绝 A 的 pending
hook.clearPending('sess-a');
expect((await pA).blocked).toBe(true);
// B 会话的 pending 仍在等待,用户批准后正常放行
const remaining = hook.getPendingConfirmations();
expect(remaining).toHaveLength(1);
expect(remaining[0].toolCallId).toBeDefined();
hook.resolveConfirmation(remaining[0].toolCallId, true, false, false);
expect((await pB).blocked).toBe(false);
});
it('resetRememberedDenial 指定会话时只重置该会话的拒绝记忆', async () => {
const hook = new ConfirmationHook(makeMockWindow(), null);
hook.setToolDefs([HIGH_RISK_DEF]);
// A、B 两个会话都记住拒绝
const pA = hook.beforeExecute(makeToolCall(), 'sess-a');
hook.resolveConfirmation(hook.getPendingConfirmations()[0].toolCallId, false, true, false);
await pA;
const pB = hook.beforeExecute(makeToolCall(), 'sess-b');
hook.resolveConfirmation(hook.getPendingConfirmations()[0].toolCallId, false, true, false);
await pB;
// 重置 A 会话的拒绝记忆 — B 会话的记忆保留
expect(hook.resetRememberedDenial('run_command', 'sess-a')).toBe(true);
expect(hook.getRememberedDenials('sess-a')).toHaveLength(0);
expect(hook.getRememberedDenials('sess-b')).toHaveLength(1);
// 缺省 sessionId — 重置所有会话
expect(hook.resetRememberedDenial('run_command')).toBe(true);
expect(hook.getRememberedDenials()).toHaveLength(0);
});
it('setAutoExecute 启用时清除所有会话的拒绝记忆(全局设置优先)', async () => {
const hook = new ConfirmationHook(makeMockWindow(), null);
hook.setToolDefs([HIGH_RISK_DEF]);
// 两个会话都记住拒绝
for (const sid of ['sess-a', 'sess-b']) {
const p = hook.beforeExecute(makeToolCall(), sid);
hook.resolveConfirmation(hook.getPendingConfirmations()[0].toolCallId, false, true, false);
await p;
}
expect(hook.getRememberedDenials()).toHaveLength(1); // 聚合去重后同一工具 1 条
// 启用自动执行 — 所有会话的拒绝记忆被清除
hook.setAutoExecute('run_command', true);
expect(hook.getRememberedDenials()).toHaveLength(0);
// 自动执行放行(任意会话)
expect((await hook.beforeExecute(makeToolCall(), 'sess-a')).blocked).toBe(false);
expect((await hook.beforeExecute(makeToolCall(), 'sess-b')).blocked).toBe(false);
});
});