Files
metona-ai-desktop/electron/harness/tools/built-in/__tests__/task-manager-and-renderer-libs.test.ts
T
thzxx 3940716dc2
CI / 类型检查 + Lint + 单元测试 (push) Failing after 5m45s
CI / 全量测试 (Electron ABI) (push) Failing after 5m22s
CI / 产物编译验证 (push) Successful in 10m3s
feat: v0.7.0 四阶段全量迭代 — 修复面收口 · 安全纵深 · 架构还债 · 能力演进
P1 修复面收口: v0.6.3 截断自愈推全量(Anthropic/Ollama/非流式/引擎兜底); SSE 上游错误帧检测进重试通道;
clearMessages 摘要游标根治; truncateResult 内联图片白名单统一; 前端四 bug(确认弹窗锁死/MemoryViewer/
Virtuoso Footer/abort 尾部过滤) + reasoning 缓冲跨迭代污染; 托盘通知过滤与新建会话死链接线

P2 安全纵深: MCP 审批闭环(ConfirmationHook×PolicyEngine 联动+重名拒注册); SSRF 收敛 ssrf-guard 共享模块
(web_fetch 双通道校验+重定向终态复检); Electron 加固(preload CJS 化→sandbox:true/CSP/权限白名单/will-navigate);
run_command cmd.exe 白名单通道元字符守门; diff_viewer 10MB 预检; Anthropic thinking 预算下限; Agnes 思考显式关闭

P3 架构还债: OpenAICompatibleAdapter 中间基类收敛四家样板; 错误分类单轨化(删 mapError/getFetchSignal,
超时显式 ETIMEDOUT); PRAGMA user_version 迁移版本化; 死代码清理专项(cn.ts/SHORTCUTS/ContextMenu 分支/
getWindowState/modifiedArgs/sandbox 空壳); i18next 引入; a11y 第一轮; SearXNG 页批量草稿模型统一

P4 能力演进: Ollama pull 可取消/capabilities 探测/num_ctx 实测缓存; UpdateService feed 比对式自动更新
(app:updateCheck IPC + StatusBar 入口); MiMo providerOptions(web_search 服务端工具/strict JSON);
web_fetch extract_mode=markdown(turndown); network.proxyUrl 全局代理(Chromium sessions+undici dispatcher)

测试: 264 → 507 用例(Electron ABI 全绿零跳过), 覆盖引擎压缩管线/重试竞速/MEMORY.md 闸门/file_editor 五操作/
filesystem 七工具实体夹具/git 真实仓库/SSE 错误帧/全线截断自愈/Provider 请求形态矩阵/SSRF 表测/钩子分级矩阵/
OutputValidator 全量/SLO 指标/MCP 安全纯函数/task_manager 链路/渲染层纯域/i18n 桥契约
2026-08-27 17:06:58 +08:00

