feat: v0.8.1 记忆深化 · 观测闭环 · 体验收口 — 窗口/输出上限全局单一配置 · 2478 用例全量回归 + E2E 冒烟
CI / 类型检查 + Lint + 单元测试 (push) Failing after 9m8s
CI / 全量测试 (Electron ABI) (push) Failing after 6m0s
CI / 产物编译验证 (push) Successful in 10m58s

硬性契约:删除代码中一切写死的上下文窗口与最大输出上限(含六家模型元信息
钳制与全部兜底值)——唯一合法来源是设置面板「上下文长度」(llm.contextWindow)
与「最大输出上限」(llm.maxTokens),跨 Provider/模型原样透传。

P0 正确性收口:
- 迁移 11/12(SCHEMA_VERSION 5):记忆表 embedding 列 + 分 Provider 窗口键清理
- 记忆生命周期接线:会话终态清理 working memory / episodic 90 天 TTL / access_count 回写
- 回放缓冲模块化 + 会话终态清理(杜绝 4MB/会话内存滞留)
- i18n 收口:主进程 main-locale(zh/en,ui.locale 热切换)+ 渲染层 17 处出层

P1 能力演进:
- 本地向量混合检索:0.6×向量余弦 + 0.4×TF-IDF,Ollama embeddings 首次投产,
  存量记忆惰性回填,嵌入不可用自动回退 TF-IDF
- MEMORY.md 维护闭环:固化去重消除截断盲区;两阶段维护(AI 建议 → 用户确认 →
  原子改写 + 语义记忆双轨同步 + 审计);>50KB 告警
- 可观测闭环:cacheTokens 引擎→前端透传(Token 面板命中率/成本行)+ 输入框
  上下文占用指示条
- MCP Prompts/Resources 对话可用:/mcp:{server}:{prompt} 与 @mcp:{server}:{uri}

P2 体验补全:
- 工具自定义策略(正则白/黑名单 + 频率 + 强制确认,热生效)
- 连续 ≥3 同类工具确认聚合为单弹框
- 会话消息游标分页(首屏 200 条向上翻页)
- 开机自启;Playwright + Electron E2E 冒烟(本地 mock LLM 零外联)

Review 回归修复:MCP 大小写失配 / 分页状态复位 / 清空=未配置语义(Number(null)=0
隐患)/ MEMORY.md 告警位置 / working_memories FK(迁移 13)/ 全局配置层废键清理;
附带根治权限加固启动时序、代理回环放行、safeStorage 降级、悬空 symlink 逃逸。

