Files
thzxx 99d0c54129
CI / 类型检查 + Lint + 单元测试 (push) Failing after 6m27s
CI / 产物编译验证 (push) Successful in 9m57s
CI / 全量测试 (Electron ABI) (push) Failing after 5m19s
feat: v0.7.4 时序语义修正 · 防线实效补漏 · 全量测试翻倍 — 2406 用例 + jsdom 组件测试全量回归
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)
2026-08-30 19:19:07 +08:00

316 lines
11 KiB
TypeScript
Raw Permalink 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.
/**
* DeepSeekAdapter.getBalance 解析测试(v0.5.2 回归修复)
*
* 背景:DeepSeek 官方 /user/balance 实际返回 balance_infos 数组格式,
* 此前按扁平字段解析(data.total_balance)→ 恒为 undefined → 界面永远显示 0。
* 本测试固化两种格式(官方数组 + 网关扁平)的解析与 URL 规范化行为。
*/
import { describe, it, expect, vi, afterEach } from 'vitest';
vi.mock('electron-log', () => ({
default: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
}));
import { DeepSeekAdapter } from '../deepseek.adapter';
const CONFIG = {
provider: 'deepseek',
baseURL: 'https://api.deepseek.com',
apiKey: 'sk-test-key',
defaultModel: 'deepseek-v4-pro',
};
function makeAdapter(baseURL = CONFIG.baseURL): DeepSeekAdapter {
return new DeepSeekAdapter({ ...CONFIG, baseURL });
}
const mockFetch = vi.fn();
vi.stubGlobal('fetch', mockFetch);
afterEach(() => {
mockFetch.mockReset();
});
function okResponse(body: unknown): Response {
return {
ok: true,
status: 200,
json: async () => body,
} as unknown as Response;
}
describe('DeepSeekAdapter.getBalance — 响应格式解析(v0.5.2', () => {
it('官方 balance_infos 数组格式正确解析(真实 API 格式,修复点)', async () => {
mockFetch.mockResolvedValue(
okResponse({
is_available: true,
balance_infos: [
{
currency: 'CNY',
total_balance: '110.55',
granted_balance: '10.55',
topped_up_balance: '100.00',
},
],
}),
);
const balance = await makeAdapter().getBalance();
expect(balance).not.toBeNull();
expect(balance!.totalBalance).toBe('110.55');
expect(balance!.grantedBalance).toBe('10.55');
expect(balance!.toppedUpBalance).toBe('100.00');
expect(balance!.currency).toBe('CNY');
});
it('扁平格式回退解析(网关/代理简化响应兼容)', async () => {
mockFetch.mockResolvedValue(
okResponse({
currency: 'USD',
total_balance: '50.00',
granted_balance: '0.00',
topped_up_balance: '50.00',
}),
);
const balance = await makeAdapter().getBalance();
expect(balance).not.toBeNull();
expect(balance!.totalBalance).toBe('50.00');
expect(balance!.currency).toBe('USD');
});
it('baseURL 带尾斜杠或 /v1 前缀时规范化为根路径端点', async () => {
mockFetch.mockResolvedValue(
okResponse({
balance_infos: [{ currency: 'CNY', total_balance: '1.00' }],
}),
);
await makeAdapter('https://api.deepseek.com/v1/').getBalance();
expect(mockFetch).toHaveBeenCalledWith(
'https://api.deepseek.com/user/balance',
expect.objectContaining({ headers: { Authorization: 'Bearer sk-test-key' } }),
);
mockFetch.mockClear();
await makeAdapter('https://api.deepseek.com/v1').getBalance();
expect(mockFetch).toHaveBeenCalledWith(
'https://api.deepseek.com/user/balance',
expect.anything(),
);
});
it('非 2xx 响应返回 null', async () => {
mockFetch.mockResolvedValue({ ok: false, status: 401 } as unknown as Response);
expect(await makeAdapter().getBalance()).toBeNull();
});
it('请求异常返回 null(网络错误)', async () => {
mockFetch.mockRejectedValue(new Error('network down'));
expect(await makeAdapter().getBalance()).toBeNull();
});
it('balance_infos 多币种时取第一项', async () => {
mockFetch.mockResolvedValue(
okResponse({
balance_infos: [
{ currency: 'CNY', total_balance: '100.00' },
{ currency: 'USD', total_balance: '13.00' },
],
}),
);
const balance = await makeAdapter().getBalance();
expect(balance!.currency).toBe('CNY');
expect(balance!.totalBalance).toBe('100.00');
});
it('balance_infos 为空数组 → 回退扁平字段(无第一项可取)', async () => {
mockFetch.mockResolvedValue(
okResponse({ balance_infos: [], currency: 'EUR', total_balance: '9.99' }),
);
const balance = await makeAdapter().getBalance();
expect(balance!.currency).toBe('EUR');
expect(balance!.totalBalance).toBe('9.99');
});
it('balance_infos 首项字段缺失 → 默认 CNY / 0 兜底', async () => {
mockFetch.mockResolvedValue(okResponse({ balance_infos: [{}] }));
const balance = await makeAdapter().getBalance();
expect(balance).toEqual({
currency: 'CNY',
totalBalance: '0',
grantedBalance: '0',
toppedUpBalance: '0',
});
});
it('is_available=false 仍返回余额(可用性由上层决定,解析不短路)', async () => {
mockFetch.mockResolvedValue(
okResponse({
is_available: false,
balance_infos: [{ currency: 'CNY', total_balance: '0.5' }],
}),
);
const balance = await makeAdapter().getBalance();
expect(balance!.totalBalance).toBe('0.5');
});
it('json 解析失败(非法响应体)→ 返回 null', async () => {
mockFetch.mockResolvedValue({
ok: true,
status: 200,
json: async () => {
throw new Error('Unexpected token');
},
} as unknown as Response);
expect(await makeAdapter().getBalance()).toBeNull();
});
it('带 /v1 且带尾斜杠的 baseURL 规范化为根路径', async () => {
mockFetch.mockResolvedValue(okResponse({ balance_infos: [{ total_balance: '1' }] }));
await makeAdapter('https://api.deepseek.com/v1/').getBalance();
expect(mockFetch).toHaveBeenCalledWith(
'https://api.deepseek.com/user/balance',
expect.anything(),
);
});
it('多级尾斜杠 baseURL 规范化为根路径', async () => {
mockFetch.mockResolvedValue(okResponse({ balance_infos: [{ total_balance: '1' }] }));
await makeAdapter('https://api.deepseek.com///').getBalance();
expect(mockFetch).toHaveBeenCalledWith(
'https://api.deepseek.com/user/balance',
expect.anything(),
);
});
it('无 /v1 前缀的 baseURL 原样拼接(不重复插入)', async () => {
mockFetch.mockResolvedValue(okResponse({ balance_infos: [{ total_balance: '1' }] }));
await makeAdapter('https://api.deepseek.com').getBalance();
expect(mockFetch).toHaveBeenCalledWith(
'https://api.deepseek.com/user/balance',
expect.anything(),
);
});
it('子路径 baseURL(非 /v1 结尾)保留子路径', async () => {
mockFetch.mockResolvedValue(okResponse({ balance_infos: [{ total_balance: '1' }] }));
await makeAdapter('https://proxy.example.com/gw/v2').getBalance();
expect(mockFetch).toHaveBeenCalledWith(
'https://proxy.example.com/gw/v2/user/balance',
expect.anything(),
);
});
it('请求头携带 Bearer apiKey', async () => {
mockFetch.mockResolvedValue(okResponse({ balance_infos: [{ total_balance: '1' }] }));
await makeAdapter().getBalance();
const [, init] = mockFetch.mock.calls[0] as [string, RequestInit];
expect((init.headers as Record<string, string>).Authorization).toBe('Bearer sk-test-key');
});
it('网络异常与解析异常不抛出,统一返回 null(调用方安全)', async () => {
mockFetch.mockRejectedValue(new Error('ECONNREFUSED'));
expect(await makeAdapter().getBalance()).toBeNull();
mockFetch.mockResolvedValue({
ok: true,
json: async () => {
throw new Error('bad json');
},
} as unknown as Response);
expect(await makeAdapter().getBalance()).toBeNull();
});
it('currency 保留字符串原样(不做数值转换)', async () => {
mockFetch.mockResolvedValue(
okResponse({ balance_infos: [{ currency: 'CNY', total_balance: '110.55' }] }),
);
const balance = await makeAdapter().getBalance();
expect(balance!.currency).toBe('CNY');
expect(typeof balance!.totalBalance).toBe('string');
});
it('请求 URL 不含 /v1 时余额端点不受影响(契约回归)', async () => {
mockFetch.mockResolvedValue(okResponse({ balance_infos: [{ total_balance: '1' }] }));
await makeAdapter('https://api.deepseek.com/v1').getBalance();
const calledUrl = mockFetch.mock.calls[0][0] as string;
expect(calledUrl).not.toContain('/v1');
expect(calledUrl).toBe('https://api.deepseek.com/user/balance');
});
it('HTTP 429 返回 null(限流不视为余额数据)', async () => {
mockFetch.mockResolvedValue({ ok: false, status: 429 } as unknown as Response);
expect(await makeAdapter().getBalance()).toBeNull();
});
it('HTTP 500 返回 null', async () => {
mockFetch.mockResolvedValue({ ok: false, status: 500 } as unknown as Response);
expect(await makeAdapter().getBalance()).toBeNull();
});
it('HTTP 403 返回 null(鉴权失败)', async () => {
mockFetch.mockResolvedValue({ ok: false, status: 403 } as unknown as Response);
expect(await makeAdapter().getBalance()).toBeNull();
});
it('空 apiKey 时发送空 Bearer 头(v0.7.4 修正命名 —— 原"不含 Authorization"与实际断言相反)', async () => {
mockFetch.mockResolvedValue(okResponse({ balance_infos: [{ total_balance: '1' }] }));
await makeAdapter().getBalance();
// 适配器配置始终携带 apiKey;此处验证 apiKey 为空串时头部仍带 'Bearer '(空值)
const noKeyAdapter = new DeepSeekAdapter({ ...CONFIG, apiKey: '' });
mockFetch.mockClear();
mockFetch.mockResolvedValue(okResponse({ balance_infos: [{ total_balance: '1' }] }));
await noKeyAdapter.getBalance();
const [, init] = mockFetch.mock.calls[0] as [string, RequestInit];
expect((init.headers as Record<string, string>).Authorization).toBe('Bearer ');
});
it('数字型 total_balance(非字符串)原样透传', async () => {
mockFetch.mockResolvedValue(
okResponse({ balance_infos: [{ currency: 'CNY', total_balance: 88 }] }),
);
const balance = await makeAdapter().getBalance();
expect(balance!.totalBalance).toBe(88);
});
it('响应为空对象 → 全部默认值', async () => {
mockFetch.mockResolvedValue(okResponse({}));
const balance = await makeAdapter().getBalance();
expect(balance).toEqual({
currency: 'CNY',
totalBalance: '0',
grantedBalance: '0',
toppedUpBalance: '0',
});
});
it('granted_balance 缺失仅缺省为 0(不影响其余字段)', async () => {
mockFetch.mockResolvedValue(
okResponse({
balance_infos: [{ currency: 'USD', total_balance: '5.0', topped_up_balance: '5.0' }],
}),
);
const balance = await makeAdapter().getBalance();
expect(balance!.grantedBalance).toBe('0');
expect(balance!.totalBalance).toBe('5.0');
});
it('balance_infos 元素为 null → 回退扁平字段(防御空条目)', async () => {
mockFetch.mockResolvedValue(
okResponse({ balance_infos: [null], currency: 'JPY', total_balance: '1000' }),
);
const balance = await makeAdapter().getBalance();
expect(balance!.currency).toBe('JPY');
expect(balance!.totalBalance).toBe('1000');
});
it('多次调用互不影响(每次独立 fetch)', async () => {
mockFetch.mockResolvedValue(okResponse({ balance_infos: [{ total_balance: '1' }] }));
const adapter = makeAdapter();
await adapter.getBalance();
await adapter.getBalance();
expect(mockFetch).toHaveBeenCalledTimes(2);
});
});