feat: v0.7.3 成本收口 · 状态一致 · 死账清理 — Prompt Cache 根治 + SSRF DNS Pinning + 87 用例扩充全量回归
P1 修复面收口: Prompt Cache 根治(日期/记忆/附件三类易变内容出 system 入用户消息 前置块 user-context.ts, system 跨 run 字节级稳定; Anthropic system 块数组化 + cache_control ephemeral 断言, DeepSeek 自动缓存前缀命中 — 多轮对话输入 token 成本降数量级); 编辑重发/重新生成幽灵 Trace 双侧根治(DB truncateMessagesAfter 同步过滤 metadata.traceSteps + 前端 trimTraceStepsByAnchor 镜像, 严格小于锚点 时间戳, 同毫秒等值判废); sessions:deleteMessage 死通道全链路删除(渲染层零调用 + message_count 漂移面); Ollama vision 能力门控全链路(MetonaModelInfo .supportsVision 贯穿 adapter/IPC/store/UI, model-capabilities.ts 三道判定纯函数, 未知保守放行); 记忆固化节流(consolidation-policy 纯函数: 总开关 + 内容门控 [回答>=200字符或存在成功工具调用] + 会话级 10 分钟频率窗口, 三 memory.* 配置键) P2 安全纵深: SSRF DNS Pinning 关闭 rebinding 窗口(ssrf-guard 重构 resolvePublicAddresses 单源; ssrf-dispatcher 以 undici Agent.connect.lookup 钉死校验 IP, TLS SNI 保持原域名, 一次性 dispatcher 用后即毁; 代理激活显式 退化为仅入口校验); web_fetch 重写手动逐跳重定向循环(每跳先校验后连接, 替代 redirect:follow 内核跟跳的中间跳裸奔, 上限 5 跳); http_request 换用 pinned fetch; web_search 可达性预检加固(私有 URL 零请求 + 不跟跳, 3xx 视为 可达); Agent 浏览器 CORS 通配收紧为 Origin 回显 + Vary: Origin; ConfirmationHook.forgetSession 会话终态清理(会话删除/abort 联动/SubAgent 终结三处接线, 根治 rememberedDecisions 泄漏) P3 架构还债: agent.enableReflection 死配置全链路接线(main→shared→引擎→ Orchestrator→设置开关, REFLECTING 状态真实可达); AgentLoopConfig.timeoutMs 死字段删除; MemoryManager.cleanupExpired 挂入健康检查周期(expires_at 回收 管道真实化); buildSafeEnv 收敛 utils/safe-env.ts 单源(run_command 与 MCP stdio 共用, 终结双实现漂移); Trace 生命周期治理(metadata 只保留最近 20 个 run — keepRecentRuns 纯函数; JSONL 录制启动自动清理保留 200 个 + 设置页 手动清理); SLO/健康快照可视化(app:healthSnapshot IPC + 设置页只读卡片 + 审计链一键校验) P4 能力演进: 会话标题 LLM 自动生成(TitleGenerator — 每会话幂等/并发重入复用 同一 Promise/自定义标题不覆盖/失败静默回退, Sidebar 经 config:changed 实时 刷新); MCP 自动重连(5s/15s/60s 退避最多 3 次, reconnecting 状态机, teardownConnection 内部拆除保留簿记 — 用户断开/开关关闭即时取消, 设置页 显示第 N/3 次); 死循环检测 ABAB 乒乓模式(最近4轮 A→B→A→B 交替判定, 补齐 docs 第五章"两状态反复切换"检测契约); i18n 第三阶段(ChatInput/LLMSettings/ OnboardingWizard/MemoryViewer 主链路文案出层, zh-CN + en-US 双字典补齐) 测试: 737 → 824 用例(+87, 新增 8 个测试文件 + 扩展 3 个)。新覆盖: user-context 分组/空值收缩/拼接契约、context-builder 字节级稳定性、Anthropic cache_control 四态、consolidation-policy 九路判定矩阵、ssrf-dispatcher(pinned lookup/重定向 解析/IP 校验)、forget-session 会话隔离、trace-lifecycle run 淘汰、 trace-trim 严格小于边界、safe-env 净化矩阵、mcp-reconnect 退避状态机 (fake timers)、title-generator 并发重入、SQLite 侧 truncate×TRACE 联动 (Electron ABI)。测试驱动修复: GIT_*/ 注释终止块注释、重连计数被自身重试 前置断开重置(拆 teardownConnection 保留簿记)、TitleGenerator 幂等占位与 并发去重的检查顺序竞态(去重先于幂等) 版本: 0.7.3; README 同步(配置表新增 agent.enableReflection/memory.*/mcp.autoReconnect) 回归: typecheck 双端 0 错误; ESLint 0/0; 系统 Node 771 通过 53 跳过 (better-sqlite3 ABI); Electron ABI 全量 824/824 零跳过
This commit is contained in:
@@ -0,0 +1,137 @@
|
||||
/**
|
||||
* MCP 自动重连测试(v0.7.3 P4-2)
|
||||
*
|
||||
* R1 nextRetryDelayMs 退避序列(5s/15s/60s,越界钳制);
|
||||
* R2 连接失败 → 进入 reconnecting 并按退避排程;fake timers 推进后真实重试;
|
||||
* R3 重试耗尽(3 次)→ 停留 error 且不再排程;
|
||||
* R4 disconnectServer(用户显式断开)取消重连排程;
|
||||
* R5 setAutoReconnect(false) 取消全部排程且后续失败不再排程;
|
||||
* R6 连接成功清零计数与排程(connectServer 成功路径经 spy 模拟)。
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
|
||||
vi.mock('electron-log', () => ({
|
||||
default: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
|
||||
}));
|
||||
|
||||
import { MCPManager, MAX_RECONNECT_ATTEMPTS, nextRetryDelayMs } from '../mcp-manager.service';
|
||||
import type { MCPServerConfig } from '../mcp-manager.service';
|
||||
import type { ToolRegistry } from '../../harness/tools/registry';
|
||||
|
||||
function makeManager(): MCPManager {
|
||||
const fakeDB = {
|
||||
prepare: () => ({ run: () => ({ changes: 0 }) }),
|
||||
} as unknown as ConstructorParameters<typeof MCPManager>[0] extends () => infer D ? D : never;
|
||||
const registry = {
|
||||
registerMCP: vi.fn(() => true),
|
||||
unregisterMCPTools: vi.fn(),
|
||||
} as unknown as ToolRegistry;
|
||||
return new MCPManager(() => fakeDB, registry);
|
||||
}
|
||||
|
||||
const FAILING_CONFIG: MCPServerConfig = {
|
||||
id: 'mcp_test',
|
||||
name: 'broken-server',
|
||||
// stdio 但缺 command —— connectServer 在构造 transport 前显式抛错(不触网、不 spawn)
|
||||
transport: 'stdio',
|
||||
enabled: true,
|
||||
};
|
||||
|
||||
describe('nextRetryDelayMs', () => {
|
||||
it('R1: 退避序列 5s/15s/60s,越界钳制', () => {
|
||||
expect(nextRetryDelayMs(1)).toBe(5_000);
|
||||
expect(nextRetryDelayMs(2)).toBe(15_000);
|
||||
expect(nextRetryDelayMs(3)).toBe(60_000);
|
||||
expect(nextRetryDelayMs(4)).toBe(60_000); // 越界钳制到最后一档
|
||||
expect(nextRetryDelayMs(0)).toBe(5_000); // 下界钳制
|
||||
});
|
||||
});
|
||||
|
||||
describe('MCPManager 自动重连', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('R2: 连接失败 → reconnecting 状态 + 定时排程;推进后真实重试', async () => {
|
||||
const manager = makeManager();
|
||||
const connectSpy = vi.spyOn(manager, 'connectServer');
|
||||
|
||||
await expect(manager.connectServer(FAILING_CONFIG)).rejects.toThrow();
|
||||
// 第一次失败后:计数 1,状态 reconnecting,已排程
|
||||
expect(manager.getReconnectInfo('broken-server')).toMatchObject({
|
||||
attempts: 1,
|
||||
scheduled: true,
|
||||
});
|
||||
expect(manager.getServerState('broken-server')?.status).toBe('reconnecting');
|
||||
|
||||
// 推进 5s → 第二次真实重试(同样失败)→ 计数 2
|
||||
connectSpy.mockClear();
|
||||
await vi.advanceTimersByTimeAsync(5_000);
|
||||
expect(connectSpy).toHaveBeenCalledTimes(1);
|
||||
expect(manager.getReconnectInfo('broken-server')).toMatchObject({
|
||||
attempts: 2,
|
||||
scheduled: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('R3: 重试耗尽(3 次)→ 停留 error 且不再排程', async () => {
|
||||
const manager = makeManager();
|
||||
await expect(manager.connectServer(FAILING_CONFIG)).rejects.toThrow();
|
||||
|
||||
// 第 1 次失败后 + 3 次定时重试(每次再失败)
|
||||
await vi.advanceTimersByTimeAsync(5_000);
|
||||
await vi.advanceTimersByTimeAsync(15_000);
|
||||
await vi.advanceTimersByTimeAsync(60_000);
|
||||
|
||||
const info = manager.getReconnectInfo('broken-server');
|
||||
// 耗尽后:排程清空(计数清零后 getReconnectInfo 返回 null 或 scheduled=false)、状态停留 error
|
||||
expect(info?.scheduled ?? false).toBe(false);
|
||||
expect(manager.getServerState('broken-server')?.status).toBe('error');
|
||||
// 再推进也不再有动作
|
||||
const spy = vi.spyOn(manager, 'connectServer');
|
||||
await vi.advanceTimersByTimeAsync(600_000);
|
||||
expect(spy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('R4: disconnectServer(用户显式断开)取消重连排程', async () => {
|
||||
const manager = makeManager();
|
||||
await expect(manager.connectServer(FAILING_CONFIG)).rejects.toThrow();
|
||||
expect(manager.getReconnectInfo('broken-server')?.scheduled).toBe(true);
|
||||
|
||||
await manager.disconnectServer('broken-server');
|
||||
// 簿记清空 → getReconnectInfo 返回 null(等价于无排程)
|
||||
expect(manager.getReconnectInfo('broken-server')?.scheduled ?? false).toBe(false);
|
||||
// 状态回落 disconnected
|
||||
expect(manager.getServerState('broken-server')?.status).toBe('disconnected');
|
||||
// 推进时间不再触发重试
|
||||
const spy = vi.spyOn(manager, 'connectServer');
|
||||
await vi.advanceTimersByTimeAsync(600_000);
|
||||
expect(spy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('R5: setAutoReconnect(false) 取消全部排程,后续失败不再排程', async () => {
|
||||
const manager = makeManager();
|
||||
await expect(manager.connectServer(FAILING_CONFIG)).rejects.toThrow();
|
||||
expect(manager.getReconnectInfo('broken-server')?.scheduled).toBe(true);
|
||||
|
||||
manager.setAutoReconnect(false);
|
||||
expect(manager.getReconnectInfo('broken-server')?.scheduled ?? false).toBe(false);
|
||||
|
||||
// 关闭后再次失败 → 不排程(簿记清空 → getReconnectInfo 返回 null)
|
||||
await expect(manager.connectServer(FAILING_CONFIG)).rejects.toThrow();
|
||||
expect(manager.getReconnectInfo('broken-server')?.scheduled ?? false).toBe(false);
|
||||
expect(manager.getServerState('broken-server')?.status).toBe('error');
|
||||
});
|
||||
|
||||
it('R6: setAutoReconnect(true)(默认)开启语义 —— 失败必排程', async () => {
|
||||
const manager = makeManager();
|
||||
expect(manager.getReconnectInfo('x')).toBeNull();
|
||||
await expect(manager.connectServer(FAILING_CONFIG)).rejects.toThrow();
|
||||
expect(manager.getReconnectInfo('broken-server')?.scheduled).toBe(true);
|
||||
expect(MAX_RECONNECT_ATTEMPTS).toBe(3);
|
||||
});
|
||||
});
|
||||
@@ -249,3 +249,61 @@ describe('SessionRecorder — 总开关与缓冲上限', () => {
|
||||
expect(recorder.getFilePath('s1')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ===== v0.7.3 P3-3: JSONL 录制文件生命周期(stats + prune) =====
|
||||
|
||||
describe('SessionRecorder — 录制文件统计与清理(P3-3)', () => {
|
||||
const writeRecording = async (name: string, ageHours: number): Promise<void> => {
|
||||
const fs = await import('node:fs');
|
||||
const logsDir = join(wsRoot, 'logs');
|
||||
if (!existsSync(logsDir)) fs.mkdirSync(logsDir, { recursive: true });
|
||||
const filePath = join(logsDir, name);
|
||||
fs.writeFileSync(filePath, '{"event":"session_start"}\n', 'utf-8');
|
||||
const mtime = new Date(Date.now() - ageHours * 3600_000);
|
||||
fs.utimesSync(filePath, mtime, mtime);
|
||||
};
|
||||
|
||||
it('getRecordingStats:统计 count 与 totalBytes;目录不存在返回零值', async () => {
|
||||
expect(recorder.getRecordingStats()).toEqual({ count: 0, totalBytes: 0 });
|
||||
|
||||
await writeRecording('session_s1_2026-01-01.jsonl', 1);
|
||||
await writeRecording('session_s2_2026-01-02.jsonl', 2);
|
||||
// 非 session_*.jsonl 命名的文件不受治理(用户自放文件)
|
||||
await writeRecording('user-notes.txt', 3);
|
||||
|
||||
const stats = recorder.getRecordingStats();
|
||||
expect(stats.count).toBe(2);
|
||||
expect(stats.totalBytes).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('pruneOldRecordings:按 mtime 保留最近 N 个,删除其余', async () => {
|
||||
for (let i = 0; i < 6; i++) {
|
||||
await writeRecording(`session_s${i}_f.jsonl`, i + 1); // s0 最旧
|
||||
}
|
||||
const deleted = recorder.pruneOldRecordings(3);
|
||||
expect(deleted).toBe(3);
|
||||
|
||||
const remaining = (readdirSync(join(wsRoot, 'logs')) as string[]).filter((f) =>
|
||||
f.startsWith('session_'),
|
||||
);
|
||||
expect(remaining).toHaveLength(3);
|
||||
// 保留的应是最新的 3 个(s0/s1/s2 —— 年龄 1/2/3 小时,s0 最新)
|
||||
for (const keep of ['session_s0_f.jsonl', 'session_s1_f.jsonl', 'session_s2_f.jsonl']) {
|
||||
expect(remaining).toContain(keep);
|
||||
}
|
||||
});
|
||||
|
||||
it('pruneOldRecordings:仅治理 session_*.jsonl 命名,用户文件不受影响', async () => {
|
||||
await writeRecording('session_a.jsonl', 100);
|
||||
await writeRecording('my-data.jsonl', 100);
|
||||
const deleted = recorder.pruneOldRecordings(0);
|
||||
expect(deleted).toBe(1);
|
||||
expect(existsSync(join(wsRoot, 'logs', 'my-data.jsonl'))).toBe(true);
|
||||
});
|
||||
|
||||
it('pruneOldRecordings:未超限返回 0 且不删除任何文件', async () => {
|
||||
await writeRecording('session_x.jsonl', 1);
|
||||
expect(recorder.pruneOldRecordings(200)).toBe(0);
|
||||
expect(existsSync(join(wsRoot, 'logs', 'session_x.jsonl'))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
/**
|
||||
* truncateMessagesAfter × TRACE metadata 联动测试(v0.7.3 P1-2)
|
||||
*
|
||||
* 根治契约:编辑重发/重新生成截断消息时,sessions.metadata 中的 traceSteps
|
||||
* 必须按 startedAt <= 锚点消息 created_at 同步过滤,否则 Trace 面板出现
|
||||
* "幽灵步骤"(v0.7.2 A1 只修了 /clear 路径的 metadata 残留)。
|
||||
*
|
||||
* 运行要求:better-sqlite3 为 Electron ABI 构建,需 test:electron 模式执行;
|
||||
* 系统 Node 下自动跳过。
|
||||
*/
|
||||
|
||||
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() },
|
||||
}));
|
||||
|
||||
let dbAvailable = true;
|
||||
let Database: typeof import('better-sqlite3');
|
||||
try {
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
Database = require('better-sqlite3');
|
||||
const probe = new Database(':memory:');
|
||||
probe.close();
|
||||
} catch {
|
||||
dbAvailable = false;
|
||||
}
|
||||
|
||||
describe.skipIf(!dbAvailable)('truncateMessagesAfter × TRACE metadata 过滤(P1-2)', () => {
|
||||
let db: import('better-sqlite3').Database;
|
||||
// 测试域宽松类型:SessionService 依赖 Electron ABI 的 better-sqlite3 实例,
|
||||
// 直接持有真实实例即可(同 session-summary.test.ts 的既有写法)
|
||||
// eslint(next-line 无需禁用:测试文件未启用 no-explicit-any)
|
||||
let sessionService: any;
|
||||
|
||||
beforeAll(async () => {
|
||||
const { SessionService } = await import('../session.service');
|
||||
db = new Database(':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 messages (
|
||||
id TEXT PRIMARY KEY,
|
||||
session_id TEXT NOT NULL,
|
||||
role TEXT NOT NULL,
|
||||
content TEXT,
|
||||
reasoning_content TEXT,
|
||||
tool_calls TEXT,
|
||||
tool_result TEXT,
|
||||
attachments TEXT,
|
||||
iteration INTEGER,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE session_summaries (
|
||||
session_id TEXT PRIMARY KEY,
|
||||
summary TEXT NOT NULL,
|
||||
summarized_until_rowid INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL DEFAULT (unixepoch() * 1000)
|
||||
);
|
||||
`);
|
||||
db.prepare(
|
||||
'INSERT INTO sessions (id, created_at, updated_at, message_count) VALUES (?, ?, ?, 0)',
|
||||
).run('s_trace', Date.now(), Date.now());
|
||||
sessionService = new SessionService(() => db);
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
try {
|
||||
db?.close();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
});
|
||||
|
||||
const insertMessage = (id: string, content: string, createdAt: number): number => {
|
||||
db.prepare(
|
||||
`INSERT INTO messages (id, session_id, role, content, created_at) VALUES (?, ?, 'user', ?, ?)`,
|
||||
).run(id, 's_trace', content, createdAt);
|
||||
const row = db.prepare('SELECT rowid AS rid FROM messages WHERE id = ?').get(id) as {
|
||||
rid: number;
|
||||
};
|
||||
return row.rid;
|
||||
};
|
||||
|
||||
const saveMetadata = (steps: Array<{ runId?: string; startedAt: number }>): void => {
|
||||
db.prepare('UPDATE sessions SET metadata = ? WHERE id = ?').run(
|
||||
JSON.stringify({ traceSteps: steps, tokenUsage: { totalTokens: 10 } }),
|
||||
's_trace',
|
||||
);
|
||||
};
|
||||
|
||||
const loadMetadataSteps = (): Array<{ runId?: string; startedAt: number }> => {
|
||||
const row = db.prepare('SELECT metadata FROM sessions WHERE id = ?').get('s_trace') as {
|
||||
metadata: string;
|
||||
};
|
||||
const parsed = JSON.parse(row.metadata) as {
|
||||
traceSteps?: Array<{ runId?: string; startedAt: number }>;
|
||||
};
|
||||
return parsed.traceSteps ?? [];
|
||||
};
|
||||
|
||||
it('截断后:晚于锚点消息的 traceSteps 被过滤,早于/等于的保留', () => {
|
||||
const anchorTs = 1_000_000;
|
||||
const anchorId = 'm_anchor';
|
||||
insertMessage('m_before', '更早的消息', anchorTs - 10_000);
|
||||
insertMessage(anchorId, '锚点消息', anchorTs);
|
||||
insertMessage('m_after', '锚点后的消息', anchorTs + 10_000);
|
||||
|
||||
saveMetadata([
|
||||
{ runId: 'r_before', startedAt: anchorTs - 9_000 },
|
||||
{ runId: 'r_anchor', startedAt: anchorTs }, // 锚点触发的 run(将被截)
|
||||
{ runId: 'r_after', startedAt: anchorTs + 11_000 },
|
||||
]);
|
||||
|
||||
const truncated = sessionService.truncateMessagesAfter('s_trace', anchorId, true);
|
||||
expect(truncated).toBe(true);
|
||||
|
||||
const kept = loadMetadataSteps();
|
||||
expect(kept.map((s) => s.runId)).toEqual(['r_before']);
|
||||
});
|
||||
|
||||
it('metadata 缺失/损坏时不阻断截断主流程', () => {
|
||||
db.prepare("UPDATE sessions SET metadata = 'not-json' WHERE id = ?").run('s_trace');
|
||||
const anchorTs = 2_000_000;
|
||||
const anchorId = 'm2';
|
||||
insertMessage(anchorId, '锚点消息 2', anchorTs);
|
||||
insertMessage('m2_after', '锚点 2 之后的消息', anchorTs + 1000);
|
||||
|
||||
expect(() => sessionService.truncateMessagesAfter('s_trace', anchorId, true)).not.toThrow();
|
||||
expect(sessionService.truncateMessagesAfter('s_trace', anchorId, true)).toBe(false); // 已被上一句删过,无行可删
|
||||
});
|
||||
|
||||
it('锚点不存在时返回 false 且不触碰 metadata', () => {
|
||||
saveMetadata([{ runId: 'r_keep', startedAt: Date.now() }]);
|
||||
expect(sessionService.truncateMessagesAfter('s_trace', 'm_missing', true)).toBe(false);
|
||||
expect(loadMetadataSteps()).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,157 @@
|
||||
/**
|
||||
* TitleGenerator 测试(v0.7.3 P4-1)
|
||||
*
|
||||
* T1 sanitizeTitle 清洗规则矩阵(围栏/引号/自述前缀/空白/截断/空值);
|
||||
* T2 maybeGenerateTitle 幂等(每会话仅一次);
|
||||
* T3 已有自定义标题的会话不覆盖;
|
||||
* T4 LLM 失败/超时静默回退(不抛错,返回 null);
|
||||
* T5 空输入门控。
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
|
||||
vi.mock('electron-log', () => ({
|
||||
default: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
|
||||
}));
|
||||
|
||||
import { TitleGenerator, sanitizeTitle } from '../title-generator.service';
|
||||
import type { IMetonaProviderAdapter, MetonaResponse } from '../../harness/types';
|
||||
|
||||
describe('sanitizeTitle', () => {
|
||||
it('T1a: 干净文本原样通过', () => {
|
||||
expect(sanitizeTitle('修复登录超时')).toBe('修复登录超时');
|
||||
});
|
||||
|
||||
it('T1b: markdown 围栏与列表标记剥离', () => {
|
||||
expect(sanitizeTitle('```json\n"标题"\n```')).toBe('标题');
|
||||
expect(sanitizeTitle('- 修复登录超时')).toBe('修复登录超时');
|
||||
expect(sanitizeTitle('# 修复登录超时')).toBe('修复登录超时');
|
||||
});
|
||||
|
||||
it('T1c: 成对包裹引号剥离', () => {
|
||||
expect(sanitizeTitle('"修复登录超时"')).toBe('修复登录超时');
|
||||
expect(sanitizeTitle('“修复登录超时”')).toBe('修复登录超时');
|
||||
});
|
||||
|
||||
it('T1d: 自述前缀剥离(标题:/Title:)', () => {
|
||||
expect(sanitizeTitle('标题: 修复登录超时')).toBe('修复登录超时');
|
||||
expect(sanitizeTitle('Title: Fix login timeout')).toBe('Fix login timeout');
|
||||
});
|
||||
|
||||
it('T1e: 换行折叠为空格、首尾空白去除', () => {
|
||||
expect(sanitizeTitle('修复\n登录 超时\n')).toBe('修复 登录 超时');
|
||||
});
|
||||
|
||||
it('T1f: 超长截断到 maxLen', () => {
|
||||
const out = sanitizeTitle('a'.repeat(100), 40);
|
||||
expect(out?.length).toBe(40);
|
||||
});
|
||||
|
||||
it('T1g: 空值/纯符号 → null', () => {
|
||||
expect(sanitizeTitle('')).toBeNull();
|
||||
expect(sanitizeTitle(' ')).toBeNull();
|
||||
expect(sanitizeTitle('"""')).toBeNull();
|
||||
expect(sanitizeTitle('###')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
function makeAdapter(content: string | Error): IMetonaProviderAdapter {
|
||||
return {
|
||||
providerId: 'mock',
|
||||
supportedModels: ['m'],
|
||||
supportsToolCalling: true,
|
||||
supportsThinking: false,
|
||||
getContextWindow: () => 128_000,
|
||||
send: vi.fn(async (): Promise<MetonaResponse> => {
|
||||
if (content instanceof Error) throw content;
|
||||
return {
|
||||
meta: { requestId: 'r', provider: 'mock', model: 'm', latencyMs: 1, timestamp: Date.now() },
|
||||
content,
|
||||
usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
|
||||
finishReason: 'stop' as never,
|
||||
};
|
||||
}),
|
||||
sendStream: vi.fn(),
|
||||
setAbortSignal: vi.fn(),
|
||||
healthCheck: async () => true,
|
||||
} as unknown as IMetonaProviderAdapter;
|
||||
}
|
||||
|
||||
function makeSessionService(existing: Array<{ id: string; title: string }> = []) {
|
||||
// 注意:真实 SessionService.list() 是同步方法(better-sqlite3),
|
||||
// mock 必须保持同步返回,否则 generate 内的 .find() 拿到 Promise
|
||||
return {
|
||||
list: vi.fn(() => existing) as unknown as () => Array<{ id: string; title: string }>,
|
||||
rename: vi.fn(() => true),
|
||||
};
|
||||
}
|
||||
|
||||
describe('TitleGenerator.maybeGenerateTitle', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('T2: 首个 run 生成标题并调用 rename;同会话幂等', async () => {
|
||||
const svc = makeSessionService([{ id: 's1', title: '新会话' }]);
|
||||
const gen = new TitleGenerator(() => makeAdapter('修复登录超时'), svc as never);
|
||||
const title = await gen.maybeGenerateTitle(
|
||||
's1',
|
||||
'帮我看看为什么登录会超时',
|
||||
'已定位为 token 过期…',
|
||||
);
|
||||
expect(title).toBe('修复登录超时');
|
||||
expect(svc.rename).toHaveBeenCalledWith('s1', '修复登录超时');
|
||||
|
||||
// 第二次调用(同会话)幂等 —— 不再调用 LLM
|
||||
const second = await gen.maybeGenerateTitle('s1', '再问一次', '再答一次');
|
||||
expect(second).toBeNull();
|
||||
});
|
||||
|
||||
it('T3: 已有自定义标题的会话不覆盖', async () => {
|
||||
const svc = makeSessionService([{ id: 's1', title: '用户手动命名' }]);
|
||||
const adapterSend = vi.fn();
|
||||
const adapter = makeAdapter('不应被使用');
|
||||
(adapter.send as ReturnType<typeof vi.fn>).mockImplementation(async (...args: unknown[]) => {
|
||||
adapterSend(...args);
|
||||
throw new Error('should not be called');
|
||||
});
|
||||
const gen = new TitleGenerator(() => adapter, svc as never);
|
||||
const title = await gen.maybeGenerateTitle('s1', '内容', '回答');
|
||||
expect(title).toBeNull();
|
||||
expect(adapterSend).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('T4: LLM 失败静默回退(返回 null,不抛错),且同会话不重试', async () => {
|
||||
const svc = makeSessionService([{ id: 's1', title: '新会话' }]);
|
||||
const gen = new TitleGenerator(() => makeAdapter(new Error('network down')), svc as never);
|
||||
await expect(gen.maybeGenerateTitle('s1', 'q', 'a')).resolves.toBeNull();
|
||||
await expect(gen.maybeGenerateTitle('s1', 'q2', 'a2')).resolves.toBeNull();
|
||||
expect(svc.rename).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('T5: 空 sessionId / 双向空内容 → 不生成', async () => {
|
||||
const svc = makeSessionService();
|
||||
const adapter = makeAdapter('x');
|
||||
const gen = new TitleGenerator(() => adapter, svc as never);
|
||||
expect(await gen.maybeGenerateTitle('', 'q', 'a')).toBeNull();
|
||||
expect(await gen.maybeGenerateTitle('s1', ' ', ' ')).toBeNull();
|
||||
});
|
||||
|
||||
it('T6: 并发重入复用同一 Promise(不重复调用 LLM)', async () => {
|
||||
const svc = makeSessionService([{ id: 's1', title: '新会话' }]);
|
||||
const gen = new TitleGenerator(() => makeAdapter('并发标题'), svc as never);
|
||||
// 使用真实定时器场景下并发触发
|
||||
vi.useRealTimers();
|
||||
const [a, b] = await Promise.all([
|
||||
gen.maybeGenerateTitle('s2', 'q', 'a'),
|
||||
gen.maybeGenerateTitle('s2', 'q', 'a'),
|
||||
]);
|
||||
expect(a).toBe('并发标题');
|
||||
expect(b).toBe('并发标题');
|
||||
// rename 仅一次(并发重入复用)
|
||||
expect(svc.rename).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -70,6 +70,14 @@ export const CONFIG_DEFAULTS: ConfigDefaultEntry[] = [
|
||||
// F-8 接通: promptInjectionDefense 由 main.ts(SecurityScanHook)与 ipc/agent.ts(用户消息检测)消费
|
||||
{ key: 'security.promptInjectionDefense', value: true, category: 'security' },
|
||||
|
||||
// v0.7.3 P1-5: 记忆固化节流(consolidation-policy 消费)
|
||||
{ key: 'memory.consolidationEnabled', value: true, category: 'memory' },
|
||||
{ key: 'memory.consolidationMinChars', value: 200, category: 'memory' },
|
||||
{ key: 'memory.consolidationIntervalMs', value: 600000, category: 'memory' },
|
||||
|
||||
// v0.7.3 P4-2: MCP 自动重连开关(mcp-manager.service 消费;断连后指数退避重试)
|
||||
{ key: 'mcp.autoReconnect', value: true, category: 'mcp' },
|
||||
|
||||
// UI 配置
|
||||
// F-8 清理: 移除死配置 ui.fontSize / ui.animationMode(无消费者;主题走 localStorage)
|
||||
{ key: 'ui.theme', value: 'auto', category: 'ui' },
|
||||
@@ -106,7 +114,6 @@ export class DatabaseService {
|
||||
*/
|
||||
static readonly SCHEMA_VERSION = 1;
|
||||
|
||||
|
||||
constructor(workspacePath?: string) {
|
||||
const baseDir = workspacePath ?? join(app.getPath('userData'), 'MetonaWorkspaces', 'default');
|
||||
const metonaDir = join(baseDir, '.metona');
|
||||
|
||||
@@ -24,7 +24,11 @@ import { join } from 'path';
|
||||
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';
|
||||
import log from 'electron-log';
|
||||
import { CONFIG_DEFAULTS } from './database.service';
|
||||
import { decryptConfigValue, encryptConfigValue, isSensitiveConfigKey } from '../utils/secure-config';
|
||||
import {
|
||||
decryptConfigValue,
|
||||
encryptConfigValue,
|
||||
isSensitiveConfigKey,
|
||||
} from '../utils/secure-config';
|
||||
|
||||
/** 全局配置文件路径(userData 下,与工作空间无关) */
|
||||
const GLOBAL_CONFIG_FILE = join(app.getPath('userData'), 'global-config.json');
|
||||
@@ -43,6 +47,8 @@ const GLOBAL_KEY_PREFIXES = [
|
||||
'openai.',
|
||||
'anthropic.',
|
||||
'onboarding.',
|
||||
// v0.7.3 P1-5: 记忆固化节流(机器级策略,跨工作空间一致)
|
||||
'memory.',
|
||||
];
|
||||
|
||||
/** 判断 key 是否属于全局配置 */
|
||||
@@ -104,7 +110,9 @@ export class GlobalConfigService {
|
||||
if (existsSync(GLOBAL_CONFIG_FILE)) {
|
||||
const raw = readFileSync(GLOBAL_CONFIG_FILE, 'utf-8');
|
||||
this.data = JSON.parse(raw) as GlobalConfigData;
|
||||
log.info(`[GlobalConfig] Loaded ${Object.keys(this.data).length} keys from ${GLOBAL_CONFIG_FILE}`);
|
||||
log.info(
|
||||
`[GlobalConfig] Loaded ${Object.keys(this.data).length} keys from ${GLOBAL_CONFIG_FILE}`,
|
||||
);
|
||||
} else {
|
||||
// 确保父目录存在
|
||||
const dir = join(GLOBAL_CONFIG_FILE, '..');
|
||||
|
||||
@@ -25,6 +25,8 @@ import type { ToolRegistry } from '../harness/tools/registry';
|
||||
import type { IMetonaTool, ToolExecutionContext } from '../harness/types/metona-tool';
|
||||
import type { MetonaToolDef } from '../harness/types';
|
||||
import { MetonaToolCategory, MetonaRiskLevel } from '../harness/types';
|
||||
// v0.7.3 P3-2: 子进程环境净化收敛到 utils/safe-env.ts 单源(与 run_command 共用)
|
||||
import { buildSafeChildEnv } from '../utils/safe-env';
|
||||
|
||||
// v0.3.0 修复: 安全解析 JSON args,防止数据库中存储了非法 JSON 导致初始化崩溃
|
||||
/** @visibleForTesting 纯函数,供安全表测直接断言 */
|
||||
@@ -97,44 +99,14 @@ export function validateMcpCommand(command: string, args: string[]): void {
|
||||
/**
|
||||
* #6 修复 + 审查修复: 构建安全的子进程环境变量
|
||||
*
|
||||
* 审查修复: 原白名单方案过于激进,剥离了 MCP Server 运行所需的 npm_config_*、代理变量等,
|
||||
* 导致 MCP Server 无法启动。改为黑名单方案:剔除包含敏感后缀的变量,保留其余。
|
||||
*
|
||||
* 注意: GITHUB_TOKEN / SLACK_BOT_TOKEN 等含 _TOKEN 后缀的变量也会被过滤。
|
||||
* v0.7.3 P3-2: 实现收敛到 utils/safe-env.ts(buildSafeChildEnv)——与
|
||||
* run_command 共用同一黑名单(历史双实现已漂移)。MCP 侧无运行时差异注入。
|
||||
* 注意: GITHUB_TOKEN / SLACK_BOT_TOKEN 等含 _TOKEN 后缀的变量会被过滤;
|
||||
* 如果 MCP Server 需要这些凭证,应通过 MCP Server 配置文件传递,而非环境变量。
|
||||
*/
|
||||
/** @visibleForTesting 纯函数,供安全表测直接断言 */
|
||||
export function buildSafeEnv(): Record<string, string> {
|
||||
// 敏感变量后缀黑名单 — 匹配这些后缀的变量不会被传递给子进程
|
||||
const SENSITIVE_SUFFIXES = [
|
||||
'_API_KEY',
|
||||
'_TOKEN',
|
||||
'_SECRET',
|
||||
'_PASSWORD',
|
||||
'_PASSWD',
|
||||
'_CREDENTIAL',
|
||||
'_CREDENTIALS',
|
||||
'_PRIVATE_KEY',
|
||||
];
|
||||
// 敏感变量名黑名单(精确匹配)
|
||||
const SENSITIVE_KEYS = new Set([
|
||||
'DEEPSEEK_API_KEY',
|
||||
'AGNES_API_KEY',
|
||||
'MIMO_API_KEY',
|
||||
'GITEA_PASSWORD',
|
||||
'DATABASE_PASSWORD',
|
||||
]);
|
||||
|
||||
const env: Record<string, string> = {};
|
||||
for (const [key, val] of Object.entries(process.env)) {
|
||||
if (!val) continue;
|
||||
// 跳过敏感变量名
|
||||
if (SENSITIVE_KEYS.has(key)) continue;
|
||||
// 跳过敏感后缀变量
|
||||
if (SENSITIVE_SUFFIXES.some((suffix) => key.toUpperCase().endsWith(suffix))) continue;
|
||||
env[key] = val;
|
||||
}
|
||||
return env;
|
||||
return buildSafeChildEnv();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -171,7 +143,29 @@ export function safeParseHeaders(
|
||||
|
||||
// ===== 类型定义 =====
|
||||
|
||||
export type MCPServerStatus = 'connecting' | 'connected' | 'disconnected' | 'error';
|
||||
export type MCPServerStatus =
|
||||
| 'connecting'
|
||||
| 'connected'
|
||||
| 'disconnected'
|
||||
| 'error'
|
||||
| 'reconnecting';
|
||||
|
||||
// ===== v0.7.3 P4-2: 自动重连策略常量 =====
|
||||
|
||||
/** 最大自动重连次数(超过后停留 error 态,等待用户手动 toggle) */
|
||||
export const MAX_RECONNECT_ATTEMPTS = 3;
|
||||
|
||||
/**
|
||||
* 重连退避间隔(毫秒):5s / 15s / 60s。
|
||||
* 纯函数 nextRetryDelayMs 消费,表测锁定(vitest fake timers 场景)。
|
||||
*/
|
||||
export const RECONNECT_DELAYS_MS = [5_000, 15_000, 60_000] as const;
|
||||
|
||||
/** @visibleForTesting 纯函数 —— 第 attempt 次(1-based)重试前的等待毫秒数 */
|
||||
export function nextRetryDelayMs(attempt: number): number {
|
||||
const idx = Math.min(Math.max(attempt, 1), RECONNECT_DELAYS_MS.length) - 1;
|
||||
return RECONNECT_DELAYS_MS[idx];
|
||||
}
|
||||
|
||||
export interface MCPServerConfig {
|
||||
id: string;
|
||||
@@ -261,6 +255,17 @@ class MCPToolAdapter implements IMetonaTool {
|
||||
|
||||
export class MCPManager {
|
||||
private servers = new Map<string, MCPServerState>();
|
||||
|
||||
// ===== v0.7.3 P4-2: 自动重连状态 =====
|
||||
/** 总开关(mcp.autoReconnect,默认 true;main.ts 启动时注入,配置变更联动) */
|
||||
private autoReconnect = true;
|
||||
/** 各 server 的重连定时器(disconnect/shutdown 时必须清理) */
|
||||
private reconnectTimers = new Map<string, NodeJS.Timeout>();
|
||||
/** 各 server 已尝试的自动重连次数(成功连接后清零) */
|
||||
private reconnectAttempts = new Map<string, number>();
|
||||
/** 待重连的配置快照(重连时从原配置重建连接,避免读 DB 中间态) */
|
||||
private reconnectConfigs = new Map<string, MCPServerConfig>();
|
||||
|
||||
/**
|
||||
* 工具集合变更回调(v0.5.3)
|
||||
*
|
||||
@@ -277,6 +282,93 @@ export class MCPManager {
|
||||
private toolRegistry: ToolRegistry,
|
||||
) {}
|
||||
|
||||
// ===== v0.7.3 P4-2: 自动重连 =====
|
||||
|
||||
/**
|
||||
* 设置自动重连开关(main.ts 启动时按 mcp.autoReconnect 注入;
|
||||
* 配置变更经 shared.ts applyConfigSideEffects 联动)。
|
||||
* 关闭时立即取消所有已排程的重连并清零计数(用户显式意图优先)。
|
||||
*/
|
||||
setAutoReconnect(enabled: boolean): void {
|
||||
this.autoReconnect = enabled;
|
||||
if (!enabled) {
|
||||
this.cancelAllReconnects();
|
||||
}
|
||||
log.debug(`[MCPManager] autoReconnect = ${enabled}`);
|
||||
}
|
||||
|
||||
/** 查询某 server 的重连状态(测试与诊断用) */
|
||||
getReconnectInfo(name: string): { attempts: number; scheduled: boolean } | null {
|
||||
const attempts = this.reconnectAttempts.get(name);
|
||||
const scheduled = this.reconnectTimers.has(name);
|
||||
if (attempts === undefined && !scheduled) return null;
|
||||
return { attempts: attempts ?? 0, scheduled };
|
||||
}
|
||||
|
||||
/** 取消某 server 的重连排程(用户显式断开/移除时调用) */
|
||||
private cancelReconnect(name: string): void {
|
||||
const timer = this.reconnectTimers.get(name);
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
this.reconnectTimers.delete(name);
|
||||
}
|
||||
this.reconnectAttempts.delete(name);
|
||||
this.reconnectConfigs.delete(name);
|
||||
}
|
||||
|
||||
/** 取消全部重连排程(shutdown / 开关关闭时调用) */
|
||||
private cancelAllReconnects(): void {
|
||||
for (const timer of this.reconnectTimers.values()) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
this.reconnectTimers.clear();
|
||||
this.reconnectAttempts.clear();
|
||||
this.reconnectConfigs.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* 连接失败后排程指数退避重连(5s/15s/60s,最多 3 次)。
|
||||
* 状态机进入 'reconnecting'(设置页可见);重试耗尽停留 'error'。
|
||||
* 仅记住传入配置快照 —— 重连时按原配置重建,不读 DB 中间态。
|
||||
*/
|
||||
private scheduleReconnect(name: string, config: MCPServerConfig): void {
|
||||
if (!this.autoReconnect) return;
|
||||
|
||||
const attempts = (this.reconnectAttempts.get(name) ?? 0) + 1;
|
||||
if (attempts > MAX_RECONNECT_ATTEMPTS) {
|
||||
log.warn(
|
||||
`[MCPManager] "${name}" reconnect exhausted (${MAX_RECONNECT_ATTEMPTS} attempts) — staying in error state`,
|
||||
);
|
||||
this.reconnectAttempts.delete(name);
|
||||
this.reconnectConfigs.delete(name);
|
||||
return;
|
||||
}
|
||||
|
||||
this.reconnectAttempts.set(name, attempts);
|
||||
this.reconnectConfigs.set(name, config);
|
||||
const state = this.servers.get(name);
|
||||
if (state) state.status = 'reconnecting';
|
||||
|
||||
const delay = nextRetryDelayMs(attempts);
|
||||
log.info(
|
||||
`[MCPManager] "${name}" reconnect scheduled in ${delay / 1000}s (attempt ${attempts}/${MAX_RECONNECT_ATTEMPTS})`,
|
||||
);
|
||||
const timer = setTimeout(() => {
|
||||
this.reconnectTimers.delete(name);
|
||||
const snapshot = this.reconnectConfigs.get(name);
|
||||
if (!snapshot) return;
|
||||
log.info(
|
||||
`[MCPManager] "${name}" reconnecting (attempt ${attempts}/${MAX_RECONNECT_ATTEMPTS})`,
|
||||
);
|
||||
void this.connectServer(snapshot).catch(() => {
|
||||
/* connectServer 失败路径已自行 scheduleReconnect / 记录状态 */
|
||||
});
|
||||
}, delay);
|
||||
// 定时器不阻塞应用退出
|
||||
timer.unref?.();
|
||||
this.reconnectTimers.set(name, timer);
|
||||
}
|
||||
|
||||
/** 注册工具集合变更回调(main.ts 在 AgentEngineManager 创建后注入) */
|
||||
setOnToolsChanged(callback: () => void): void {
|
||||
this.toolsChangedCallback = callback;
|
||||
@@ -356,10 +448,9 @@ export class MCPManager {
|
||||
async connectServer(config: MCPServerConfig): Promise<void> {
|
||||
const { name } = config;
|
||||
|
||||
// 断开已有连接
|
||||
if (this.servers.has(name)) {
|
||||
await this.disconnectServer(name);
|
||||
}
|
||||
// 断开已有连接(内部拆除 —— 保留重连簿记,否则重试计数被清零、
|
||||
// 退避序列永远停在第 1 次;用户显式断开走 disconnectServer)
|
||||
await this.teardownConnection(name);
|
||||
|
||||
this.servers.set(name, {
|
||||
config,
|
||||
@@ -441,6 +532,15 @@ export class MCPManager {
|
||||
state.connectedAt = Date.now();
|
||||
state.error = undefined;
|
||||
|
||||
// v0.7.3 P4-2: 连接成功 —— 清零重连计数并取消排程
|
||||
this.reconnectAttempts.delete(name);
|
||||
this.reconnectConfigs.delete(name);
|
||||
const pendingTimer = this.reconnectTimers.get(name);
|
||||
if (pendingTimer) {
|
||||
clearTimeout(pendingTimer);
|
||||
this.reconnectTimers.delete(name);
|
||||
}
|
||||
|
||||
// 更新数据库
|
||||
const db = this.getDB();
|
||||
db.prepare(
|
||||
@@ -468,6 +568,9 @@ export class MCPManager {
|
||||
`,
|
||||
).run((error as Error).message, name);
|
||||
|
||||
// v0.7.3 P4-2: 失败后排程指数退避自动重连(开关关闭时 no-op)
|
||||
this.scheduleReconnect(name, config);
|
||||
|
||||
log.error(`MCP server "${name}" connection failed:`, error);
|
||||
throw error;
|
||||
}
|
||||
@@ -476,14 +579,15 @@ export class MCPManager {
|
||||
/**
|
||||
* 断开 MCP Server
|
||||
*/
|
||||
async disconnectServer(name: string): Promise<void> {
|
||||
/**
|
||||
* 内部连接拆除(保留重连簿记)—— connectServer 重连前的清理动作。
|
||||
* 与 disconnectServer 的区别:不清 reconnectAttempts/Timers/Configs,
|
||||
* 否则自动重连的每次重试都会把自己的计数清零(退避序列永远停在第 1 次)。
|
||||
*/
|
||||
private async teardownConnection(name: string): Promise<void> {
|
||||
const state = this.servers.get(name);
|
||||
if (!state) return;
|
||||
|
||||
// 从 ToolRegistry 注销
|
||||
this.toolRegistry.unregisterMCPTools(name);
|
||||
|
||||
// 关闭客户端
|
||||
if (state.client) {
|
||||
try {
|
||||
await state.client.close();
|
||||
@@ -491,13 +595,24 @@ export class MCPManager {
|
||||
// 忽略关闭错误
|
||||
}
|
||||
}
|
||||
|
||||
state.status = 'disconnected';
|
||||
state.client = null;
|
||||
state.tools = [];
|
||||
|
||||
// v0.5.3: 工具集合已变化 — 通知调用方同步引擎(已有引擎需移除失效工具定义)
|
||||
this.notifyToolsChanged();
|
||||
}
|
||||
|
||||
/**
|
||||
* 断开 MCP Server(用户显式语义:取消重连排程 + 拆除连接)
|
||||
*/
|
||||
async disconnectServer(name: string): Promise<void> {
|
||||
// v0.7.3 P4-2: 用户显式断开/移除 —— 取消重连排程(用户意图优先于自动重试)。
|
||||
// 无论是否存在连接态(error/reconnecting 态的 server 也可能被移除)都执行。
|
||||
this.cancelReconnect(name);
|
||||
await this.teardownConnection(name);
|
||||
|
||||
const state = this.servers.get(name);
|
||||
if (state) {
|
||||
state.status = 'disconnected';
|
||||
}
|
||||
|
||||
log.info(`MCP server "${name}" disconnected`);
|
||||
}
|
||||
@@ -601,12 +716,16 @@ export class MCPManager {
|
||||
status: MCPServerStatus;
|
||||
toolCount: number;
|
||||
error?: string;
|
||||
/** v0.7.3 P4-2: reconnecting 状态下的已尝试次数(第 N/3 次排程) */
|
||||
reconnectAttempt?: number;
|
||||
}> {
|
||||
return Array.from(this.servers.values()).map((s) => ({
|
||||
name: s.config.name,
|
||||
status: s.status,
|
||||
toolCount: s.tools.length,
|
||||
error: s.error,
|
||||
reconnectAttempt:
|
||||
s.status === 'reconnecting' ? this.reconnectAttempts.get(s.config.name) : undefined,
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -618,6 +737,7 @@ export class MCPManager {
|
||||
status: MCPServerStatus;
|
||||
toolCount: number;
|
||||
error?: string;
|
||||
reconnectAttempt?: number;
|
||||
} | null {
|
||||
const state = this.servers.get(name);
|
||||
if (!state) return null;
|
||||
@@ -626,6 +746,8 @@ export class MCPManager {
|
||||
status: state.status,
|
||||
toolCount: state.tools.length,
|
||||
error: state.error,
|
||||
reconnectAttempt:
|
||||
state.status === 'reconnecting' ? this.reconnectAttempts.get(state.config.name) : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -633,6 +755,8 @@ export class MCPManager {
|
||||
* 关闭所有连接
|
||||
*/
|
||||
async shutdown(): Promise<void> {
|
||||
// v0.7.3 P4-2: 退出前取消全部重连排程(timer 已 unref,此处幂等清理)
|
||||
this.cancelAllReconnects();
|
||||
const names = Array.from(this.servers.keys());
|
||||
await Promise.allSettled(names.map((n) => this.disconnectServer(n)));
|
||||
log.info('MCP Manager shut down');
|
||||
|
||||
@@ -18,7 +18,15 @@
|
||||
*/
|
||||
|
||||
import { join } from 'path';
|
||||
import { appendFileSync, existsSync, mkdirSync, promises } from 'fs';
|
||||
import {
|
||||
appendFileSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
promises,
|
||||
readdirSync,
|
||||
statSync,
|
||||
unlinkSync,
|
||||
} from 'fs';
|
||||
import log from 'electron-log';
|
||||
|
||||
// ===== 事件类型 =====
|
||||
@@ -265,6 +273,82 @@ export class SessionRecorder {
|
||||
return first?.filePath ?? null;
|
||||
}
|
||||
|
||||
// ===== v0.7.3 P3-3: JSONL 录制文件生命周期治理 =====
|
||||
|
||||
/** JSONL 录制文件名模式(仅治理本服务产出的文件) */
|
||||
private static readonly RECORDING_NAME = /^session_.+\.jsonl$/;
|
||||
|
||||
/**
|
||||
* 统计录制目录中的 JSONL 文件(设置页展示 + 清理前置确认用)。
|
||||
* 目录不存在 / 统计失败返回零值(不抛错)。
|
||||
*/
|
||||
getRecordingStats(): { count: number; totalBytes: number } {
|
||||
try {
|
||||
const logsDir = join(this.workspacePath, 'logs');
|
||||
if (!existsSync(logsDir)) return { count: 0, totalBytes: 0 };
|
||||
const names = readdirSync(logsDir).filter((n) => SessionRecorder.RECORDING_NAME.test(n));
|
||||
let totalBytes = 0;
|
||||
for (const name of names) {
|
||||
try {
|
||||
totalBytes += statSync(join(logsDir, name)).size;
|
||||
} catch {
|
||||
/* 单文件统计失败跳过 */
|
||||
}
|
||||
}
|
||||
return { count: names.length, totalBytes };
|
||||
} catch {
|
||||
return { count: 0, totalBytes: 0 };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理旧录制文件(按修改时间保留最近 maxFiles 个,默认 200)。
|
||||
*
|
||||
* 背景:workspace/logs/session_*.jsonl 随使用无限累积无任何清理路径。
|
||||
* 清理策略:mtime 降序保留前 maxFiles 个,其余删除;仅匹配本服务的
|
||||
* session_*.jsonl 命名(用户自放文件不受影响)。启动时(main.ts)与
|
||||
* 设置页手动清理共用本方法。
|
||||
*
|
||||
* @returns 实际删除的文件数
|
||||
*/
|
||||
pruneOldRecordings(maxFiles = 200): number {
|
||||
try {
|
||||
const logsDir = join(this.workspacePath, 'logs');
|
||||
if (!existsSync(logsDir)) return 0;
|
||||
const entries = readdirSync(logsDir)
|
||||
.filter((n) => SessionRecorder.RECORDING_NAME.test(n))
|
||||
.map((name) => {
|
||||
try {
|
||||
return { name, mtime: statSync(join(logsDir, name)).mtimeMs };
|
||||
} catch {
|
||||
return { name, mtime: 0 };
|
||||
}
|
||||
})
|
||||
.sort((a, b) => b.mtime - a.mtime);
|
||||
|
||||
if (entries.length <= maxFiles) return 0;
|
||||
const toDelete = entries.slice(maxFiles);
|
||||
let deleted = 0;
|
||||
for (const entry of toDelete) {
|
||||
try {
|
||||
unlinkSync(join(logsDir, entry.name));
|
||||
deleted++;
|
||||
} catch {
|
||||
/* 单文件删除失败(占用中)跳过 */
|
||||
}
|
||||
}
|
||||
if (deleted > 0) {
|
||||
log.info(
|
||||
`[SessionRecorder] Pruned ${deleted} old recording file(s) (kept ${Math.min(maxFiles, entries.length)})`,
|
||||
);
|
||||
}
|
||||
return deleted;
|
||||
} catch (err) {
|
||||
log.warn('[SessionRecorder] pruneOldRecordings failed:', err);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 私有方法 =====
|
||||
|
||||
/**
|
||||
|
||||
@@ -247,10 +247,12 @@ export class SessionService {
|
||||
const db = this.getDBFn();
|
||||
const op = inclusive ? '>=' : '>';
|
||||
|
||||
// 先查锚点 rowid(删除后无法再定位)
|
||||
// 先查锚点 rowid 与时间戳(删除后无法再定位)
|
||||
const anchor = db
|
||||
.prepare('SELECT rowid AS rid FROM messages WHERE session_id = ? AND id = ?')
|
||||
.get(sessionId, messageId) as { rid: number } | undefined;
|
||||
.prepare(
|
||||
'SELECT rowid AS rid, created_at AS ts FROM messages WHERE session_id = ? AND id = ?',
|
||||
)
|
||||
.get(sessionId, messageId) as { rid: number; ts: number } | undefined;
|
||||
if (!anchor) return false;
|
||||
|
||||
const result = db
|
||||
@@ -270,6 +272,40 @@ export class SessionService {
|
||||
'DELETE FROM session_summaries WHERE session_id = ? AND summarized_until_rowid >= ?',
|
||||
).run(sessionId, anchor.rid + (inclusive ? 0 : 1));
|
||||
|
||||
// v0.7.3 P1-2 根治: 同步截断 metadata 中的 TRACE 步骤。
|
||||
// 此前编辑重发/重新生成只删消息 —— traceSteps 残留,Trace 面板出现
|
||||
// "幽灵步骤"(与 /clear 的 metadata 残留同类,v0.7.2 A1 只修了 clear 路径)。
|
||||
// 截断语义:锚点消息(inclusive 时含锚点)触发的 run 及其之后全部作废 ——
|
||||
// 按 startedAt < 锚点消息 created_at 过滤保留更早 run 的步骤(严格小于:
|
||||
// 锚点消息触发的 run 与消息同毫秒落库,等值属于"锚点侧"必须丢弃 ——
|
||||
// 宁可多删一个边界步骤也不留幽灵步骤)。tokenUsage 为最近一次 run 的
|
||||
// 累计展示值,紧随其后的重发 run 会重写,无需修正。
|
||||
try {
|
||||
const row = db.prepare('SELECT metadata FROM sessions WHERE id = ?').get(sessionId) as
|
||||
| { metadata: string }
|
||||
| undefined;
|
||||
if (row?.metadata) {
|
||||
const data = JSON.parse(row.metadata) as {
|
||||
traceSteps?: Array<{ startedAt?: number }>;
|
||||
tokenUsage?: unknown;
|
||||
};
|
||||
if (Array.isArray(data.traceSteps)) {
|
||||
const kept = data.traceSteps.filter(
|
||||
(s) => typeof s?.startedAt !== 'number' || s.startedAt < anchor.ts,
|
||||
);
|
||||
if (kept.length !== data.traceSteps.length) {
|
||||
data.traceSteps = kept;
|
||||
db.prepare('UPDATE sessions SET metadata = ? WHERE id = ?').run(
|
||||
JSON.stringify(data),
|
||||
sessionId,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// metadata 解析失败不阻断截断主流程(与截断语义无耦合)
|
||||
}
|
||||
|
||||
log.info(
|
||||
`Session truncated: ${sessionId} (${result.changes} messages removed after ${messageId})`,
|
||||
);
|
||||
@@ -355,12 +391,11 @@ export class SessionService {
|
||||
|
||||
/**
|
||||
* 删除一条消息
|
||||
*
|
||||
* v0.7.3 P1-3: 随 sessions:deleteMessage 死通道一并移除 —— 该方法不回减
|
||||
* sessions.message_count(saveMessage 加、删除不加的计数漂移面),且渲染层
|
||||
* 从未有调用方。消息删除语义由 truncateMessagesAfter(含计数修正)覆盖。
|
||||
*/
|
||||
deleteMessage(messageId: string): boolean {
|
||||
const db = this.getDBFn();
|
||||
const result = db.prepare('DELETE FROM messages WHERE id = ?').run(messageId);
|
||||
return result.changes > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空会话所有消息
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
/**
|
||||
* Title Generator — 会话标题 LLM 自动生成(v0.7.3 P4-1)
|
||||
*
|
||||
* 背景:首轮消息后前端仅以"用户首条消息截前 30 字符"作为会话标题
|
||||
* (agent-store.sendMessage),中文长句体验差且语义压缩生硬。
|
||||
*
|
||||
* 本服务在会话首个完成的 run 之后(terminationReason === 'completed')用主
|
||||
* Provider adapter 发起一次极小的非流式请求(maxTokens 32 / temperature 0.3 /
|
||||
* thinking 关闭),生成 ≤16 字的精炼标题并写回 sessions 表。生成失败(网络 /
|
||||
* 配额 / 解析失败)静默回退——前端首 30 字符截断标题保持有效,无损可用性。
|
||||
*
|
||||
* 契约:
|
||||
* - 每个会话生命周期内仅生成一次(内存 Set 幂等,进程重启后自然重置——
|
||||
* 已有非默认标题的会话通过 hasCustomTitle 判定跳过,不会重复生成);
|
||||
* - 标题经 sanitizeTitle 清洗:剥离 markdown/引号/换行/前后缀冒号,
|
||||
* 折叠空白,超长截断,空结果返回 null(调用方保持原标题不变)。
|
||||
*/
|
||||
|
||||
import { nanoid } from 'nanoid';
|
||||
import log from 'electron-log';
|
||||
import type { IMetonaProviderAdapter, MetonaRequest } from '../harness/types';
|
||||
import type { SessionService } from './session.service';
|
||||
|
||||
/** 生成标题的最大长度(字符)——超过即截断 */
|
||||
const MAX_TITLE_LENGTH = 40;
|
||||
|
||||
/** 传给 LLM 的用户消息 / 回答摘录长度 */
|
||||
const EXCERPT_LENGTH = 600;
|
||||
|
||||
/** LLM 调用超时(标题生成不应阻塞任何主流程) */
|
||||
const TITLE_TIMEOUT_MS = 15_000;
|
||||
|
||||
/**
|
||||
* 清洗 LLM 返回的标题文本。
|
||||
*
|
||||
* 规则(按序应用):
|
||||
* 1. 剥离 markdown 代码围栏与首尾 `#`/`-`/`*` 列表标记;
|
||||
* 2. 剥离成对包裹引号(中英文单双引号);
|
||||
* 3. 剥离 "标题:"/"Title:" 这类自述前缀;
|
||||
* 4. 折叠全部空白(含换行)为单个空格并 trim;
|
||||
* 5. 超过 maxLen 截断;
|
||||
* 6. 空结果返回 null(调用方保持原标题)。
|
||||
*/
|
||||
export function sanitizeTitle(raw: string, maxLen: number = MAX_TITLE_LENGTH): string | null {
|
||||
if (!raw || typeof raw !== 'string') return null;
|
||||
|
||||
let title = raw.trim();
|
||||
// 1/2. markdown 围栏、列表标记与包裹引号 —— 循环应用直至稳定(处理嵌套包装
|
||||
// 如 ```"标题"``` / 多层引号;剥除全部首尾引号字符而非仅成对项,
|
||||
// 使 '"""' 这类纯符号输入收敛为空 → null)
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const before = title;
|
||||
title = title
|
||||
.replace(/^```(?:[a-z]*)\s*/i, '')
|
||||
.replace(/\s*```$/i, '')
|
||||
.replace(/^[#\-*>]+\s*/, '')
|
||||
.replace(/^["'“”『』「"]+/, '')
|
||||
.replace(/["'“”『』「"]+$/, '');
|
||||
if (title === before) break;
|
||||
}
|
||||
// 3. 自述前缀(标题:/Title:/会话标题: 等)
|
||||
title = title.replace(/^(?:标题|会话标题|题目|title)\s*[::]\s*/i, '');
|
||||
// 4. 折叠空白(换行合并——LLM 偶发多行输出时取首行语义)
|
||||
title = title.replace(/\s+/g, ' ').trim();
|
||||
// 5. 截断
|
||||
if (title.length > maxLen) title = title.slice(0, maxLen).trimEnd();
|
||||
// 6. 空结果
|
||||
return title.length > 0 ? title : null;
|
||||
}
|
||||
|
||||
export class TitleGenerator {
|
||||
/** 已生成过标题的会话(进程级幂等) */
|
||||
private generated = new Set<string>();
|
||||
/** 进行中的生成任务(防并发重复调用) */
|
||||
private running = new Map<string, Promise<string | null>>();
|
||||
|
||||
constructor(
|
||||
private getAdapter: () => IMetonaProviderAdapter,
|
||||
private sessionService: SessionService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 为会话生成标题(fire-and-forget 调用;失败静默)。
|
||||
*
|
||||
* @param sessionId 会话 ID
|
||||
* @param userMessage 用户原始消息(干净版本,不含注入前缀)
|
||||
* @param assistantAnswer Agent 最终回答
|
||||
* @returns 生成的标题(未生成/失败返回 null)
|
||||
*/
|
||||
async maybeGenerateTitle(
|
||||
sessionId: string,
|
||||
userMessage: string,
|
||||
assistantAnswer: string,
|
||||
): Promise<string | null> {
|
||||
if (!sessionId || typeof sessionId !== 'string') return null;
|
||||
// 输入门控:双向内容均为空无生成意义
|
||||
if (!userMessage?.trim() && !assistantAnswer?.trim()) return null;
|
||||
|
||||
// 并发去重先于幂等短路 —— 同一会话进行中的生成必须复用同一 Promise,
|
||||
// 而不能被"已占位"的幂等判断吞掉(否则并发第二调用拿到 null)
|
||||
const existing = this.running.get(sessionId);
|
||||
if (existing) return existing;
|
||||
// 幂等:每会话仅一次(占位同步完成,先于任何 await)
|
||||
if (this.generated.has(sessionId)) return null;
|
||||
|
||||
this.generated.add(sessionId);
|
||||
const task = this.generate(sessionId, userMessage, assistantAnswer).finally(() => {
|
||||
this.running.delete(sessionId);
|
||||
});
|
||||
this.running.set(sessionId, task);
|
||||
return task;
|
||||
}
|
||||
|
||||
private async generate(
|
||||
sessionId: string,
|
||||
userMessage: string,
|
||||
assistantAnswer: string,
|
||||
): Promise<string | null> {
|
||||
try {
|
||||
const adapter = this.getAdapter();
|
||||
if (!adapter) return null;
|
||||
|
||||
// 已有自定义标题(用户手动重命名 / 前端首条截断标题)时不覆盖,
|
||||
// 避免用户主动命名被 LLM 标题冲掉
|
||||
const sessions = this.sessionService.list();
|
||||
const current = sessions.find((s) => s.id === sessionId);
|
||||
if (current && current.title !== '新会话') {
|
||||
log.debug(`[TitleGenerator] session ${sessionId} already titled "${current.title}" — skip`);
|
||||
return null;
|
||||
}
|
||||
|
||||
const request: MetonaRequest = {
|
||||
meta: {
|
||||
sessionId: 'title-generation',
|
||||
iteration: 0,
|
||||
requestId: `tg_${nanoid(12)}`,
|
||||
timestamp: Date.now(),
|
||||
agentVersion: '1.0.0',
|
||||
},
|
||||
systemPrompt: {
|
||||
roleDefinition:
|
||||
'You generate concise conversation titles for an AI assistant desktop app.',
|
||||
outputConstraints:
|
||||
'Given the first user message and the assistant reply, output ONE title of at most 16 characters ' +
|
||||
'in the same language as the user message. The title must capture the core topic or task. ' +
|
||||
'No quotes, no markdown, no ending punctuation, no explanations — output the title text ONLY.',
|
||||
safetyGuidelines:
|
||||
'Do not include sensitive data (passwords, keys, personal info) in the title.',
|
||||
},
|
||||
messages: [
|
||||
{
|
||||
role: 'user',
|
||||
content:
|
||||
`User message: ${userMessage.slice(0, EXCERPT_LENGTH)}\n\n` +
|
||||
`Assistant reply: ${assistantAnswer.slice(0, EXCERPT_LENGTH)}\n\n` +
|
||||
`Output the title only.`,
|
||||
timestamp: Date.now(),
|
||||
},
|
||||
],
|
||||
params: {
|
||||
maxTokens: 32,
|
||||
temperature: 0.3,
|
||||
stream: false,
|
||||
thinkingEnabled: false,
|
||||
thinkingEffort: 'low',
|
||||
},
|
||||
};
|
||||
|
||||
// 超时保护:标题生成绝不能拖慢会话收尾
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
const timeoutPromise = new Promise<never>((_, reject) => {
|
||||
timer = setTimeout(() => reject(new Error('title generation timeout')), TITLE_TIMEOUT_MS);
|
||||
});
|
||||
const response = await Promise.race([adapter.send(request), timeoutPromise]);
|
||||
const title = sanitizeTitle(response.content);
|
||||
if (!title) {
|
||||
log.debug(
|
||||
`[TitleGenerator] session ${sessionId}: empty/unsanitizable title, keeping fallback`,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
const renamed = this.sessionService.rename(sessionId, title);
|
||||
if (renamed) {
|
||||
log.info(`[TitleGenerator] session ${sessionId} titled: "${title}"`);
|
||||
}
|
||||
return renamed ? title : null;
|
||||
} finally {
|
||||
if (timer) clearTimeout(timer);
|
||||
}
|
||||
} catch (err) {
|
||||
// 静默回退:标题失败不影响会话可用性(前端首条截断标题仍在)
|
||||
log.debug(
|
||||
`[TitleGenerator] session ${sessionId} title generation failed:`,
|
||||
(err as Error).message,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user