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:
@@ -10,7 +10,7 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="https://img.shields.io/badge/version-0.5.1-blue?style=flat-square" alt="Version" />
|
||||
<img src="https://img.shields.io/badge/version-0.5.2-blue?style=flat-square" alt="Version" />
|
||||
<img src="https://img.shields.io/badge/license-MIT-green?style=flat-square" alt="License" />
|
||||
<img src="https://img.shields.io/badge/Electron-35-47848F?style=flat-square&logo=electron" alt="Electron" />
|
||||
<img src="https://img.shields.io/badge/React-19-61DAFB?style=flat-square&logo=react" alt="React" />
|
||||
@@ -865,7 +865,7 @@ npm run format # Prettier 格式化
|
||||
|
||||
# ─── 测试 ─────────────────────────────────
|
||||
npm test # 运行单元测试 (Vitest, 系统 Node — audit 套件因 better-sqlite3 ABI 自动跳过)
|
||||
npm run test:electron # 运行全量单元测试 (Electron Node ABI, 215 用例全执行, 含 SQLite 审计链哈希 + 引擎工具链集成)
|
||||
npm run test:electron # 运行全量单元测试 (Electron Node ABI, 224 用例全执行, 含 SQLite 审计链哈希 + 引擎工具链集成)
|
||||
npm run test:watch # 测试监听模式
|
||||
|
||||
# ─── 构建 ─────────────────────────────────
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -25,6 +25,7 @@ import { AgentLoopEngine } from '../engine';
|
||||
import { TerminationReason } from '../types';
|
||||
import type {
|
||||
IMetonaProviderAdapter,
|
||||
MetonaRequest,
|
||||
MetonaResponse,
|
||||
MetonaStreamEvent,
|
||||
MetonaToolDef,
|
||||
@@ -36,7 +37,11 @@ import { PermissionCheckHook, RateLimitHook } from '../../hooks/pre-tool';
|
||||
import { ConfirmationHook } from '../../hooks/confirmation-hook';
|
||||
import { PolicyEngine } from '../../sandbox/permissions';
|
||||
|
||||
// ===== Mock Adapter(流式 tool_call → 文本收尾) =====
|
||||
// ===== Mock Adapter(流式 tool_call → 文本收尾;记录请求供契约断言) =====
|
||||
// v0.5.2 教训:mock 无条件吐 tool_call 事件会掩盖"请求未携带工具定义"的契约缺陷
|
||||
// (模型只有收到 tools 才能真正发起 tool_call)— 此处记录 requests 供断言。
|
||||
|
||||
const recordedRequests: MetonaRequest[] = [];
|
||||
|
||||
function createMockAdapter(scripts: MetonaStreamEvent[][]): IMetonaProviderAdapter {
|
||||
let call = 0;
|
||||
@@ -60,7 +65,8 @@ function createMockAdapter(scripts: MetonaStreamEvent[][]): IMetonaProviderAdapt
|
||||
finishReason: 'stop' as never,
|
||||
}),
|
||||
),
|
||||
sendStream: vi.fn(async function* (): AsyncIterable<MetonaStreamEvent> {
|
||||
sendStream: vi.fn(async function* (req: MetonaRequest): AsyncIterable<MetonaStreamEvent> {
|
||||
recordedRequests.push(req);
|
||||
const script = scripts[call % scripts.length];
|
||||
call++;
|
||||
for (const ev of script) yield ev;
|
||||
@@ -173,18 +179,23 @@ function makeEngineWithHooks(
|
||||
registry.registerBuiltin(makeTool('read_file'));
|
||||
registry.registerBuiltin(makeTool('run_command'));
|
||||
|
||||
return new AgentLoopEngine(
|
||||
const engine = new AgentLoopEngine(
|
||||
{ maxIterations },
|
||||
createMockAdapter(adapterScripts),
|
||||
registry,
|
||||
[new PermissionCheckHook(new PolicyEngine()), new RateLimitHook(100), hook],
|
||||
[],
|
||||
);
|
||||
// 模拟 AgentEngineManager.createEngine 的正确接线(v0.5.2 修复):
|
||||
// 引擎不自动从 registry 拉取请求工具,必须显式 setTools
|
||||
engine.setTools(registry.listTools());
|
||||
return engine;
|
||||
}
|
||||
|
||||
describe('AgentLoopEngine 工具调用链路(adapter → 引擎 → 真实 Hook 管道 → registry)', () => {
|
||||
it('SAFE 工具免确认直接执行:结果回填 + 工具上下文 sessionId 正确', async () => {
|
||||
executedTools.length = 0;
|
||||
recordedRequests.length = 0;
|
||||
const hook = new ConfirmationHook(makeMockWindow(), null);
|
||||
|
||||
const engine = makeEngineWithHooks(
|
||||
@@ -194,6 +205,12 @@ describe('AgentLoopEngine 工具调用链路(adapter → 引擎 → 真实 Hoo
|
||||
|
||||
const output = await engine.runStream(userMessage, 'sess-chain-1', [], systemPrompt);
|
||||
|
||||
// 请求契约:LLM 请求必须携带工具定义(v0.5.2 回归点 —
|
||||
// 真实模型只有收到 tools 才能发起 tool_call,缺失即"口头说调工具实际不调")
|
||||
expect(recordedRequests.length).toBeGreaterThan(0);
|
||||
expect(recordedRequests[0].tools).toBeDefined();
|
||||
expect(recordedRequests[0].tools!.map((t) => t.name)).toContain('read_file');
|
||||
|
||||
// 循环完成:工具轮 → 文本轮
|
||||
expect(output.terminationReason).toBe(TerminationReason.COMPLETED);
|
||||
expect(output.finalAnswer).toBe('done after tool');
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
/**
|
||||
* AgentEngineManager 回归测试(v0.5.2)
|
||||
*
|
||||
* 背景:v0.4.0 P2-10 引入每会话懒创建引擎后,createEngine 未调用 setTools,
|
||||
* 且启动期 setToolsAll 调用时 engines Map 为空(全是 no-op)→ 新引擎 tools=[]
|
||||
* → LLM 请求不带工具定义 → 模型无法发起 tool_call,只能凭历史记忆"口头说要
|
||||
* 调工具"并瞎编结果。v0.5.2 在 createEngine 中从 registry 拉取工具修复。
|
||||
*
|
||||
* 本测试直接断言"传给 adapter.sendStream 的请求携带工具"——这是唯一能
|
||||
* 拦住该类回归的测试层级(引擎单测的 mock adapter 无条件吐 tool_call
|
||||
* 事件,会掩盖请求契约缺陷)。
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
|
||||
vi.mock('electron-log', () => ({
|
||||
default: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
|
||||
}));
|
||||
|
||||
import { AgentEngineManager } from '../agent-engine-manager.service';
|
||||
import type {
|
||||
IMetonaProviderAdapter,
|
||||
MetonaRequest,
|
||||
MetonaResponse,
|
||||
MetonaStreamEvent,
|
||||
} from '../../harness/types';
|
||||
import { MetonaStreamEventType } from '../../harness/types';
|
||||
import { ToolRegistry } from '../../harness/tools/registry';
|
||||
import type { IMetonaTool } from '../../harness/types/metona-tool';
|
||||
import { MetonaToolCategory, MetonaRiskLevel } from '../../harness/types';
|
||||
|
||||
/** 记录请求的 mock adapter — runStream 完成后检查 requests 数组 */
|
||||
function createRecordingAdapter(requests: MetonaRequest[]): IMetonaProviderAdapter {
|
||||
return {
|
||||
providerId: 'mock',
|
||||
supportedModels: ['mock-model'],
|
||||
supportsToolCalling: true,
|
||||
supportsThinking: false,
|
||||
getContextWindow: () => 1_000_000,
|
||||
send: vi.fn(
|
||||
async (): Promise<MetonaResponse> => ({
|
||||
meta: { requestId: 'r', provider: 'mock', model: 'm', latencyMs: 1, timestamp: Date.now() },
|
||||
content: 'ok',
|
||||
usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
|
||||
finishReason: 'stop' as never,
|
||||
}),
|
||||
),
|
||||
sendStream: vi.fn(async function* (req: MetonaRequest): AsyncIterable<MetonaStreamEvent> {
|
||||
requests.push(req);
|
||||
yield {
|
||||
type: MetonaStreamEventType.TEXT_DELTA,
|
||||
requestId: 'r',
|
||||
sessionId: req.meta.sessionId,
|
||||
iteration: req.meta.iteration,
|
||||
seq: 0,
|
||||
timestamp: Date.now(),
|
||||
delta: 'done',
|
||||
};
|
||||
yield {
|
||||
type: MetonaStreamEventType.DONE,
|
||||
requestId: 'r',
|
||||
sessionId: req.meta.sessionId,
|
||||
iteration: req.meta.iteration,
|
||||
seq: 1,
|
||||
timestamp: Date.now(),
|
||||
};
|
||||
}),
|
||||
setAbortSignal: vi.fn(),
|
||||
healthCheck: async () => true,
|
||||
};
|
||||
}
|
||||
|
||||
function makeTool(name: string): IMetonaTool {
|
||||
return {
|
||||
definition: {
|
||||
name,
|
||||
description: `${name} (test fixture)`,
|
||||
parameters: { type: 'object', properties: {}, required: [] },
|
||||
category: MetonaToolCategory.FILESYSTEM,
|
||||
riskLevel: MetonaRiskLevel.SAFE,
|
||||
requiresPermission: false,
|
||||
timeoutMs: 5_000,
|
||||
},
|
||||
async execute() {
|
||||
return { ok: true };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const userMessage = { role: 'user' as const, content: 'hello', timestamp: Date.now() };
|
||||
const systemPrompt = { roleDefinition: '', outputConstraints: '', safetyGuidelines: '' };
|
||||
|
||||
describe('AgentEngineManager — 懒创建引擎的工具传递(v0.5.2 回归修复)', () => {
|
||||
it('新会话首次 sendMessage 时,LLM 请求必须携带 registry 中的工具定义', async () => {
|
||||
const requests: MetonaRequest[] = [];
|
||||
const adapter = createRecordingAdapter(requests);
|
||||
const registry = new ToolRegistry();
|
||||
registry.registerBuiltin(makeTool('read_file'));
|
||||
registry.registerBuiltin(makeTool('run_command'));
|
||||
|
||||
// 模拟真实启动流程:manager 创建时 registry 已有工具,
|
||||
// 但引擎在首次 sendMessage 才懒创建(setToolsAll 此时是 no-op)
|
||||
const manager = new AgentEngineManager({
|
||||
buildAdapter: () => adapter,
|
||||
baseConfig: {},
|
||||
toolRegistry: registry,
|
||||
});
|
||||
|
||||
const engine = manager.getEngine('sess-lazy-1');
|
||||
await engine.runStream(userMessage, 'sess-lazy-1', [], systemPrompt);
|
||||
|
||||
// 核心断言:请求携带工具定义(回归点 — 修复前为 undefined)
|
||||
expect(requests).toHaveLength(1);
|
||||
expect(requests[0].tools).toBeDefined();
|
||||
expect(requests[0].tools!.map((t) => t.name)).toContain('read_file');
|
||||
expect(requests[0].tools!.map((t) => t.name)).toContain('run_command');
|
||||
});
|
||||
|
||||
it('已禁用的工具不出现在懒创建引擎的请求中', async () => {
|
||||
const requests: MetonaRequest[] = [];
|
||||
const adapter = createRecordingAdapter(requests);
|
||||
const registry = new ToolRegistry();
|
||||
registry.registerBuiltin(makeTool('read_file'));
|
||||
registry.registerBuiltin(makeTool('web_browser'));
|
||||
registry.setToolEnabled('web_browser', false);
|
||||
|
||||
const manager = new AgentEngineManager({
|
||||
buildAdapter: () => adapter,
|
||||
baseConfig: {},
|
||||
toolRegistry: registry,
|
||||
});
|
||||
|
||||
const engine = manager.getEngine('sess-lazy-2');
|
||||
await engine.runStream(userMessage, 'sess-lazy-2', [], systemPrompt);
|
||||
|
||||
expect(requests[0].tools).toBeDefined();
|
||||
expect(requests[0].tools!.map((t) => t.name)).toContain('read_file');
|
||||
expect(requests[0].tools!.map((t) => t.name)).not.toContain('web_browser');
|
||||
});
|
||||
|
||||
it('setToolsAll 仍可热更新已存在的引擎(工具开关变更场景)', async () => {
|
||||
const requests: MetonaRequest[] = [];
|
||||
const adapter = createRecordingAdapter(requests);
|
||||
const registry = new ToolRegistry();
|
||||
registry.registerBuiltin(makeTool('read_file'));
|
||||
|
||||
const manager = new AgentEngineManager({
|
||||
buildAdapter: () => adapter,
|
||||
baseConfig: {},
|
||||
toolRegistry: registry,
|
||||
});
|
||||
|
||||
const engine = manager.getEngine('sess-hot');
|
||||
await engine.runStream(userMessage, 'sess-hot', [], systemPrompt);
|
||||
expect(requests[0].tools!.map((t) => t.name)).toContain('read_file');
|
||||
|
||||
// 热更新:新注册工具 + setToolsAll 同步
|
||||
registry.registerBuiltin(makeTool('new_tool'));
|
||||
manager.setToolsAll(registry.listTools());
|
||||
|
||||
requests.length = 0;
|
||||
await engine.runStream(userMessage, 'sess-hot', [], systemPrompt);
|
||||
expect(requests[0].tools!.map((t) => t.name)).toContain('new_tool');
|
||||
});
|
||||
|
||||
it('无 toolRegistry 时请求不带 tools(纯对话配置,行为不回归)', async () => {
|
||||
const requests: MetonaRequest[] = [];
|
||||
const adapter = createRecordingAdapter(requests);
|
||||
|
||||
const manager = new AgentEngineManager({
|
||||
buildAdapter: () => adapter,
|
||||
baseConfig: {},
|
||||
});
|
||||
|
||||
const engine = manager.getEngine('sess-no-tools');
|
||||
await engine.runStream(userMessage, 'sess-no-tools', [], systemPrompt);
|
||||
|
||||
expect(requests[0].tools).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -39,14 +39,16 @@ export class AgentEngineManager extends EventEmitter {
|
||||
private baseConfig: Partial<AgentLoopConfig>;
|
||||
private workspacePath = '';
|
||||
|
||||
constructor(private opts: {
|
||||
/** adapter 工厂(每次调用返回新实例;闭包内读取最新配置) */
|
||||
buildAdapter: () => IMetonaProviderAdapter;
|
||||
baseConfig: Partial<AgentLoopConfig>;
|
||||
toolRegistry?: ToolRegistry;
|
||||
preToolHooks?: PreToolHook[];
|
||||
postToolHooks?: PostToolHook[];
|
||||
}) {
|
||||
constructor(
|
||||
private opts: {
|
||||
/** adapter 工厂(每次调用返回新实例;闭包内读取最新配置) */
|
||||
buildAdapter: () => IMetonaProviderAdapter;
|
||||
baseConfig: Partial<AgentLoopConfig>;
|
||||
toolRegistry?: ToolRegistry;
|
||||
preToolHooks?: PreToolHook[];
|
||||
postToolHooks?: PostToolHook[];
|
||||
},
|
||||
) {
|
||||
super();
|
||||
this.primaryAdapter = opts.buildAdapter();
|
||||
this.baseConfig = { ...opts.baseConfig };
|
||||
@@ -153,8 +155,19 @@ export class AgentEngineManager extends EventEmitter {
|
||||
);
|
||||
engine.setFallbackAdapter(this.fallbackAdapter);
|
||||
if (this.workspacePath) engine.setWorkspacePath(this.workspacePath);
|
||||
// v0.5.2 关键修复: 新建引擎从 registry 拉取当前启用工具。
|
||||
// setToolsAll 只同步"已存在"的引擎 — 引擎是懒创建的(首次 sendMessage 时 getEngine),
|
||||
// 启动期的 setToolsAll 调用时 engines Map 为空,全是 no-op。
|
||||
// 此前缺此调用 → 新引擎 this.tools=[] → LLM 请求不带 tools →
|
||||
// 模型无法发起 tool_call(症状:模型口头说要调工具,实际不调,凭历史记忆瞎编)。
|
||||
// v0.4.0 P2-10 引入每会话引擎时遗留的回归,v0.5.2 修复。
|
||||
if (this.opts.toolRegistry) {
|
||||
engine.setTools(this.opts.toolRegistry.listTools());
|
||||
}
|
||||
this.forwardEngineEvents(engine, sessionId);
|
||||
log.debug(`[EngineManager] engine created for session ${sessionId} (total: ${this.engines.size + 1})`);
|
||||
log.debug(
|
||||
`[EngineManager] engine created for session ${sessionId} (total: ${this.engines.size + 1})`,
|
||||
);
|
||||
return engine;
|
||||
}
|
||||
|
||||
@@ -167,7 +180,8 @@ export class AgentEngineManager extends EventEmitter {
|
||||
const payload = { ...data, sessionId: data.sessionId || sessionId };
|
||||
// 维护运行中集合(LRU 淘汰保护)
|
||||
if (payload.state === 'INIT' || payload.current === 'INIT') this.running.add(sessionId);
|
||||
if (payload.state === 'TERMINATED' || payload.current === 'TERMINATED') this.running.delete(sessionId);
|
||||
if (payload.state === 'TERMINATED' || payload.current === 'TERMINATED')
|
||||
this.running.delete(sessionId);
|
||||
this.emit('stateChange', payload);
|
||||
});
|
||||
engine.on('complete', (data) => {
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "metona-ai-desktop",
|
||||
"version": "0.5.0",
|
||||
"version": "0.5.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "metona-ai-desktop",
|
||||
"version": "0.5.0",
|
||||
"version": "0.5.1",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@emotion/react": "^11.14.0",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "metona-ai-desktop",
|
||||
"version": "0.5.1",
|
||||
"version": "0.5.2",
|
||||
"description": "MetonaAI Desktop — 生产级通用 AI Agent 智能体桌面应用",
|
||||
"main": "dist-electron/main/main.js",
|
||||
"author": "Metona Team",
|
||||
|
||||
Reference in New Issue
Block a user