Files
metona-ai-desktop/electron/utils/__tests__/network-proxy.test.ts
T
thzxx 9b45c445bf
CI / 类型检查 + Lint + 单元测试 (push) Failing after 9m8s
CI / 全量测试 (Electron ABI) (push) Failing after 6m0s
CI / 产物编译验证 (push) Successful in 10m58s
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 全项留档。
2026-09-08 09:35:58 +08:00

212 lines
7.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Network Proxy 测试(v0.7.2 覆盖补齐 —— 此前零测试)
*
* 锁定 session 级代理应用契约(v0.6.4 P4-5 的回归防线):
* 1. 配置 proxyUrl → Chromium 双分区(default + agent-browser+ undici ProxyAgent
* 2. 环境变量回退(HTTPS_PROXY/HTTP_PROXY
* 3. 双空 → 显式直连(direct mode + 直连 Agent
* 4. 失败语义:任一通道失败仅 WARN 不阻断主流程
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
const sessionMocks = vi.hoisted(() => ({
defaultSetProxy: vi.fn(async (..._args: unknown[]) => undefined),
partitionSetProxy: vi.fn(async (..._args: unknown[]) => undefined),
throwOnDefaultSetProxy: false,
throwOnPartitionSetProxy: false,
}));
vi.mock('electron', () => ({
session: {
defaultSession: {
setProxy: (...args: unknown[]) => {
if (sessionMocks.throwOnDefaultSetProxy) {
return Promise.reject(new Error('setProxy exploded'));
}
return sessionMocks.defaultSetProxy(...args);
},
},
fromPartition: () => ({
setProxy: (...args: unknown[]) => {
if (sessionMocks.throwOnPartitionSetProxy) {
return Promise.reject(new Error('partition setProxy exploded'));
}
return sessionMocks.partitionSetProxy(...args);
},
}),
},
}));
vi.mock('electron-log', () => ({
default: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
}));
const undiciMocks = vi.hoisted(() => ({
setGlobalDispatcher: vi.fn(),
proxyAgentCalls: [] as string[],
agentCalls: 0,
}));
vi.mock('undici', () => ({
Agent: class {
constructor() {
undiciMocks.agentCalls++;
}
},
ProxyAgent: class {
constructor(opts: { uri: string }) {
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),
}));
import { applySessionProxy, isProxyActive } from '../network-proxy';
beforeEach(() => {
sessionMocks.defaultSetProxy.mockClear();
sessionMocks.partitionSetProxy.mockClear();
sessionMocks.throwOnDefaultSetProxy = false;
sessionMocks.throwOnPartitionSetProxy = false;
undiciMocks.setGlobalDispatcher.mockClear();
undiciMocks.proxyAgentCalls.length = 0;
undiciMocks.agentCalls = 0;
delete process.env['HTTPS_PROXY'];
delete process.env['HTTP_PROXY'];
});
afterEach(() => {
delete process.env['HTTPS_PROXY'];
delete process.env['HTTP_PROXY'];
});
describe('applySessionProxy — 双通道应用', () => {
it('配置代理 → default + agent-browser 分区均设置 proxyRulesundici 走 ProxyAgent', async () => {
await applySessionProxy('http://127.0.0.1:7890');
const expected = { proxyRules: 'http://127.0.0.1:7890' };
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);
});
it('代理地址两侧空白被 trim', async () => {
await applySessionProxy(' http://proxy.local:8080 ');
expect(sessionMocks.defaultSetProxy).toHaveBeenCalledWith({
proxyRules: 'http://proxy.local:8080',
});
});
});
describe('applySessionProxy — 环境变量回退链', () => {
it('未配置 proxyUrl 时回退 HTTPS_PROXY 环境变量', async () => {
process.env['HTTPS_PROXY'] = 'http://env-proxy:3128';
await applySessionProxy(null);
expect(sessionMocks.defaultSetProxy).toHaveBeenCalledWith({
proxyRules: 'http://env-proxy:3128',
});
});
it('HTTPS_PROXY 缺失时回退 HTTP_PROXY', async () => {
process.env['HTTP_PROXY'] = 'http://env-http:3128';
await applySessionProxy(undefined);
expect(sessionMocks.defaultSetProxy).toHaveBeenCalledWith({
proxyRules: 'http://env-http:3128',
});
});
it('双空 → 显式直连(direct mode + 直连 Agent', async () => {
await applySessionProxy(null);
expect(sessionMocks.defaultSetProxy).toHaveBeenCalledWith({ mode: 'direct' });
expect(undiciMocks.agentCalls).toBe(1); // 直连 Agent
expect(undiciMocks.proxyAgentCalls).toHaveLength(0);
});
it('配置空串视为未配置(回退环境变量)', async () => {
process.env['HTTPS_PROXY'] = 'http://env-fallback:1';
await applySessionProxy(' ');
expect(sessionMocks.defaultSetProxy).toHaveBeenCalledWith({
proxyRules: 'http://env-fallback:1',
});
});
it('proxyUrl 与 HTTPS_PROXY 同时存在 → proxyUrl 优先(显式配置覆盖环境变量)', async () => {
process.env['HTTPS_PROXY'] = 'http://env-ignored:3128';
await applySessionProxy('http://explicit:8080');
expect(sessionMocks.defaultSetProxy).toHaveBeenCalledWith({
proxyRules: 'http://explicit:8080',
});
});
it('HTTPS_PROXY 为空串时回退 HTTP_PROXY', async () => {
process.env['HTTPS_PROXY'] = '';
process.env['HTTP_PROXY'] = 'http://fallback:3128';
await applySessionProxy(null);
expect(sessionMocks.defaultSetProxy).toHaveBeenCalledWith({
proxyRules: 'http://fallback:3128',
});
});
});
describe('applySessionProxy — 失败语义(绝不阻断主流程)', () => {
it('Chromium 通道失败 → 仅 WARNundici 通道照常设置', async () => {
sessionMocks.throwOnDefaultSetProxy = true;
await expect(applySessionProxy('http://proxy:1')).resolves.toBeUndefined();
expect(undiciMocks.proxyAgentCalls).toEqual(['http://proxy:1']);
});
it('agent-browser 分区失败 → 仅 WARNdefault 与 undici 不受影响', async () => {
sessionMocks.throwOnPartitionSetProxy = true;
await expect(applySessionProxy('http://proxy:2')).resolves.toBeUndefined();
expect(sessionMocks.defaultSetProxy).toHaveBeenCalledWith({
proxyRules: 'http://proxy:2',
});
expect(undiciMocks.proxyAgentCalls).toEqual(['http://proxy:2']);
});
it('双通道均失败 → 不抛错(resolve undefined', async () => {
sessionMocks.throwOnDefaultSetProxy = true;
sessionMocks.throwOnPartitionSetProxy = true;
await expect(applySessionProxy('http://proxy:3')).resolves.toBeUndefined();
});
});
describe('isProxyActive — 代理激活标志(P2-1', () => {
it('配置代理后标志为 true', async () => {
await applySessionProxy('http://proxy:8080');
expect(isProxyActive()).toBe(true);
});
it('回退环境变量后标志为 true', async () => {
process.env['HTTPS_PROXY'] = 'http://env:3128';
await applySessionProxy(null);
expect(isProxyActive()).toBe(true);
});
it('双空直连后标志为 false', async () => {
await applySessionProxy(null);
expect(isProxyActive()).toBe(false);
});
it('先激活再切回直连 → 标志复位为 false', async () => {
await applySessionProxy('http://proxy:1');
expect(isProxyActive()).toBe(true);
await applySessionProxy(null);
expect(isProxyActive()).toBe(false);
});
});