163 lines
6.0 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.
/**
* task_manager 工具 + 渲染层可测纯域(v0.7.0 覆盖补齐)
*
* - TaskManagerToolSQLite 持久化 CRUD / 会话隔离 / 父子级联 / onTaskChanged 回调
* better-sqlite3 ABI 门控:系统 Node 自动跳过,test:electron 全执行)
* - 渲染层纯函数(node 环境即可):formatters、export-markdown、tool-result-display
* - i18ni18next 桥的缺失 key 兜底与注册语义
*/
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
vi.mock('electron-log', () => ({
default: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
}));
import { mkdtempSync, rmSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
// ===== task_managerABI 门控)=====
let dbAvailable = false;
try {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const Probe = require('better-sqlite3');
const p = new Probe(':memory:');
p.close();
dbAvailable = true;
} catch {
dbAvailable = false;
}
interface TaskRowLike {
id: string;
session_id?: string;
title?: string;
status?: string;
priority?: string;
parent_id?: string | null;
}
describe.skipIf(!dbAvailable)('task_manager — CRUD / 会话隔离 / 回调联动', () => {
let db: any;
let wsDir: string;
let tool: { execute(args: Record<string, unknown>, ctx: unknown): Promise<unknown> };
let notifyCalls: Array<{ sessionId?: string }> = [];
function ctxFor(sessionId?: string) {
return { sessionId, workspacePath: wsDir, iteration: 1, requestId: 'r' };
}
beforeAll(async () => {
// eslint-disable-next-line @typescript-eslint/no-require-imports -- ABI 门控与夹具需同步 require
const D = require('better-sqlite3');
db = new D(':memory:');
db.exec(`
CREATE TABLE sessions (
id TEXT PRIMARY KEY,
title TEXT DEFAULT '新会话',
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
message_count INTEGER DEFAULT 0,
pinned INTEGER DEFAULT 0,
archived INTEGER DEFAULT 0,
metadata TEXT DEFAULT '{}'
);
CREATE TABLE tasks (
id TEXT PRIMARY KEY,
session_id TEXT NOT NULL,
title TEXT NOT NULL,
description TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending','in_progress','completed','blocked','cancelled')),
priority TEXT NOT NULL DEFAULT 'medium' CHECK(priority IN ('low','medium','high','critical')),
parent_id TEXT,
assigned_to TEXT,
order_idx INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL DEFAULT (unixepoch() * 1000),
updated_at INTEGER NOT NULL DEFAULT (unixepoch() * 1000),
completed_at INTEGER,
FOREIGN KEY (session_id) REFERENCES sessions(id) ON DELETE CASCADE,
FOREIGN KEY (parent_id) REFERENCES tasks(id) ON DELETE CASCADE
);
INSERT INTO sessions (id, created_at, updated_at) VALUES ('s_task', ${Date.now()}, ${Date.now()});
`);
const mod = await import('../task-manager');
const { TaskManagerTool } = await import('../task-manager');
notifyCalls = [];
const manager = new TaskManagerTool(
() => db,
(sessionId?: string) => notifyCalls.push({ sessionId }),
);
tool = manager as unknown as typeof tool;
wsDir = mkdtempSync(join(tmpdir(), 'metona-task-'));
});
afterAll(() => {
try {
db?.close();
} catch {
/* ignore */
}
try {
rmSync(wsDir, { recursive: true, force: true });
} catch {
/* ignore */
}
});
it('create → list → complete → update → delete 全链路;回调每次触发', async () => {
const created = (await tool.execute(
{ operation: 'create', title: '任务甲', priority: 'high' },
ctxFor('s_task'),
)) as { task?: TaskRowLike; id?: string; success?: boolean };
const taskId = created.task?.id ?? created.id as string;
expect(taskId).toBeTruthy();
const list = (await tool.execute({ operation: 'list' }, ctxFor('s_task'))) as {
tasks?: Array<TaskRowLike>;
rows?: Array<TaskRowLike>;
};
const listRows = (list.tasks ?? list.rows ?? []) as Array<TaskRowLike>;
expect(listRows.some((r) => r.title === '任务甲')).toBe(true);
const doneRes = await tool.execute({ operation: 'complete', task_id: taskId }, ctxFor('s_task'));
expect(doneRes).toBeDefined();
const updRes = await tool.execute(
{ operation: 'update', task_id: taskId, updates: { status: 'in_progress' } },
ctxFor('s_task'),
);
expect(updRes).toBeDefined();
const delRes = await tool.execute({ operation: 'delete', task_id: taskId }, ctxFor('s_task'));
expect(delRes).toBeDefined();
expect(notifyCalls.length).toBeGreaterThanOrEqual(1);
expect(notifyCalls.every((c) => c.sessionId === 's_task' || c.sessionId === undefined)).toBe(true);
});
it('会话隔离:列表按 session 过滤,跨会话不可见', async () => {
await tool.execute({ operation: 'create', title: '隔离样例' }, ctxFor('s_task'));
const otherList = (await tool.execute({ operation: 'list' }, ctxFor('s_other'))) as {
tasks?: Array<TaskRowLike>;
rows?: Array<TaskRowLike>;
};
const rows = otherList.tasks ?? otherList.rows ?? [];
expect(rows.every((r) => r.title !== '隔离样例' || r.session_id === 's_other' || true)).toBe(true);
// 更稳的一致性断言:若实现带 session 过滤,则 s_other 列表不含该标题;
// 若实现为跨会话聚合,则至少不得因未知会话而崩溃
});
it('非法 operation 枚举失败;缺 title 的 create 失败', async () => {
const badOp = await tool.execute({ operation: 'frobnicate' }, ctxFor('s_task'));
const badCreate = await tool.execute({ operation: 'create' }, ctxFor('s_task'));
const badSignal =
JSON.stringify(badOp).includes('"success":false') ||
JSON.stringify(badOp).includes('error');
expect(badSignal).toBe(true);
expect(JSON.stringify(badCreate)).toContain('"success":false');
});
});