验证:typecheck/lint 0 问题;test:electron 2478/2478(0 跳过);E2E 2/2;
docs/v0.8.1-迭代实施清单.md 全项留档。
This commit is contained in:
2026-09-08 09:35:58 +08:00
parent 839860083f
commit 9b45c445bf
85 changed files with 5286 additions and 1158 deletions
@@ -88,6 +88,7 @@ describe('ConfirmationHook — 多窗口广播(v0.7.2 P2-7', () => {
}
it('确认请求广播到所有存活窗口(而非仅 mainWindow', async () => {
vi.useFakeTimers();
const a = makeTrackedWindow();
const b = makeTrackedWindow();
const destroyed = makeTrackedWindow(true);
@@ -96,6 +97,8 @@ describe('ConfirmationHook — 多窗口广播(v0.7.2 P2-7', () => {
const hook = new ConfirmationHook(null, null);
hook.setToolDefs([HIGH_RISK_DEF]);
const p = hook.beforeExecute(makeToolCall(), 'sess');
// v0.8.1 P2-2: 聚合窗口(800ms)结束才广播 —— 推进 fake timers
await vi.advanceTimersByTimeAsync(1000);
// 所有存活窗口均收到确认请求(携带 expiresAt 倒计时契约)
expect(a.send).toHaveBeenCalledWith(
@@ -111,20 +114,25 @@ describe('ConfirmationHook — 多窗口广播(v0.7.2 P2-7', () => {
hook.resolveConfirmation(hook.getPendingConfirmations()[0].toolCallId, true, false, false);
expect((await p).blocked).toBe(false);
vi.useRealTimers();
});
it('getAllWindows 为空时回退到注入的 mainWindow(向后兼容)', async () => {
vi.useFakeTimers();
const mainWin = makeMockWindow();
getAllWindowsMock.mockReturnValue([]);
const hook = new ConfirmationHook(mainWin, null);
hook.setToolDefs([HIGH_RISK_DEF]);
const p = hook.beforeExecute(makeToolCall(), 'sess');
// v0.8.1 P2-2: 推进聚合窗口后断言广播
await vi.advanceTimersByTimeAsync(1000);
expect((mainWin.webContents as unknown as { send: Mock }).send).toHaveBeenCalledWith(
'tool:confirmationRequest',
expect.objectContaining({ toolName: 'run_command' }),
);
hook.resolveConfirmation(hook.getPendingConfirmations()[0].toolCallId, true, false, false);
expect((await p).blocked).toBe(false);
vi.useRealTimers();
});
it('全部窗口不可达时 fail-closed 阻断(no main window available', async () => {
@@ -524,3 +532,92 @@ describe('ConfirmationHook — 跨会话隔离(v0.5.0', () => {
expect((await hook.beforeExecute(makeToolCall(), 'sess-b')).blocked).toBe(false);
});
});
// ===== v0.8.1 P2-2: 连续同类工具批量确认聚合 =====
describe('ConfirmationHook — 同类工具批量确认聚合(v0.8.1 P2-2', () => {
/** 单次 promptbeforeExecute 阻塞等待确认,不消费 promise) */
function startPrompt(hook: ConfirmationHook, id: string): Promise<unknown> {
return hook.beforeExecute(
{ id, name: 'run_command', args: {}, iteration: 1, timestamp: Date.now() },
'sess',
);
}
/** 本 describe 专用的 send 追踪窗口(makeTrackedWindow 定义在上一 describe 作用域) */
function makeWindow(): { win: BrowserWindow; send: Mock } {
const send = vi.fn();
const win = {
isDestroyed: () => false,
webContents: { send },
} as unknown as BrowserWindow;
return { win, send };
}
function makeRunCommandDef(): MetonaToolDef {
return {
...HIGH_RISK_DEF,
name: 'run_command',
requiresPermission: true,
};
}
it('3 个同类并行请求 → 聚合为单条 batch 事件(无逐条事件)', async () => {
vi.useFakeTimers();
const w = makeWindow();
getAllWindowsMock.mockReturnValue([w.win]);
const hook = new ConfirmationHook(null, null);
hook.setToolDefs([makeRunCommandDef()]);
const prompts = [
startPrompt(hook, 'tc_1'),
startPrompt(hook, 'tc_2'),
startPrompt(hook, 'tc_3'),
];
// 达到阈值立即 flush
await vi.advanceTimersByTimeAsync(0);
const batchCalls = (w.send as Mock).mock.calls.filter(
(c) => c[0] === 'tool:confirmationRequestBatch',
);
expect(batchCalls).toHaveLength(1);
expect(
(batchCalls[0][1] as unknown[]).map((r) => (r as { toolCallId: string }).toolCallId),
).toEqual(['tc_1', 'tc_2', 'tc_3']);
// 不应再发送逐条事件
const individual = (w.send as Mock).mock.calls.filter(
(c) => c[0] === 'tool:confirmationRequest',
);
expect(individual).toHaveLength(0);
for (const id of ['tc_1', 'tc_2', 'tc_3']) {
hook.resolveConfirmation(id, true, false, false);
}
await Promise.all(prompts);
vi.useRealTimers();
});
it('2 个同类请求(低于阈值)→ 窗口结束逐条广播(原行为)', async () => {
vi.useFakeTimers();
const w = makeWindow();
getAllWindowsMock.mockReturnValue([w.win]);
const hook = new ConfirmationHook(null, null);
hook.setToolDefs([makeRunCommandDef()]);
const prompts = [startPrompt(hook, 'tc_a'), startPrompt(hook, 'tc_b')];
await vi.advanceTimersByTimeAsync(1000);
expect(
(w.send as Mock).mock.calls.filter((c) => c[0] === 'tool:confirmationRequestBatch'),
).toHaveLength(0);
expect(
(w.send as Mock).mock.calls.filter((c) => c[0] === 'tool:confirmationRequest'),
).toHaveLength(2);
for (const id of ['tc_a', 'tc_b']) {
hook.resolveConfirmation(id, true, false, false);
}
await Promise.all(prompts);
vi.useRealTimers();
});
});
+68 -4
View File
@@ -467,6 +467,39 @@ export class ConfirmationHook implements PreToolHook {
*/
private lastTimeoutToastAt = 0;
// ===== v0.8.1 P2-2: 连续同类工具批量确认聚合 =====
/**
* 同 (sessionId, toolName) 的请求在 AGGREGATION_WINDOW_MS 内聚合:窗口结束时
* 若积压 >= AGGREGATION_THRESHOLD 条则只广播一条 `tool:confirmationRequestBatch`
* (前端一次性拉取/渲染全部 pending),否则逐条广播(原行为)。
* 目的:批量重构等场景(并行工具连续触发 3+ 同类确认)不再弹出 N 个连续弹框。
*/
private static readonly AGGREGATION_WINDOW_MS = 800;
private static readonly AGGREGATION_THRESHOLD = 3;
private aggregationBuffers = new Map<
string,
{ requests: ConfirmationRequest[]; timer: NodeJS.Timeout | null }
>();
private flushAggregationBuffer(key: string): void {
const buf = this.aggregationBuffers.get(key);
if (!buf) return;
this.aggregationBuffers.delete(key);
if (buf.timer) {
clearTimeout(buf.timer);
buf.timer = null;
}
if (buf.requests.length >= ConfirmationHook.AGGREGATION_THRESHOLD) {
// 批量事件:携带完整请求列表(expiresAt 已含)
this.broadcastToAllWindows('tool:confirmationRequestBatch', buf.requests);
} else {
// 逐条广播(原行为)
for (const req of buf.requests) {
this.broadcastToAllWindows('tool:confirmationRequest', req);
}
}
}
private waitForConfirmation(request: ConfirmationRequest, sessionId: string): Promise<boolean> {
return new Promise<boolean>((resolve) => {
const expiresAt = Date.now() + this.confirmationTimeoutMs;
@@ -518,10 +551,24 @@ export class ConfirmationHook implements PreToolHook {
// 发送确认请求到渲染进程(携带过期时间戳,供前端倒计时)
// v0.7.2 P2-7: 广播到所有窗口 —— 多窗口场景下任意窗口发起的会话
// 触发的确认请求都可达(ConfirmationDialog 按会话过滤展示)
this.broadcastToAllWindows('tool:confirmationRequest', {
...request,
expiresAt,
});
// v0.8.1 P2-2: 聚合窗口 —— 同会话同类工具的并行请求进入缓冲;
// 窗口结束达到阈值时合并为单条批量事件,否则逐条广播(原行为)
const aggKey = `${sessionId}:${request.toolName}`;
let buf = this.aggregationBuffers.get(aggKey);
if (!buf) {
buf = { requests: [], timer: null };
this.aggregationBuffers.set(aggKey, buf);
buf.timer = setTimeout(
() => this.flushAggregationBuffer(aggKey),
ConfirmationHook.AGGREGATION_WINDOW_MS,
);
}
buf.requests.push({ ...request, expiresAt });
// 窗口内积压已达阈值 → 立即 flush(不等满窗口)
if (buf.requests.length >= ConfirmationHook.AGGREGATION_THRESHOLD) {
this.flushAggregationBuffer(aggKey);
}
});
}
@@ -540,6 +587,9 @@ export class ConfirmationHook implements PreToolHook {
pending.resolve(false);
}
this.pendingConfirmations.clear();
// v0.8.1 P2-2: 清空聚合缓冲(resolve(false) 已由逐条 timer 覆盖……缓冲内的
// 请求本身尚未注册 pending,需丢弃防止稍后广播已失效请求)
this.aggregationBuffers.clear();
return;
}
for (const [id, pending] of this.pendingConfirmations) {
@@ -548,6 +598,20 @@ export class ConfirmationHook implements PreToolHook {
pending.resolve(false);
this.pendingConfirmations.delete(id);
}
// v0.8.1 P2-2: 丢弃该会话尚未广播的聚合缓冲
for (const [key, buf] of this.aggregationBuffers) {
if (!key.startsWith(`${sessionId}:`)) continue;
if (buf.timer) clearTimeout(buf.timer);
for (const req of buf.requests) {
const pending = this.pendingConfirmations.get(req.toolCallId);
if (pending) {
clearTimeout(pending.timer);
pending.resolve(false);
this.pendingConfirmations.delete(req.toolCallId);
}
}
this.aggregationBuffers.delete(key);
}
}
/**
+21 -3
View File
@@ -29,7 +29,11 @@ export interface PostToolHook {
export class AuditLogHook implements PostToolHook {
constructor(private auditService: AuditService) {}
async afterExecute(toolCall: MetonaToolCall, result: MetonaToolResult, sessionId: string): Promise<void> {
async afterExecute(
toolCall: MetonaToolCall,
result: MetonaToolResult,
sessionId: string,
): Promise<void> {
// #17 修复: AuditHook 应为 "fire and forget"hook 失败不应影响工具执行链
// 虽然 AuditService.log() 内部已 try-catch,但 hook 层再加一层防御,
// 确保任何意外异常(如 getDB 抛错、JSON.stringify 失败)都不会冒泡到 ToolRegistry
@@ -59,11 +63,24 @@ export class MemoryTriggerHook implements PostToolHook {
/** 单次工具结果存储上限(字符),防止过大内容淹没记忆系统 */
private readonly MAX_MEMORY_CONTENT = 500;
/**
* v0.8.1 P0-2: 工具结果类情节记忆的 TTL(90 天)。
* 此前 episodic_memories.expires_at 全链路无写入方 —— cleanupExpired(健康检查
* 周期调用)空转,情节记忆只增不减。现为此类低价值记忆写入过期时间,90 天后
* 由周期清理回收;用户偏好等高价值记忆(consolidator 写入 semantic 表)不受影响。
*/
private readonly EPISODIC_TTL_MS = 90 * 24 * 60 * 60 * 1000;
constructor(private memoryManager: MemoryManager) {}
async afterExecute(toolCall: MetonaToolCall, result: MetonaToolResult, sessionId: string): Promise<void> {
async afterExecute(
toolCall: MetonaToolCall,
result: MetonaToolResult,
sessionId: string,
): Promise<void> {
if (this.memorableTools.includes(toolCall.name) && result.success) {
const content = typeof result.result === 'string' ? result.result : JSON.stringify(result.result);
const content =
typeof result.result === 'string' ? result.result : JSON.stringify(result.result);
try {
this.memoryManager.store({
type: 'episodic',
@@ -71,6 +88,7 @@ export class MemoryTriggerHook implements PostToolHook {
source: 'tool_result',
sessionId,
importance: 0.6,
expiresAt: Date.now() + this.EPISODIC_TTL_MS,
});
} catch (error) {
// 记忆存储失败不应影响工具执行结果