feat: v0.8.1 记忆深化 · 观测闭环 · 体验收口 — 窗口/输出上限全局单一配置 · 2478 用例全量回归 + E2E 冒烟
硬性契约:删除代码中一切写死的上下文窗口与最大输出上限(含六家模型元信息
钳制与全部兜底值)——唯一合法来源是设置面板「上下文长度」(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:
@@ -59,6 +59,14 @@ vi.mock('undici', () => ({
|
||||
undiciMocks.proxyAgentCalls.push(opts.uri);
|
||||
}
|
||||
},
|
||||
// v0.8.1 P2-5: 组合 dispatcher 基类(回环直连 + 其余走代理)
|
||||
Dispatcher: class {
|
||||
dispatch(): boolean {
|
||||
return true;
|
||||
}
|
||||
async close(): Promise<void> {}
|
||||
async destroy(): Promise<void> {}
|
||||
},
|
||||
setGlobalDispatcher: (...args: unknown[]) => undiciMocks.setGlobalDispatcher(...args),
|
||||
}));
|
||||
|
||||
@@ -89,6 +97,7 @@ describe('applySessionProxy — 双通道应用', () => {
|
||||
expect(sessionMocks.defaultSetProxy).toHaveBeenCalledWith(expected);
|
||||
expect(sessionMocks.partitionSetProxy).toHaveBeenCalledWith(expected);
|
||||
expect(undiciMocks.proxyAgentCalls).toEqual(['http://127.0.0.1:7890']);
|
||||
expect(undiciMocks.agentCalls).toBeGreaterThanOrEqual(1); // 回环直连 Agent 同步构建
|
||||
expect(undiciMocks.setGlobalDispatcher).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
|
||||
@@ -40,9 +40,11 @@ import {
|
||||
isEncryptedValue,
|
||||
encryptConfigValue,
|
||||
decryptConfigValue,
|
||||
resetEncryptionUsableForTests,
|
||||
} from '../secure-config';
|
||||
|
||||
beforeEach(() => {
|
||||
resetEncryptionUsableForTests();
|
||||
mockState.encryptionAvailable = true;
|
||||
mockState.failDecrypt = false;
|
||||
});
|
||||
@@ -113,13 +115,22 @@ describe('加密降级与失败语义', () => {
|
||||
expect(isEncryptedValue(value)).toBe(false);
|
||||
});
|
||||
|
||||
it('加密过程抛错 → 回退明文存储(不阻断配置保存)', () => {
|
||||
// decryptString 抛错不影响 encrypt;此处验证 decrypt 失败语义
|
||||
mockState.failDecrypt = true;
|
||||
it('解密失败(跨机器/重装)→ 返回空串(不阻断,引导重录)', () => {
|
||||
// v0.8.1: roundtrip probe 需要一次可用加解密 —— 先完成加密,再注入解密失败
|
||||
const encrypted = encryptConfigValue('sk-x') as string;
|
||||
expect(isEncryptedValue(encrypted)).toBe(true);
|
||||
mockState.failDecrypt = true;
|
||||
expect(decryptConfigValue(encrypted)).toBe(''); // 失败 → 空串(createAdapter 判定未配置,引导重录)
|
||||
});
|
||||
|
||||
it('roundtrip 探测失败 → 会话级降级明文存储(v0.8.1 新增)', () => {
|
||||
// failDecrypt 令 probe 失败 → usable=false → 加密直接降级明文
|
||||
mockState.failDecrypt = true;
|
||||
const value = encryptConfigValue('sk-probe-fail') as string;
|
||||
expect(value).toBe('sk-probe-fail');
|
||||
expect(isEncryptedValue(value)).toBe(false);
|
||||
});
|
||||
|
||||
it('safeStorage 不可用时已加密值仍可识别且不被二次"加密"', () => {
|
||||
const once = encryptConfigValue('sk-again') as string;
|
||||
mockState.encryptionAvailable = false;
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
/**
|
||||
* Main-process Locale — 主进程侧文案双语(v0.8.1 P0-4 i18n 收口第二期)
|
||||
*
|
||||
* 背景:v0.7.2 建立了渲染层 i18next 集中文案字典,但主进程直接 broadcast 的
|
||||
* toast / 系统通知(压缩、死循环、故障转移、记忆固化、sendMessage 错误路径等)
|
||||
* 全部硬编码中文 —— en-US 用户看到的系统提示仍是中文,i18n 收口未完成。
|
||||
*
|
||||
* 契约:
|
||||
* - 语言偏好唯一来源是设置面板 `ui.locale`(zh-CN / en-US);
|
||||
* - main.ts 启动时注入一次,config:set/setBatch 变更 ui.locale 时经
|
||||
* applyConfigSideEffects 热切换(无需重启);
|
||||
* - mt(key, params) 为唯一取词入口,缺 key 时回退 zh 表,再缺失时回退 key 本身
|
||||
* (与渲染层 t() 的回退语义一致);
|
||||
* - 文案表只覆盖"主进程主动产生"的文案;渲染层文案仍归 i18n-strings.ts。
|
||||
*/
|
||||
|
||||
export type MainLocale = 'zh-CN' | 'en-US';
|
||||
|
||||
let currentLocale: MainLocale = 'zh-CN';
|
||||
|
||||
/** 设置主进程语言(非法值保持不变;null/undefined 视为未配置 → zh-CN 默认) */
|
||||
export function setMainLocale(locale: string | null | undefined): void {
|
||||
if (locale === 'en-US' || locale === 'zh-CN') {
|
||||
currentLocale = locale;
|
||||
}
|
||||
}
|
||||
|
||||
export function getMainLocale(): MainLocale {
|
||||
return currentLocale;
|
||||
}
|
||||
|
||||
const zh: Record<string, string> = {
|
||||
// ===== sendMessage 错误路径 =====
|
||||
'agent.error.invalidSessionId': '无效的会话 ID',
|
||||
'agent.error.invalidMessage': '无效的消息格式',
|
||||
'agent.error.sessionBusy': '该会话正在执行任务,请等待完成或先中断后再发送',
|
||||
'agent.error.sessionMissing': '会话不存在或已被删除,请刷新后重试',
|
||||
'agent.error.adapterLoadFailed':
|
||||
'Adapter 加载失败,请检查 LLM 配置(Provider、API Key、Base URL、Model 是否完整)',
|
||||
// ===== SOUL.md 降级提示 =====
|
||||
'agent.soul.fallbackToast':
|
||||
'未找到 SOUL.md 或内容为空,已使用默认 Metona 身份。可在工作空间根目录创建 SOUL.md 自定义 Agent 人格',
|
||||
// ===== 引擎事件 toast =====
|
||||
'agent.toast.compressed': '上下文压缩: {{original}} → {{compressed}} tokens(节省 {{saved}})',
|
||||
'agent.toast.deadLoop':
|
||||
'检测到死循环(第 {{iteration}} 轮):连续3轮重复相同工具调用,已自动终止',
|
||||
'agent.toast.providerSwitched': 'Provider 故障转移: {{from}} → {{to}}(主 Provider 请求失败)',
|
||||
'agent.toast.consolidated': 'AI 已将 {{count}} 条重要记忆写入 MEMORY.md',
|
||||
'agent.toast.memoryOversize': 'MEMORY.md 已超过 50KB,建议在「记忆」面板整理记忆',
|
||||
// ===== LLM 运行时查询 =====
|
||||
'llm.balance.queryFailed': '余额查询失败(API Key 无效或网络错误)',
|
||||
'llm.listModels.notConfigured': 'LLM 未配置(Provider/Model 为空),无法获取模型列表',
|
||||
'llm.listModels.noApiKey': 'API Key 未配置,无法获取模型列表',
|
||||
'llm.listModels.configInvalid': 'LLM 配置校验失败,请先在设置中修正配置',
|
||||
'llm.listModels.unsupported': '当前 Provider 不支持模型列表查询',
|
||||
'llm.pull.ollamaOnly': '仅 Ollama Provider 支持模型下载',
|
||||
'llm.pull.inProgress': '已有模型下载任务进行中,请先取消',
|
||||
'llm.pull.none': '没有进行中的下载任务',
|
||||
// ===== main.ts 适配器/Provider =====
|
||||
'config.toast.configIncomplete':
|
||||
'LLM 配置不完整,请在设置中补全 Provider、API Key、Base URL 和 Model',
|
||||
'config.toast.providerSwitched': 'Provider 已切换: {{from}} → {{to}}',
|
||||
'config.toast.providerSwitchFailed': 'Provider 切换失败: {{message}}',
|
||||
// ===== 系统通知 =====
|
||||
'notify.updateAvailable.title': 'MetonaAI 更新可用',
|
||||
'notify.updateAvailable.body': '新版本 {{version}} 已发布,可在 设置 → 日志与数据 中下载安装',
|
||||
'notify.taskCompleted.title': 'MetonaAI — 任务完成',
|
||||
'notify.taskCompleted.body': 'Agent 已完成任务 ({{seconds}}s)',
|
||||
// ===== shared.ts 配置副作用 =====
|
||||
'config.error.configIncomplete':
|
||||
'LLM 配置不完整,请检查 Provider、API Key、Base URL 和 Model 是否都已填写',
|
||||
'config.error.workspaceSaveFailed': '工作空间路径保存失败:{{message}}',
|
||||
// ===== 记忆维护(v0.8.1 P1-2) =====
|
||||
'memory.maintain.auditTitle': 'MEMORY.md 记忆整理',
|
||||
};
|
||||
|
||||
const en: Record<string, string> = {
|
||||
'agent.error.invalidSessionId': 'Invalid session ID',
|
||||
'agent.error.invalidMessage': 'Invalid message format',
|
||||
'agent.error.sessionBusy':
|
||||
'This session is already running. Please wait for it to finish or abort it first.',
|
||||
'agent.error.sessionMissing': 'Session does not exist or has been deleted. Please refresh.',
|
||||
'agent.error.adapterLoadFailed':
|
||||
'Adapter load failed. Check your LLM config (Provider, API Key, Base URL, Model).',
|
||||
'agent.soul.fallbackToast':
|
||||
'SOUL.md not found or empty — using the default Metona identity. Create SOUL.md in the workspace root to customize the agent persona.',
|
||||
'agent.toast.compressed':
|
||||
'Context compressed: {{original}} → {{compressed}} tokens (saved {{saved}})',
|
||||
'agent.toast.deadLoop':
|
||||
'Dead loop detected (iteration {{iteration}}): the same tool call repeated 3 times — aborted automatically',
|
||||
'agent.toast.providerSwitched': 'Provider failover: {{from}} → {{to}} (primary provider failed)',
|
||||
'agent.toast.consolidated': '{{count}} important memories were written to MEMORY.md',
|
||||
'agent.toast.memoryOversize':
|
||||
'MEMORY.md exceeds 50KB — consider tidying it up in the Memory panel',
|
||||
'llm.balance.queryFailed': 'Balance query failed (invalid API key or network error)',
|
||||
'llm.listModels.notConfigured': 'LLM not configured (Provider/Model empty) — cannot list models',
|
||||
'llm.listModels.noApiKey': 'API Key not configured — cannot list models',
|
||||
'llm.listModels.configInvalid': 'LLM config validation failed — fix it in Settings first',
|
||||
'llm.listModels.unsupported': 'The current provider does not support model listing',
|
||||
'llm.pull.ollamaOnly': 'Only the Ollama provider supports model download',
|
||||
'llm.pull.inProgress': 'A model download is already in progress — cancel it first',
|
||||
'llm.pull.none': 'No download in progress',
|
||||
'config.toast.configIncomplete':
|
||||
'LLM config incomplete. Please set Provider, API Key, Base URL and Model in Settings.',
|
||||
'config.toast.providerSwitched': 'Provider switched: {{from}} → {{to}}',
|
||||
'config.toast.providerSwitchFailed': 'Provider switch failed: {{message}}',
|
||||
'notify.updateAvailable.title': 'MetonaAI update available',
|
||||
'notify.updateAvailable.body':
|
||||
'Version {{version}} has been released. Install it in Settings → Logs & Data.',
|
||||
'notify.taskCompleted.title': 'MetonaAI — task completed',
|
||||
'notify.taskCompleted.body': 'The agent finished the task ({{seconds}}s)',
|
||||
'config.error.configIncomplete':
|
||||
'LLM config incomplete. Check that Provider, API Key, Base URL and Model are all filled in.',
|
||||
'config.error.workspaceSaveFailed': 'Failed to save workspace path: {{message}}',
|
||||
'memory.maintain.auditTitle': 'MEMORY.md maintenance',
|
||||
};
|
||||
|
||||
const DICTS: Record<MainLocale, Record<string, string>> = { 'zh-CN': zh, 'en-US': en };
|
||||
|
||||
/** 主进程文案取词:缺 key 回退 zh 表;参数以 {{name}} 占位替换 */
|
||||
export function mt(key: string, params?: Record<string, string | number>): string {
|
||||
const raw = DICTS[currentLocale][key] ?? zh[key] ?? key;
|
||||
if (!params) return raw;
|
||||
return raw.replace(/\{\{(\w+)\}\}/g, (_, name: string) => String(params[name] ?? ''));
|
||||
}
|
||||
@@ -80,12 +80,46 @@ export async function applySessionProxy(proxyUrl: string | null | undefined): Pr
|
||||
// ===== 通道二:主进程 Node fetch(undici 全局 dispatcher)=====
|
||||
// 动态 import:主进程所有 fetch 出口共享该调度器;setGlobalDispatcher 写入的
|
||||
// 全局符号对所有引用同一 undici registry 的 fetch 实例生效。失败不阻断主流程。
|
||||
//
|
||||
// v0.8.1 根治: 代理 dispatcher 必须放行回环目标(127.0.0.1 / ::1 / localhost)。
|
||||
// 此前全局 ProxyAgent 会把发往本机的请求(本地 Ollama / SearXNG / E2E mock LLM
|
||||
// / 指向 localhost 的任意 Provider)也交给系统代理 —— 代理不可用或拒绝回环时
|
||||
// 这类请求全部 "fetch failed"。现用组合 dispatcher:回环直连、其余走代理
|
||||
// (与 NO_PROXY=127.0.0.1,localhost 的通用语义一致)。
|
||||
await (async () => {
|
||||
try {
|
||||
const { Agent, ProxyAgent, setGlobalDispatcher } = await import('undici');
|
||||
const undici = await import('undici');
|
||||
const { Agent, ProxyAgent, Dispatcher, setGlobalDispatcher } = undici;
|
||||
if (rules !== '') {
|
||||
setGlobalDispatcher(new ProxyAgent({ uri: rules, connectTimeout: 15_000 }));
|
||||
log.info(`[Network] Node fetch dispatcher → ProxyAgent(${rules})`);
|
||||
const direct = new Agent({ connectTimeout: 15_000 });
|
||||
const proxy = new ProxyAgent({ uri: rules, connectTimeout: 15_000 });
|
||||
type DispatchArgs = Parameters<InstanceType<typeof Dispatcher>['dispatch']>;
|
||||
class LoopbackBypassDispatcher extends Dispatcher {
|
||||
override dispatch(...args: DispatchArgs): boolean {
|
||||
const opts = args[0];
|
||||
let host = '';
|
||||
if (typeof opts.origin === 'string') {
|
||||
host = new URL(opts.origin).hostname;
|
||||
} else if (opts.origin instanceof URL) {
|
||||
host = opts.origin.hostname;
|
||||
}
|
||||
const isLoopback =
|
||||
host === '127.0.0.1' ||
|
||||
host === '::1' ||
|
||||
host === '[::1]' ||
|
||||
host === 'localhost' ||
|
||||
host.endsWith('.localhost');
|
||||
return (isLoopback ? direct : proxy).dispatch(...args);
|
||||
}
|
||||
override async close(): Promise<void> {
|
||||
await Promise.all([direct.close(), proxy.close()]);
|
||||
}
|
||||
override async destroy(): Promise<void> {
|
||||
await Promise.all([direct.destroy(), proxy.destroy()]);
|
||||
}
|
||||
}
|
||||
setGlobalDispatcher(new LoopbackBypassDispatcher());
|
||||
log.info(`[Network] Node fetch dispatcher → ProxyAgent(${rules}) + loopback bypass`);
|
||||
} else {
|
||||
setGlobalDispatcher(new Agent());
|
||||
log.info('[Network] Node fetch dispatcher → direct Agent');
|
||||
|
||||
@@ -17,6 +17,49 @@ import log from 'electron-log';
|
||||
/** 加密值前缀标记(版本化,便于未来算法升级) */
|
||||
const ENCRYPTION_PREFIX = 'metona-enc:v1:';
|
||||
|
||||
/**
|
||||
* v0.8.1 根治: 加密可用性探测(roundtrip probe)。
|
||||
*
|
||||
* isEncryptionAvailable()=true 并不保证加解密可实际往返(部分桌面/服务会话下
|
||||
* DPAPI/keyring 返回的密文无法回解,写后读必失败 → API Key 被静默清空)。
|
||||
* 现在进程内首次使用时做一次 encrypt→decrypt 回环校验:
|
||||
* - 通过 → 正常加密存储;
|
||||
* - 失败 → 本次会话降级为明文存储(与 isEncryptionAvailable=false 同语义),
|
||||
* 保持功能可用并 WARN 留痕;读取侧对"本会话明文"无感知(无前缀原样返回)。
|
||||
*/
|
||||
let encryptionUsable: boolean | null = null;
|
||||
|
||||
function isEncryptionUsable(): boolean {
|
||||
if (encryptionUsable !== null) return encryptionUsable;
|
||||
try {
|
||||
if (!safeStorage.isEncryptionAvailable()) {
|
||||
encryptionUsable = false;
|
||||
return false;
|
||||
}
|
||||
const probe = 'metona-probe-0123456789abcdef';
|
||||
const cipher = safeStorage.encryptString(probe);
|
||||
const roundtrip = safeStorage.decryptString(cipher);
|
||||
encryptionUsable = roundtrip === probe;
|
||||
if (!encryptionUsable) {
|
||||
log.warn(
|
||||
'[SecureConfig] safeStorage roundtrip probe failed — falling back to plaintext storage for this session',
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
log.warn(
|
||||
'[SecureConfig] safeStorage probe threw — falling back to plaintext:',
|
||||
(err as Error).message,
|
||||
);
|
||||
encryptionUsable = false;
|
||||
}
|
||||
return encryptionUsable;
|
||||
}
|
||||
|
||||
/** 测试专用:清除 roundtrip 探测缓存(生产代码不得调用) */
|
||||
export function resetEncryptionUsableForTests(): void {
|
||||
encryptionUsable = null;
|
||||
}
|
||||
|
||||
/** 敏感配置 key 匹配模式(与 IPC 层审计脱敏规则保持一致) */
|
||||
const SENSITIVE_KEY_PATTERNS = [
|
||||
'apikey',
|
||||
@@ -57,7 +100,7 @@ export function encryptConfigValue(value: unknown): unknown {
|
||||
if (typeof value !== 'string' || value.length === 0) return value;
|
||||
if (isEncryptedValue(value)) return value; // 已加密,幂等
|
||||
try {
|
||||
if (!safeStorage.isEncryptionAvailable()) {
|
||||
if (!isEncryptionUsable()) {
|
||||
log.warn('[SecureConfig] safeStorage 不可用,敏感配置将以明文存储');
|
||||
return value;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user