P1 修复面收口: - 超时三态区分(aborted→USER_INTERRUPT / ETIMEDOUT→TIMEOUT / 其余→ERROR), 根治"真实网络超时被误报为用户中断" - 流空闲超时统一(SSE/Ollama/Anthropic 读循环 60s 无数据抛 504 进重试通道) - 同会话并发 sendMessage 防重入(isRunning 守卫)+ 会话存在性预检 + 前置调用移入 try(ERROR+DONE 双事件保证,根治 isStreaming 假死) - 清空审计后 resetChainCache(根治 verifyChain 误报 TAMPERED) - DONE 不再提前清理 TRACE(TERMINATED 统一收尾,补全最终迭代录制) - IME 合成回车不发送(普通 Enter + Cmd/Ctrl+Enter 双分支)+ handleSend 闭包修复 P2 安全纵深: - preload 移除原始 electronAPI 暴露(渲染层零使用,关掉 XSS invoke 任意通道单点风险) - CORS 同源回显根治(仅当前浏览页面 Origin,did-navigate 同步) - MEMORY.md 命令保护正则扩展(括号/$/反引号/< 重定向边界 + 前导路径) - write_file append TOCTOU 统一(open 后 realpath 校验,新文件分支补漏) - 敏感键归一化(authKey 驼峰/连字符命中)+ MCP headers 鉴权值加密落库 - ReDoS 检测共享化(search_files/file_editor 统一拦截) - run_tests/lint_code 升风险 + 需确认 + npx --no-install(执行边界对齐 run_command) - MCP/SearXNG/llm.baseURL/updateFeedUrl 配置类 URL 高危目标校验(IPv6 去括号 + 十六进制映射解析 + 尾点剥离) P3 架构还债: - temperature/maxTokens 热生效(引擎/编排器/SubAgent 三处接线)+ setBatch 单事务落盘 - SessionRecorder flush 竞态根治(flushPromise 等待 + 超限内联落盘 + stopRecording async) - 内存收口(lastConsolidationBySession LRU / subTraces 清理 / 会话删除 disposeEngine) - i18n 全量收口(28 组件 + 353 key 双字典,状态标签改渲染时函数) - 死代码清理(updateTraceStep/HEADER_HEIGHT/void preA/失实注释) - 斜杠菜单 MUI 化 + 删除逻辑收敛 resetSessionState + Blob URL 统一释放 + 用户消息"仅保存"落库(saveMessage 透传前端 id 修复 id 错位) P4 能力演进: - 死循环检测拆分(驻留前置 + 乒乓后置带进度信号,合法交替不误报) - run-lock 30s 超时强制 abort(旧 run 卡死不无限排队) - RETRY 双通道 stream_reset(前端按 run 归属精确清空,根治重试文本重复) - FTS5 trigram 中文子串搜索(迁移 9 版本化 SCHEMA_VERSION=2,≤2 字符 LIKE 回退) - getContextWindow 兜底 1M→128K(未知模型防 413) 测试: - 855 → 2406 用例(+1551,2.8 倍):服务层 +325(含 MemoryManager 51 新用例)、 工具实体 +483、IPC/适配器 +390(含 OpenAI/Anthropic/Ollama 独立套件)、 纯函数表格化 +330;引入 jsdom + @testing-library(14 组件测试文件 249 用例) - 修复 R1(saveMessage id 透传)/ R2(stream_reset 精确归属)两个回归缺陷 - 遗留低危项清零:git-tools 顺序耦合 / web-fetch 真实时间退避 / slo 内存断言 / mcp-security 多余 skipIf / deepseek-balance 命名误导 / 组件 mock 注入脆弱性 版本: 0.7.4; README 同步(工具风险表/版本徽章); 依赖: 移除 @electron-toolkit/preload, 新增 jsdom/@testing-library(devDependencies 不打包) 回归: typecheck 双端 0 错误; ESLint 0/0; Electron ABI 全量 2406/2406 零跳过; 系统 Node 2110 通过 296 跳过(better-sqlite3 ABI)
285 lines
8.0 KiB
TypeScript
285 lines
8.0 KiB
TypeScript
/**
|
||
* Health Checker + SLO Monitor — 健康检查器与 SLO 监控
|
||
*
|
||
* HealthChecker: 对数据库连通性、磁盘空间、内存使用执行真实检查。
|
||
* SLOMonitor: C-9 修复 — 补全 SLO 监控核心功能(错误率、延迟分布、吞吐量、燃烧速率)。
|
||
*
|
||
* @see docs/生产级通用 AI Agent 智能体桌面应用:完整设计与构建指南.html — 第十一章
|
||
*/
|
||
|
||
import { existsSync } from 'fs';
|
||
import { app } from 'electron';
|
||
import type Database from 'better-sqlite3';
|
||
|
||
export interface HealthReport {
|
||
healthy: boolean;
|
||
checks: HealthCheck[];
|
||
timestamp: Date;
|
||
}
|
||
|
||
export interface HealthCheck {
|
||
name: string;
|
||
healthy: boolean;
|
||
latencyMs?: number;
|
||
error?: string;
|
||
}
|
||
|
||
export class HealthChecker {
|
||
/**
|
||
* @param getDB 数据库获取器(用于真实验证数据库连通性)
|
||
* @param dbPath 数据库文件路径(后备:文件存在性检查)
|
||
*/
|
||
constructor(
|
||
private getDB?: () => Database.Database,
|
||
private dbPath?: string,
|
||
) {}
|
||
|
||
async check(): Promise<HealthReport> {
|
||
const checks: HealthCheck[] = [];
|
||
checks.push(await this.checkDatabase());
|
||
checks.push(await this.checkFreeMemory());
|
||
checks.push(await this.checkMemoryUsage());
|
||
const allHealthy = checks.every((c) => c.healthy);
|
||
return { healthy: allHealthy, checks, timestamp: new Date() };
|
||
}
|
||
|
||
private async checkDatabase(): Promise<HealthCheck> {
|
||
const start = Date.now();
|
||
try {
|
||
// 优先使用注入的 DB 实例执行真实 ping
|
||
if (this.getDB) {
|
||
const db = this.getDB();
|
||
// 执行真实查询验证数据库连通性
|
||
db.prepare('SELECT 1').get();
|
||
return { name: 'database', healthy: true, latencyMs: Date.now() - start };
|
||
}
|
||
// 后备:检查数据库文件是否存在
|
||
if (this.dbPath && existsSync(this.dbPath)) {
|
||
return { name: 'database', healthy: true, latencyMs: Date.now() - start };
|
||
}
|
||
return { name: 'database', healthy: false, error: 'Database not available' };
|
||
} catch (error) {
|
||
return {
|
||
name: 'database',
|
||
healthy: false,
|
||
error: error instanceof Error ? error.message : String(error),
|
||
};
|
||
}
|
||
}
|
||
|
||
private async checkFreeMemory(): Promise<HealthCheck> {
|
||
try {
|
||
const userDataPath = app.getPath('userData');
|
||
if (!existsSync(userDataPath)) {
|
||
return { name: 'free_memory', healthy: false, error: 'User data path not accessible' };
|
||
}
|
||
// 检查实际可用内存(Windows/Linux 返回字节数)
|
||
const { freemem } = await import('os');
|
||
const freeBytes = freemem();
|
||
const freeMB = freeBytes / (1024 * 1024);
|
||
// 少于 200MB 视为不健康
|
||
if (freeMB < 200) {
|
||
return {
|
||
name: 'free_memory',
|
||
healthy: false,
|
||
error: `Free memory critically low: ${freeMB.toFixed(0)}MB available`,
|
||
};
|
||
}
|
||
return { name: 'free_memory', healthy: true };
|
||
} catch (error) {
|
||
return {
|
||
name: 'free_memory',
|
||
healthy: false,
|
||
error: error instanceof Error ? error.message : String(error),
|
||
};
|
||
}
|
||
}
|
||
|
||
private async checkMemoryUsage(): Promise<HealthCheck> {
|
||
const used = process.memoryUsage();
|
||
const heapUsedMB = used.heapUsed / 1024 / 1024;
|
||
const thresholdMB = 512;
|
||
return {
|
||
name: 'memory_usage',
|
||
healthy: heapUsedMB < thresholdMB,
|
||
...(heapUsedMB >= thresholdMB
|
||
? { error: `Heap usage ${heapUsedMB.toFixed(0)}MB exceeds threshold ${thresholdMB}MB` }
|
||
: {}),
|
||
};
|
||
}
|
||
}
|
||
|
||
// ===== C-9 修复: SLO Monitor — SLO 监控核心功能 =====
|
||
|
||
/**
|
||
* SLO 监控配置
|
||
*/
|
||
export interface SLOConfig {
|
||
/** SLO 目标(如 0.999 表示 99.9% 可用性) */
|
||
target: number;
|
||
/** 滑动窗口大小(毫秒,默认 5 分钟) */
|
||
windowMs: number;
|
||
/** 延迟分位数(如 0.95 表示 P95) */
|
||
latencyPercentiles: number[];
|
||
/** 延迟告警阈值(毫秒) */
|
||
latencyThresholdMs: number;
|
||
}
|
||
|
||
/**
|
||
* SLO 请求记录
|
||
*/
|
||
interface SLORequestRecord {
|
||
timestamp: number;
|
||
latencyMs: number;
|
||
success: boolean;
|
||
}
|
||
|
||
/**
|
||
* SLO 状态报告
|
||
*/
|
||
export interface SLOStatus {
|
||
/** 当前错误率(0-1) */
|
||
errorRate: number;
|
||
/** 当前吞吐量(请求/秒) */
|
||
throughput: number;
|
||
/** 平均延迟(毫秒) */
|
||
avgLatencyMs: number;
|
||
/** 延迟分位数 */
|
||
percentiles: Record<string, number>;
|
||
/** 燃烧速率(实际错误率 / 错误预算) */
|
||
burnRate: number;
|
||
/** SLO 目标 */
|
||
target: number;
|
||
/** 错误预算(1 - target) */
|
||
errorBudget: number;
|
||
/** 是否违反 SLO */
|
||
violated: boolean;
|
||
/** 窗口内总请求数 */
|
||
totalRequests: number;
|
||
/** 窗口内错误请求数 */
|
||
errorRequests: number;
|
||
/** 时间戳 */
|
||
timestamp: Date;
|
||
}
|
||
|
||
/**
|
||
* SLO Monitor — SLO 监控器
|
||
*
|
||
* C-9 修复: 补全 SLO 监控核心功能
|
||
*
|
||
* 功能:
|
||
* 1. 错误率追踪 — 记录请求成功/失败,计算滑动窗口内错误率
|
||
* 2. 延迟分布追踪 — 记录请求延迟,计算 P50/P95/P99 分位数
|
||
* 3. 吞吐量追踪 — 计算每秒请求数
|
||
* 4. 燃烧速率计算 — 实际错误率 / 错误预算,>1 表示 SLO 即将违反
|
||
*
|
||
* @see docs/生产级通用 AI Agent 智能体桌面应用:完整设计与构建指南.html — 第十一章
|
||
*/
|
||
export class SLOMonitor {
|
||
private records: SLORequestRecord[] = [];
|
||
private readonly config: SLOConfig;
|
||
|
||
constructor(config: Partial<SLOConfig> = {}) {
|
||
this.config = {
|
||
target: 0.999,
|
||
windowMs: 5 * 60 * 1000, // 5 分钟
|
||
latencyPercentiles: [0.5, 0.95, 0.99],
|
||
latencyThresholdMs: 5000,
|
||
...config,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 记录一次请求
|
||
* @param latencyMs 延迟(毫秒)
|
||
* @param success 是否成功
|
||
*/
|
||
recordRequest(latencyMs: number, success: boolean): void {
|
||
const record: SLORequestRecord = {
|
||
timestamp: Date.now(),
|
||
latencyMs,
|
||
success,
|
||
};
|
||
this.records.push(record);
|
||
// 清理过期记录
|
||
this.cleanup();
|
||
}
|
||
|
||
/**
|
||
* 清理窗口外的过期记录
|
||
*/
|
||
private cleanup(): void {
|
||
const cutoff = Date.now() - this.config.windowMs;
|
||
// v0.7.4 P3-3: 修正失实注释 —— 保留窗口长度(windowMs,5 分钟),
|
||
// 不额外多留窗口外的数据(getStatus 只统计窗口内记录)
|
||
this.records = this.records.filter((r) => r.timestamp >= cutoff);
|
||
}
|
||
|
||
/**
|
||
* 获取当前 SLO 状态
|
||
*/
|
||
getStatus(): SLOStatus {
|
||
this.cleanup();
|
||
|
||
const now = Date.now();
|
||
const windowStart = now - this.config.windowMs;
|
||
const windowRecords = this.records.filter((r) => r.timestamp >= windowStart);
|
||
|
||
const totalRequests = windowRecords.length;
|
||
const errorRequests = windowRecords.filter((r) => !r.success).length;
|
||
const errorRate = totalRequests > 0 ? errorRequests / totalRequests : 0;
|
||
|
||
const throughput = totalRequests / (this.config.windowMs / 1000);
|
||
|
||
const latencies = windowRecords.map((r) => r.latencyMs).sort((a, b) => a - b);
|
||
const avgLatencyMs =
|
||
latencies.length > 0 ? latencies.reduce((sum, l) => sum + l, 0) / latencies.length : 0;
|
||
|
||
const percentiles: Record<string, number> = {};
|
||
for (const p of this.config.latencyPercentiles) {
|
||
const key = `P${(p * 100).toFixed(0)}`;
|
||
percentiles[key] = this.calculatePercentile(latencies, p);
|
||
}
|
||
|
||
const errorBudget = 1 - this.config.target;
|
||
const burnRate = errorBudget > 0 ? errorRate / errorBudget : 0;
|
||
|
||
return {
|
||
errorRate,
|
||
throughput,
|
||
avgLatencyMs,
|
||
percentiles,
|
||
burnRate,
|
||
target: this.config.target,
|
||
errorBudget,
|
||
violated: burnRate > 1,
|
||
totalRequests,
|
||
errorRequests,
|
||
timestamp: new Date(),
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 计算分位数
|
||
*/
|
||
private calculatePercentile(sortedValues: number[], percentile: number): number {
|
||
if (sortedValues.length === 0) return 0;
|
||
const index = Math.ceil(percentile * sortedValues.length) - 1;
|
||
return sortedValues[Math.max(0, index)];
|
||
}
|
||
|
||
/**
|
||
* 重置所有记录
|
||
*/
|
||
reset(): void {
|
||
this.records = [];
|
||
}
|
||
|
||
/**
|
||
* 获取配置
|
||
*/
|
||
getConfig(): SLOConfig {
|
||
return { ...this.config };
|
||
}
|
||
}
|