fix: v0.5.2 紧急修复 — 工具调用完全失效(引擎懒创建不带工具)+ DeepSeek 余额解析错误
P0 工具调用失效(用户实测反馈:Agnes/DeepSeek 均无法调用工具): - 根因:AgentEngineManager.createEngine 未调用 setTools。引擎是懒创建的 (首次 sendMessage 时 getEngine),启动期的 setToolsAll 调用时 engines Map 为空(全是 no-op)→ 新引擎 this.tools=[] → LLM 请求不带 tools → 模型无法发起 tool_call。症状与用户反馈完全吻合:模型口头说要调工具 (模仿历史消息中的工具调用模式),实际不调,凭记忆瞎编结果。 - 引入点:v0.4.0 P2-10 每会话引擎重构(v0.3.x 全局单引擎时代 setTools 直接作用于唯一引擎,无此问题)。 - 修复:createEngine 从 toolRegistry 拉取当前启用工具(registry 是启用 状态的唯一事实源,MCP 后注册/工具开关场景均一致)。 P1 DeepSeek 余额显示错误(用户实测反馈:显示的不是真实余额): - 根因:DeepSeek 官方 /user/balance 实际返回 balance_infos 数组格式, 此前按扁平字段解析(data.total_balance)→ 恒为 undefined → 界面恒显示 0。 - 修复:优先解析 balance_infos[0],回退扁平格式(网关兼容);URL 规范化 (剥离尾斜杠与 /v1 前缀 — 余额端点在根路径,chat 端点两种写法都合法)。 测试(215 → 224 用例): - 新增 AgentEngineManager 回归测试 ×4:懒创建引擎的 LLM 请求必须携带 registry 工具定义(本次事故的直接拦截测试)/ 禁用工具不出现 / setToolsAll 热更新 / 无 registry 时行为不回归 - 新增 DeepSeek 余额解析测试 ×5:官方数组格式 / 扁平回退 / URL 规范化 / 非 2xx / 网络异常 - 补强引擎链路测试:mock adapter 记录请求并断言 tools 契约 — 此前 mock 无条件吐 tool_call 事件,掩盖了"请求未携带工具定义"的缺陷(复检盲区 的直接教训:mock 必须断言请求契约,否则测试是道具) 验证: lint 0 / typecheck 双工程 0 / test:electron 224 全过 / build 成功
This commit is contained in:
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* 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();
|
||||
});
|
||||
});
|
||||
@@ -53,21 +53,25 @@ export class DeepSeekAdapter extends BaseAdapter {
|
||||
const body = this.toNativeRequest(request, false);
|
||||
|
||||
// #24 修复: 使用 fetchWithTimeout 替代 getFetchSignal + fetch,确保 timer 清理
|
||||
const response = await this.fetchWithTimeout(`${this.config.baseURL}/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${this.config.apiKey}`,
|
||||
...this.config.headers,
|
||||
const response = await this.fetchWithTimeout(
|
||||
`${this.config.baseURL}/chat/completions`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${this.config.apiKey}`,
|
||||
...this.config.headers,
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
}, this.config.timeoutMs ?? 120_000);
|
||||
this.config.timeoutMs ?? 120_000,
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
await this.throwHttpError(response, 'DeepSeek API error');
|
||||
}
|
||||
|
||||
const data = await response.json() as Record<string, unknown>;
|
||||
const data = (await response.json()) as Record<string, unknown>;
|
||||
const parsed = parseOpenAICompatibleResponse(data);
|
||||
|
||||
return {
|
||||
@@ -93,15 +97,19 @@ export class DeepSeekAdapter extends BaseAdapter {
|
||||
const body = this.toNativeRequest(request, true);
|
||||
|
||||
// #24 修复: 使用 fetchWithTimeout 替代 getFetchSignal + fetch,确保 timer 清理
|
||||
const response = await this.fetchWithTimeout(`${this.config.baseURL}/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${this.config.apiKey}`,
|
||||
...this.config.headers,
|
||||
const response = await this.fetchWithTimeout(
|
||||
`${this.config.baseURL}/chat/completions`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${this.config.apiKey}`,
|
||||
...this.config.headers,
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
}, this.config.timeoutMs ?? 300_000);
|
||||
this.config.timeoutMs ?? 300_000,
|
||||
);
|
||||
|
||||
if (!response.ok || !response.body) {
|
||||
await this.throwHttpError(response, 'DeepSeek stream error');
|
||||
@@ -132,7 +140,7 @@ export class DeepSeekAdapter extends BaseAdapter {
|
||||
signal: AbortSignal.timeout(10_000),
|
||||
});
|
||||
if (response.ok) {
|
||||
const data = await response.json() as { data?: Array<{ id: string }> };
|
||||
const data = (await response.json()) as { data?: Array<{ id: string }> };
|
||||
if (data.data?.length) {
|
||||
// 合并 API 返回的模型 ID 与本地元数据
|
||||
return data.data.map((m) => DeepSeekAdapter.MODEL_INFO[m.id] ?? { id: m.id });
|
||||
@@ -164,6 +172,18 @@ export class DeepSeekAdapter extends BaseAdapter {
|
||||
|
||||
// ===== GET /user/balance =====
|
||||
|
||||
/**
|
||||
* 查询账户余额
|
||||
*
|
||||
* v0.5.2 修复: DeepSeek 官方 API 实际返回 `balance_infos` 数组格式:
|
||||
* { "is_available": true, "balance_infos": [{ "currency": "CNY",
|
||||
* "total_balance": "110.00", "granted_balance": "10.00", "topped_up_balance": "100.00" }] }
|
||||
* 此前按扁平字段解析(data.total_balance)→ 永远取到 undefined → 恒显示 0。
|
||||
* 现优先取 balance_infos[0],回退扁平格式(兼容网关/代理的简化响应)。
|
||||
*
|
||||
* URL 规范化: 余额端点为 {root}/user/balance(无 /v1 前缀)。用户配置的
|
||||
* baseURL 可能带 /v1 或尾斜杠(chat 端点两种写法都合法),此处剥离后拼接。
|
||||
*/
|
||||
async getBalance(): Promise<{
|
||||
currency: string;
|
||||
totalBalance: string;
|
||||
@@ -171,20 +191,34 @@ export class DeepSeekAdapter extends BaseAdapter {
|
||||
toppedUpBalance: string;
|
||||
} | null> {
|
||||
try {
|
||||
const response = await fetch(`${this.config.baseURL}/user/balance`, {
|
||||
// 规范化 baseURL:去尾斜杠、去尾 /v1(余额端点在根路径下)
|
||||
const root = this.config.baseURL.replace(/\/+$/, '').replace(/\/v1$/, '');
|
||||
const response = await fetch(`${root}/user/balance`, {
|
||||
headers: { Authorization: `Bearer ${this.config.apiKey}` },
|
||||
signal: AbortSignal.timeout(10_000),
|
||||
});
|
||||
if (!response.ok) return null;
|
||||
const data = await response.json() as {
|
||||
currency?: string; total_balance?: string;
|
||||
granted_balance?: string; topped_up_balance?: string;
|
||||
const data = (await response.json()) as {
|
||||
is_available?: boolean;
|
||||
balance_infos?: Array<{
|
||||
currency?: string;
|
||||
total_balance?: string;
|
||||
granted_balance?: string;
|
||||
topped_up_balance?: string;
|
||||
}>;
|
||||
// 扁平格式字段(网关/代理兼容)
|
||||
currency?: string;
|
||||
total_balance?: string;
|
||||
granted_balance?: string;
|
||||
topped_up_balance?: string;
|
||||
};
|
||||
// 优先官方 balance_infos 数组,回退扁平格式
|
||||
const info = data.balance_infos?.[0] ?? data;
|
||||
return {
|
||||
currency: data.currency ?? 'CNY',
|
||||
totalBalance: data.total_balance ?? '0',
|
||||
grantedBalance: data.granted_balance ?? '0',
|
||||
toppedUpBalance: data.topped_up_balance ?? '0',
|
||||
currency: info.currency ?? 'CNY',
|
||||
totalBalance: info.total_balance ?? '0',
|
||||
grantedBalance: info.granted_balance ?? '0',
|
||||
toppedUpBalance: info.topped_up_balance ?? '0',
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
@@ -228,7 +262,10 @@ export class DeepSeekAdapter extends BaseAdapter {
|
||||
} else if (request.params.thinkingEnabled) {
|
||||
body.thinking = { type: 'enabled' };
|
||||
const effortMap: Record<string, string> = {
|
||||
low: 'high', medium: 'high', high: 'high', max: 'max',
|
||||
low: 'high',
|
||||
medium: 'high',
|
||||
high: 'high',
|
||||
max: 'max',
|
||||
};
|
||||
// DeepSeek API 仅支持 high / max 两档,low/medium 映射为 high
|
||||
body.reasoning_effort = effortMap[request.params.thinkingEffort ?? 'high'] ?? 'high';
|
||||
|
||||
Reference in New Issue
Block a user