feat: v0.7.3 成本收口 · 状态一致 · 死账清理 — Prompt Cache 根治 + SSRF DNS Pinning + 87 用例扩充全量回归
CI / 类型检查 + Lint + 单元测试 (push) Failing after 5m47s
CI / 全量测试 (Electron ABI) (push) Failing after 5m19s
CI / 产物编译验证 (push) Successful in 9m55s

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:
2026-08-30 09:44:43 +08:00
parent 26169b7be4
commit ebe45482b0
68 changed files with 4568 additions and 664 deletions
+31 -7
View File
@@ -37,7 +37,8 @@ import type { MetonaMessage } from '../../harness/types';
function makeEngineMock(overrides: Record<string, unknown> = {}) {
return {
runStream: vi.fn().mockResolvedValue({
finalAnswer: '这是最终回答',
// v0.7.3 P1-5: 固化门控要求回答 >= minChars(默认 200)—— mock 回答扩到阈值之上
finalAnswer: '这是最终回答' + '补充细节。'.repeat(60),
terminationReason: 'completed',
iterations: [
{
@@ -140,6 +141,8 @@ function makeCtx(overrides: Record<string, unknown> = {}) {
// v0.5.1: abortByParent 返回 taskId[]abortSession 据此清理 SubAgent pending 确认)
orchestrator: Object.assign(new EventEmitter(), { abortByParent: vi.fn(() => []) }),
confirmationHook: { clearPending: vi.fn() },
// v0.7.3 P4-1: 会话标题生成器接线(sendMessage 完成路径消费)
titleGenerator: { maybeGenerateTitle: vi.fn().mockResolvedValue(null) },
reloadAdapter: vi.fn(() => true),
...overrides,
};
@@ -266,10 +269,13 @@ describe('agent:sendMessage — 成功路径', () => {
sessionId: 'sess_1',
}),
);
// 2. 引擎启动(每会话引擎)
// 2. 引擎启动(每会话引擎)—— v0.7.3 P1-1: 引擎收到带上下文前置块的消息副本
expect(ctxRaw.agentEngineManager.getEngine).toHaveBeenCalledWith('sess_1');
expect(engine.runStream).toHaveBeenCalledWith(
VALID_MESSAGE,
expect.objectContaining({
role: 'user',
content: expect.stringContaining(String(VALID_MESSAGE.content)),
}),
'sess_1',
[],
expect.objectContaining({ roleDefinition: 'role' }),
@@ -292,7 +298,10 @@ describe('agent:sendMessage — 成功路径', () => {
);
expect(ctxRaw.sessionRecorder.stopRecording).toHaveBeenCalled();
// 7. 输出验证执行
expect(ctxRaw.outputValidator.validate).toHaveBeenCalledWith('这是最终回答', expect.anything());
expect(ctxRaw.outputValidator.validate).toHaveBeenCalledWith(
expect.stringContaining('这是最终回答'),
expect.anything(),
);
// 8. 摘要评估(异步触发)
await vi.waitFor(() =>
expect(ctxRaw.sessionSummaryService.maybeSummarize).toHaveBeenCalledWith('sess_1'),
@@ -301,7 +310,7 @@ describe('agent:sendMessage — 成功路径', () => {
await vi.waitFor(() => expect(ctxRaw.memoryConsolidator.consolidate).toHaveBeenCalled());
});
it('注入相关记忆到 System Prompt 动态区', async () => {
it('注入相关记忆到用户消息上下文前置块(P1-1:system 保持缓存稳定)', async () => {
const { ctx, ctxRaw } = makeCtx({
memoryManager: {
search: vi.fn(() => [
@@ -321,9 +330,16 @@ describe('agent:sendMessage — 成功路径', () => {
await handler(null, VALID_MESSAGE, 'sess_1');
expect(ctxRaw.memoryManager.search).toHaveBeenCalled();
// 引擎收到的 systemPrompt 应包含记忆块
// P1-1: 记忆注入迁移到首条 user 消息前置块(system 跨 run 字节稳定 → 缓存命中)
const prompt = engine_runStreamPrompt(ctxRaw);
expect(prompt.dynamicReminders).toContain('用户偏好深色主题');
expect(prompt.dynamicReminders).not.toContain('用户偏好深色主题');
const userMessage = engine_runStreamUserMessage(ctxRaw);
expect(userMessage.content).toContain('[Contextual information for this message');
expect(userMessage.content).toContain('用户偏好深色主题');
// DB 持久化仍使用原始干净内容(前置块只存在于引擎副本)
expect(ctxRaw.sessionService.saveMessage).toHaveBeenCalledWith(
expect.objectContaining({ content: VALID_MESSAGE.content }),
);
});
it('验证发现 warning 级问题时广播 VALIDATION 流事件', async () => {
@@ -406,6 +422,14 @@ describe('agent:abortSession — 中断编排', () => {
});
});
/** 从 runStream 调用参数中提取首条用户消息(P1-1 前置块断言用) */
function engine_runStreamUserMessage(ctxRaw: Record<string, unknown>): { content: string } {
const engine = (ctxRaw.agentEngineManager as unknown as { getEngine: Mock }).getEngine() as {
runStream: Mock;
};
return engine.runStream.mock.calls[0][0];
}
/** 从 runStream 调用参数中提取 systemPrompt */
function engine_runStreamPrompt(ctxRaw: Record<string, unknown>): {
roleDefinition: string;
@@ -65,7 +65,7 @@ describe('sessions 域 — 参数校验矩阵', () => {
getMessages: vi.fn(() => []),
pin: vi.fn(() => true),
archive: vi.fn(() => true),
deleteMessage: vi.fn(() => true),
// v0.7.3 P1-3: sessions:deleteMessage 死通道已删除,service 方法一并移除
clearMessages: vi.fn(),
truncateMessagesAfter: vi.fn(() => true),
searchMessages: vi.fn(() => []),
+110 -64
View File
@@ -19,8 +19,24 @@ import { MetonaErrorCode, MetonaStreamEventType } from '../harness/types';
import { estimateMessagesTokens } from '../harness/utils/token-estimator';
import { DeepSeekAdapter } from '../harness/adapters/deepseek.adapter';
import { OllamaAdapter } from '../harness/adapters/ollama.adapter';
// v0.7.3 P1-1: 用户上下文前置块(动态内容出 system,保 prompt cache 前缀稳定)
import { buildUserContextPrefix, withUserContextPrefix } from '../harness/prompts/user-context';
// v0.7.3 P1-5: 记忆固化触发决策(纯函数)
import { shouldConsolidate } from '../harness/memory/consolidation-policy';
import log from 'electron-log';
/** 构建 "时区名 (UTC±N)" 标签(注入用户上下文前置块;失败回退 UTC) */
function buildTimezoneLabel(): string {
try {
const tz = Intl.DateTimeFormat().resolvedOptions().timeZone ?? 'UTC';
const offset = -new Date().getTimezoneOffset() / 60;
const offsetStr = offset >= 0 ? `UTC+${offset}` : `UTC${offset}`;
return `${tz} (${offsetStr})`;
} catch {
return 'UTC';
}
}
/** 单会话的 text_delta 节流状态 */
interface ThrottleState {
buffer: string;
@@ -56,12 +72,16 @@ export function registerAgentHandlers(ctx: IPCContext): void {
sessionSummaryService,
orchestrator,
confirmationHook,
titleGenerator,
} = ctx;
// ===== 常驻事件管道:text_delta 按会话节流(F8 =====
const throttleStates = new Map<string, ThrottleState>();
const iterationTraces = new Map<string, IterationTrace>();
// v0.7.3 P1-5: 会话级记忆固化时间戳(consolidation-policy 频率门控的状态持有方)
const lastConsolidationBySession = new Map<string, number>();
const flushThrottle = (sessionId: string): void => {
const st = throttleStates.get(sessionId);
if (!st) return;
@@ -411,59 +431,46 @@ export function registerAgentHandlers(ctx: IPCContext): void {
});
}
// 检索与用户消息相关的记忆,注入到 System Prompt 动态区
// 检索与用户消息相关的记忆 + 附件元信息 → 构建用户消息上下文前置块。
// v0.7.3 P1-1 根治: 记忆注入与附件提示此前追加进 systemPrompt.dynamicReminders
// 每条消息都改变 system 字节 → 跨 run 缓存全 miss。现随首条 user 消息注入
// LLM 语义等价),system prompt 保持跨 run 字节级稳定。
let userContextPrefix = '';
try {
const memories = memoryManager.search(userMessage.content, { topK: 5, minImportance: 0.3 });
const attachments = (
userMessage as MetonaMessage & {
attachments?: Array<{ name: string; type: string; truncated?: boolean }>;
}
).attachments;
userContextPrefix = buildUserContextPrefix({
now: Date.now(),
memories,
attachments: Array.isArray(attachments) ? attachments : [],
timezoneLabel: buildTimezoneLabel(),
});
if (memories.length > 0) {
const memorySection = memories
.map(
(m, i) =>
`[${i + 1}] (${m.type}, 重要度: ${m.importance.toFixed(1)}) ${m.content.slice(0, 200)}`,
)
.join('\n');
const memoryBlock = `## Relevant Memories (Retrieved)\n${memorySection}`;
systemPrompt.dynamicReminders = systemPrompt.dynamicReminders
? `${systemPrompt.dynamicReminders}\n\n---\n\n${memoryBlock}`
: memoryBlock;
log.debug(`[AGENT] Injected ${memories.length} memories into system prompt`);
log.debug(`[AGENT] Injected ${memories.length} memories into user context prefix`);
}
} catch (err) {
log.warn('[AGENT] Memory retrieval failed, proceeding without memories:', err);
// 记忆检索失败时前置块退化为仅含日期时间(附件提示随之丢失可接受——
// 主进程附件提示是辅助语义,附件内容本体仍在消息中)
userContextPrefix = buildUserContextPrefix({
now: Date.now(),
memories: [],
attachments: [],
timezoneLabel: buildTimezoneLabel(),
});
}
// 附件提示注入:用户直接上传的文件/图片,避免 LLM 误以为需要在工作空间查找
const attachments = (
userMessage as MetonaMessage & { attachments?: Array<{ name: string; type: string }> }
).attachments;
if (Array.isArray(attachments) && attachments.length > 0) {
const attachmentList = attachments
.map((att, i) => {
const typeLabel =
att.type === 'image' ? 'image' : att.type === 'text' ? 'text file' : 'file';
// v0.7.2 A5: 文本附件被上传入口截断(512KB 上限)时,明确告知 LLM 内容不完整,
// 防止模型把残缺内容当作完整文件事实
const truncatedNote =
(att as { truncated?: boolean }).truncated === true
? ' (TRUNCATED — only the first 512KB is included; the full content is NOT available)'
: '';
const note =
att.type === 'image'
? 'already provided to you via vision capability — you can SEE it directly, do NOT call view_image or any tool to read it again'
: att.type === 'text'
? `content${truncatedNote} already inlined in the user message, do NOT search in workspace or read it again`
: 'uploaded directly by user, do NOT search in workspace';
return `${i + 1}. [${typeLabel}] ${att.name}${note}`;
})
.join('\n');
const attachmentBlock = `## User Attachments (Direct Upload)\nThe following files were uploaded directly by the user to this conversation. They are inline attachments, NOT workspace files:\n${attachmentList}\n\n**IMPORTANT**: Images listed above are already visible to you in this conversation. Do NOT call \`view_image\`, \`read_file\`, or any file tool to read them — doing so wastes a tool call and may fail (they are not workspace files).`;
systemPrompt.dynamicReminders = systemPrompt.dynamicReminders
? `${systemPrompt.dynamicReminders}\n\n---\n\n${attachmentBlock}`
: attachmentBlock;
log.debug(`[AGENT] Injected ${attachments.length} attachment hints into system prompt`);
}
// 构建发送给引擎的用户消息副本 —— 前置块只存在于该副本:
// DB 持久化(上方 saveMessage 已用原始内容)、前端展示、记忆固化、
// 注入检测均使用原始干净内容,互不污染。
const engineUserMessage: MetonaMessage = {
...userMessage,
content: withUserContextPrefix(userContextPrefix, userMessage.content),
};
try {
// 提示注入检测(安全模块)
@@ -503,8 +510,9 @@ export function registerAgentHandlers(ctx: IPCContext): void {
});
// 启动 Agent LoopP2-10: 每会话独立引擎)
// v0.7.3 P1-1: 传入带上下文前置块的消息副本 —— 原始 userMessage 保持干净
const engine = agentEngineManager.getEngine(sessionId);
const output = await engine.runStream(userMessage, sessionId, history, systemPrompt);
const output = await engine.runStream(engineUserMessage, sessionId, history, systemPrompt);
// 输出验证(不阻塞响应,仅记录警告)
// v0.3.0 修复: 传入 toolResults 和 context,启用事实一致性检查和幻觉检测
@@ -624,23 +632,58 @@ export function registerAgentHandlers(ctx: IPCContext): void {
workspaceService.updateMemoryTimestamp();
// 会话结束:AI 判断本次对话有哪些重要内容需要持久化到 MEMORY.md
// 异步执行,不阻塞主流程返回;失败仅记录日志
memoryConsolidator
.consolidate(userMessage.content, output.finalAnswer, output.iterations)
.then((result) => {
if (result.appended > 0) {
log.info(
`[AGENT] Memory consolidated: ${result.appended} entries appended to MEMORY.md`,
);
broadcast('toast:show', {
type: 'info',
message: `AI 已将 ${result.appended} 条重要记忆写入 MEMORY.md`,
});
}
})
.catch((err) => {
log.warn('[AGENT] Memory consolidation failed:', err);
});
// v0.7.3 P1-5 节流: 此前每次 run 无条件发起固化 LLM 请求,短寒暄同样触发。
// 现按 consolidation-policy 决策(总开关 + 内容门控 + 会话级频率窗口)触发;
// 异步执行不阻塞主流程返回;失败仅记录日志。
const lastConsolidationAt = lastConsolidationBySession.get(sessionId) ?? 0;
const hadSuccessfulToolCall = output.iterations.some((step) =>
(step.toolResults ?? []).some((r) => r.success),
);
const decision = shouldConsolidate({
enabled: configService.get<boolean>('memory.consolidationEnabled') !== false,
answerChars: output.finalAnswer?.length ?? 0,
minChars: configService.get<number>('memory.consolidationMinChars') ?? 200,
hadSuccessfulToolCall,
lastConsolidationAt,
now: Date.now(),
intervalMs: configService.get<number>('memory.consolidationIntervalMs') ?? 600_000,
});
if (decision.consolidate) {
memoryConsolidator
.consolidate(userMessage.content, output.finalAnswer, output.iterations)
.then((result) => {
if (result.appended > 0) {
lastConsolidationBySession.set(sessionId, Date.now());
log.info(
`[AGENT] Memory consolidated: ${result.appended} entries appended to MEMORY.md`,
);
broadcast('toast:show', {
type: 'info',
message: `AI 已将 ${result.appended} 条重要记忆写入 MEMORY.md`,
});
}
})
.catch((err) => {
log.warn('[AGENT] Memory consolidation failed:', err);
});
} else {
log.debug(`[AGENT] Memory consolidation skipped (${decision.reason})`);
}
// v0.7.3 P4-1: 首个完成的 run 之后生成精炼会话标题(每会话幂等,失败静默)
if (output.terminationReason === 'completed') {
titleGenerator
.maybeGenerateTitle(sessionId, userMessage.content, output.finalAnswer)
.then((title) => {
if (title) {
// 广播重命名结果,前端 Sidebar 实时刷新标题
broadcast('config:changed', { key: `session.title.${sessionId}`, value: title });
}
})
.catch(() => {
/* 静默 —— 标题失败已有 debug 日志 */
});
}
// TOOL 层:记录会话结束 / TRACE 层:停止录制
auditService.logSessionEnd({
@@ -832,8 +875,9 @@ export function registerAgentHandlers(ctx: IPCContext): void {
// v0.5.0: 按会话清理 — 只拒绝被中断会话的 pending,不影响其他并发会话等待中的确认
confirmationHook.clearPending(sessionId);
// v0.5.1: 被中止 SubAgent 的 pending 确认一并拒绝(含 SubAgent 递归派生的孙任务)
// v0.7.3 P2-3: 被中止的 SubAgent 是会话终态 —— 用 forgetSession 连决策记忆一并清理
for (const taskId of abortedTaskIds) {
confirmationHook.clearPending(taskId);
confirmationHook.forgetSession(taskId);
}
// TOOL 层:记录中断
@@ -880,6 +924,8 @@ export function registerAgentHandlers(ctx: IPCContext): void {
});
subTraces.delete(taskId);
subMeta.delete(taskId);
// v0.7.3 P2-3: SubAgent 终态 —— 决策记忆随任务终结清理(防长期运行泄漏)
confirmationHook.forgetSession(taskId);
};
orchestrator.on(
+28
View File
@@ -34,6 +34,34 @@ export function registerAppHandlers(ctx: IPCContext): void {
return result;
});
// ===== v0.7.3 P3-4: 健康快照(SLO 指标 + 最近健康检查报告)=====
ipcMain.handle('app:healthSnapshot', async () => {
try {
return { success: true, data: ctx.getHealthSnapshot() };
} catch (error) {
return { success: false, error: (error as Error).message };
}
});
// ===== v0.7.3 P3-3: JSONL 录制文件统计与清理(设置页展示 + 手动清理)=====
ipcMain.handle('logs:traceStats', async () => {
try {
return { success: true, data: ctx.sessionRecorder.getRecordingStats() };
} catch (error) {
return { success: false, error: (error as Error).message };
}
});
ipcMain.handle('logs:pruneTraceFiles', async () => {
try {
const deleted = ctx.sessionRecorder.pruneOldRecordings();
log.info(`[LOGS] Manual trace prune: ${deleted} file(s) removed`);
return { success: true, data: { deleted } };
} catch (error) {
return { success: false, error: (error as Error).message };
}
});
ipcMain.handle('app:openExternal', async (_event, url: unknown) => {
// M-12 修复: URL 协议白名单校验,防止打开 file:///smb:// 等危险协议
if (typeof url !== 'string' || !url) {
+15
View File
@@ -23,6 +23,9 @@ import type { ConfirmationHook } from '../harness/hooks/confirmation-hook';
import type { MemoryConsolidator } from '../harness/memory/consolidator';
import type { TaskOrchestrator } from '../harness/orchestration/orchestrator';
import type { SessionSummaryService } from '../services/session-summary.service';
import type { TitleGenerator } from '../services/title-generator.service';
import type { HealthChecker } from '../utils/slo';
import type { SLOMonitor } from '../utils/slo';
/** 工具就绪状态(main.ts 在 MCP 初始化完成后更新,tools.ts 的 isReady 查询读取) */
export interface ToolsReadyRef {
@@ -30,6 +33,14 @@ export interface ToolsReadyRef {
toolCount: number;
}
/** v0.7.3 P3-4: 健康快照载荷(app:healthSnapshot 返回) */
export interface HealthSnapshot {
slo: ReturnType<SLOMonitor['getStatus']>;
/** 最近一次健康检查报告;null 表示应用启动后尚未执行过检查(周期 60s) */
health: Awaited<ReturnType<HealthChecker['check']>> | null;
generatedAt: number;
}
export interface IPCContext {
mainWindow: BrowserWindow;
sessionService: SessionService;
@@ -49,6 +60,10 @@ export interface IPCContext {
memoryConsolidator: MemoryConsolidator;
orchestrator: TaskOrchestrator;
sessionSummaryService: SessionSummaryService;
/** v0.7.3 P4-1: 会话标题生成器 */
titleGenerator: TitleGenerator;
/** v0.7.3 P3-4: 健康快照读取器(SLO + 最近健康检查报告) */
getHealthSnapshot: () => HealthSnapshot;
toolsReadyRef: ToolsReadyRef;
}
+11 -7
View File
@@ -13,7 +13,7 @@ const isValidSessionId = (id: unknown): id is string =>
typeof id === 'string' && id.length > 0 && id.length <= 200;
export function registerSessionHandlers(ctx: IPCContext): void {
const { sessionService } = ctx;
const { sessionService, confirmationHook } = ctx;
ipcMain.handle('sessions:list', async () => {
return sessionService.list();
@@ -34,7 +34,13 @@ export function registerSessionHandlers(ctx: IPCContext): void {
ipcMain.handle('sessions:delete', async (_event, sessionId: unknown) => {
// M-34 修复: 校验 sessionId
if (!isValidSessionId(sessionId)) return { success: false, error: 'Invalid sessionId' };
return { success: sessionService.delete(sessionId) };
const result = { success: sessionService.delete(sessionId) };
// v0.7.3 P2-3: 会话删除 = 会话终态 —— 决策记忆/pending 确认一并清理
// (防 rememberedDecisions 随会话数累积泄漏)
if (result.success) {
confirmationHook.forgetSession(sessionId);
}
return result;
});
ipcMain.handle('sessions:getMessages', async (_event, sessionId: unknown) => {
@@ -55,11 +61,9 @@ export function registerSessionHandlers(ctx: IPCContext): void {
return { success: sessionService.archive(sessionId, archived) };
});
ipcMain.handle('sessions:deleteMessage', async (_event, messageId: unknown) => {
if (typeof messageId !== 'string' || !messageId)
return { success: false, error: 'Invalid messageId' };
return { success: sessionService.deleteMessage(messageId) };
});
// v0.7.3 P1-3: sessions:deleteMessage 已删除 —— 渲染层零调用方(死通道),
// 且原实现不回减 sessions.message_count(计数漂移面)。消息删除语义由
// sessions:truncateAfter(编辑重发/重新生成)与会话删除级联完整覆盖。
// v0.7.2 A1 根治: 语义修正 —— "清空会话"的成功判定是"操作完成"而非"有行被删除"。
// 原实现透传 DELETE 影响行数(changes > 0),空会话清空会返回 success:false
+11
View File
@@ -101,6 +101,11 @@ export function applyEngineConfigKey(ctx: IPCContext, key: string, value: unknow
thinkingEffort: value as 'low' | 'medium' | 'high' | 'max',
});
break;
// v0.7.3 P3-1: enableReflection 接线(此前为死配置)— 引擎 REFLECTING 状态开关
case 'agent.enableReflection':
agentEngineManager.updateConfigAll({ enableReflection: value === true });
orchestrator.updateDefaultConfig({ enableReflection: value === true });
break;
case 'agent.toolExecutionTimeoutMs':
agentEngineManager.updateConfigAll({ toolExecutionTimeoutMs: value as number });
break;
@@ -202,5 +207,11 @@ export async function applyConfigSideEffects(
await applySessionProxy(typeof proxyValue === 'string' ? proxyValue : null);
}
// v0.7.3 P4-2: MCP 自动重连开关变更 → 即时联动(关闭时取消全部已排程重连)
const autoReconnectEntry = entries.find((e) => e.key === 'mcp.autoReconnect');
if (autoReconnectEntry) {
ctx.mcpManager.setAutoReconnect(autoReconnectEntry.value !== false);
}
return null;
}