feat: v0.7.0 四阶段全量迭代 — 修复面收口 · 安全纵深 · 架构还债 · 能力演进
P1 修复面收口: v0.6.3 截断自愈推全量(Anthropic/Ollama/非流式/引擎兜底); SSE 上游错误帧检测进重试通道; clearMessages 摘要游标根治; truncateResult 内联图片白名单统一; 前端四 bug(确认弹窗锁死/MemoryViewer/ Virtuoso Footer/abort 尾部过滤) + reasoning 缓冲跨迭代污染; 托盘通知过滤与新建会话死链接线 P2 安全纵深: MCP 审批闭环(ConfirmationHook×PolicyEngine 联动+重名拒注册); SSRF 收敛 ssrf-guard 共享模块 (web_fetch 双通道校验+重定向终态复检); Electron 加固(preload CJS 化→sandbox:true/CSP/权限白名单/will-navigate); run_command cmd.exe 白名单通道元字符守门; diff_viewer 10MB 预检; Anthropic thinking 预算下限; Agnes 思考显式关闭 P3 架构还债: OpenAICompatibleAdapter 中间基类收敛四家样板; 错误分类单轨化(删 mapError/getFetchSignal, 超时显式 ETIMEDOUT); PRAGMA user_version 迁移版本化; 死代码清理专项(cn.ts/SHORTCUTS/ContextMenu 分支/ getWindowState/modifiedArgs/sandbox 空壳); i18next 引入; a11y 第一轮; SearXNG 页批量草稿模型统一 P4 能力演进: Ollama pull 可取消/capabilities 探测/num_ctx 实测缓存; UpdateService feed 比对式自动更新 (app:updateCheck IPC + StatusBar 入口); MiMo providerOptions(web_search 服务端工具/strict JSON); web_fetch extract_mode=markdown(turndown); network.proxyUrl 全局代理(Chromium sessions+undici dispatcher) 测试: 264 → 507 用例(Electron ABI 全绿零跳过), 覆盖引擎压缩管线/重试竞速/MEMORY.md 闸门/file_editor 五操作/ filesystem 七工具实体夹具/git 真实仓库/SSE 错误帧/全线截断自愈/Provider 请求形态矩阵/SSRF 表测/钩子分级矩阵/ OutputValidator 全量/SLO 指标/MCP 安全纯函数/task_manager 链路/渲染层纯域/i18n 桥契约
This commit is contained in:
@@ -1,12 +1,18 @@
|
||||
/**
|
||||
* BaseAdapter 单元测试(v0.4.1 测试补齐)
|
||||
* 覆盖:错误映射(mapError)、HTTP 错误识别(throwHttpError)、
|
||||
* ContentFilterError、上下文窗口读取、fetchWithTimeout 超时与清理
|
||||
* BaseAdapter 单元测试(v0.6.4 P3-2 错误分类单轨化后重写)
|
||||
*
|
||||
* 契约变更说明:
|
||||
* - mapError 已删除(生产路径死代码,与 engine.isRetryableError 双轨漂移)。
|
||||
* 错误分类的唯一事实来源是 engine.isRetryableError —— 本文件改为验证
|
||||
* "BaseAdapter 抛出的错误携带可判定字段"的形状契约:
|
||||
* throwHttpError → error.status;fetchWithTimeout 超时 → code='ETIMEDOUT'
|
||||
* + 'timed out' message(命中引擎网络超时分支)。
|
||||
* - 新增:错误体长度截断、外部 abort 与自身超时的区分。
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest';
|
||||
import { BaseAdapter, ContentFilterError } from '../base-adapter';
|
||||
import { MetonaErrorCode, MetonaStreamEventType } from '../../types';
|
||||
import { MetonaStreamEventType } from '../../types';
|
||||
import type {
|
||||
IMetonaProviderAdapter,
|
||||
AdapterConfig,
|
||||
@@ -30,11 +36,6 @@ class TestAdapter extends BaseAdapter {
|
||||
// 空实现
|
||||
}
|
||||
|
||||
/** 测试辅助: 暴露 protected mapError */
|
||||
mapErrorPublic(error: unknown) {
|
||||
return this.mapError(error);
|
||||
}
|
||||
|
||||
/** 测试辅助: 暴露 protected throwHttpError */
|
||||
async throwHttpErrorPublic(response: Response, context: string) {
|
||||
return this.throwHttpError(response, context);
|
||||
@@ -56,62 +57,42 @@ function makeAdapter(config: Partial<AdapterConfig> = {}): TestAdapter {
|
||||
});
|
||||
}
|
||||
|
||||
describe('BaseAdapter — mapError 错误映射', () => {
|
||||
it('timeout 消息映射为 NETWORK_TIMEOUT 且可重试', () => {
|
||||
const adapter = makeAdapter();
|
||||
const err = adapter.mapErrorPublic(new Error('Request timeout after 30s'));
|
||||
expect(err.code).toBe(MetonaErrorCode.NETWORK_TIMEOUT);
|
||||
expect(err.retryable).toBe(true);
|
||||
expect(err.provider).toBe('test');
|
||||
});
|
||||
// ===== 错误形状契约(engine.isRetryableError 的输入保证) =====
|
||||
|
||||
it('ECONNREFUSED 映射为 NETWORK_ERROR 且可重试', () => {
|
||||
const adapter = makeAdapter();
|
||||
const err = adapter.mapErrorPublic(new Error('fetch failed: ECONNREFUSED 127.0.0.1:11434'));
|
||||
expect(err.code).toBe(MetonaErrorCode.NETWORK_ERROR);
|
||||
expect(err.retryable).toBe(true);
|
||||
});
|
||||
describe('BaseAdapter — 抛出错误的可判定形状(单轨化契约)', () => {
|
||||
/** 与 engine.isRetryableError 相同的判定逻辑(镜像断言用) */
|
||||
const isRetryableShape = (err: unknown): boolean => {
|
||||
const e = err as { status?: number; code?: string; message?: string };
|
||||
if (e.status === 429) return true;
|
||||
if (e.status && e.status >= 500 && e.status < 600) return true;
|
||||
if (e.code === 'ECONNRESET' || e.code === 'ETIMEDOUT' || e.code === 'ENOTFOUND') return true;
|
||||
const msg = e.message?.toLowerCase() ?? '';
|
||||
if (msg.includes('aborted') || msg.includes('socket hang up')) return true;
|
||||
return false;
|
||||
};
|
||||
|
||||
it('HTTP 401 优先按 status code 映射为 AUTH_INVALID 且不可重试', () => {
|
||||
const adapter = makeAdapter();
|
||||
const e = new Error('API error: 401 Unauthorized');
|
||||
(e as Error & { status: number }).status = 401;
|
||||
const err = adapter.mapErrorPublic(e);
|
||||
expect(err.code).toBe(MetonaErrorCode.AUTH_INVALID);
|
||||
expect(err.retryable).toBe(false);
|
||||
});
|
||||
|
||||
it('HTTP 429 映射为 RATE_LIMITED 且可重试', () => {
|
||||
const adapter = makeAdapter();
|
||||
const e = new Error('429 Too Many Requests');
|
||||
(e as Error & { status: number }).status = 429;
|
||||
const err = adapter.mapErrorPublic(e);
|
||||
expect(err.code).toBe(MetonaErrorCode.RATE_LIMITED);
|
||||
expect(err.retryable).toBe(true);
|
||||
expect(err.retryAfterMs).toBe(5000);
|
||||
});
|
||||
|
||||
it('ContentFilterError 优先映射为 CONTENT_FILTERED', () => {
|
||||
const adapter = makeAdapter();
|
||||
const cf = new ContentFilterError('high risk content', 'MiMo');
|
||||
const err = adapter.mapErrorPublic(cf);
|
||||
expect(err.code).toBe(MetonaErrorCode.CONTENT_FILTERED);
|
||||
expect(err.retryable).toBe(false);
|
||||
});
|
||||
|
||||
it('普通 Error 映射为 UNKNOWN 且不可重试', () => {
|
||||
const adapter = makeAdapter();
|
||||
const err = adapter.mapErrorPublic(new Error('whatever'));
|
||||
expect(err.code).toBe(MetonaErrorCode.UNKNOWN);
|
||||
expect(err.retryable).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('BaseAdapter — throwHttpError', () => {
|
||||
function makeResponse(status: number, body: string): Response {
|
||||
return new Response(body, { status, statusText: 'Status' });
|
||||
}
|
||||
|
||||
it('throwHttpError 携带 status;429/5xx 形状可重试,4xx 不可', async () => {
|
||||
const adapter = makeAdapter();
|
||||
try {
|
||||
await adapter.throwHttpErrorPublic(makeResponse(429, 'rate limited'), 'T');
|
||||
expect.fail('should throw');
|
||||
} catch (e) {
|
||||
expect((e as Error & { status?: number }).status).toBe(429);
|
||||
expect(isRetryableShape(e)).toBe(true);
|
||||
}
|
||||
try {
|
||||
await adapter.throwHttpErrorPublic(makeResponse(401, ''), 'T');
|
||||
expect.fail('should throw');
|
||||
} catch (e) {
|
||||
expect((e as Error & { status?: number }).status).toBe(401);
|
||||
expect(isRetryableShape(e)).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it('content_filter 错误体抛出 ContentFilterError(含 status)', async () => {
|
||||
const adapter = makeAdapter();
|
||||
const body = JSON.stringify({ error: { code: 'content_filter', message: 'high risk' } });
|
||||
@@ -126,16 +107,20 @@ describe('BaseAdapter — throwHttpError', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('普通错误体抛出带 status 属性的 Error(供 isRetryableError 判断)', async () => {
|
||||
it('巨大 HTML 错误体在消息中被截断(v0.6.4)', async () => {
|
||||
const adapter = makeAdapter();
|
||||
await expect(
|
||||
adapter.throwHttpErrorPublic(makeResponse(503, 'Service Unavailable'), 'DeepSeek'),
|
||||
).rejects.toThrow('DeepSeek: 503');
|
||||
const bigHtml = `<html>${'x'.repeat(100_000)}</html>`;
|
||||
let caught: unknown;
|
||||
try {
|
||||
await adapter.throwHttpErrorPublic(makeResponse(503, ''), 'DeepSeek');
|
||||
await adapter.throwHttpErrorPublic(makeResponse(502, bigHtml), 'GW');
|
||||
expect.fail('should throw');
|
||||
} catch (e) {
|
||||
expect((e as Error & { status: number }).status).toBe(503);
|
||||
caught = e;
|
||||
}
|
||||
expect((caught as Error).message.length).toBeLessThan(1_000);
|
||||
expect((caught as Error).message).toContain('[truncated');
|
||||
// 截断不影响 status 判定
|
||||
expect((caught as Error & { status?: number }).status).toBe(502);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -145,7 +130,7 @@ describe('BaseAdapter — getContextWindow', () => {
|
||||
expect(adapter.getContextWindow()).toBe(128_000);
|
||||
});
|
||||
|
||||
it('未配置时返回保守默认值 1M', () => {
|
||||
it('未配置时返回兜底默认值 1M(子类应覆盖真实窗口)', () => {
|
||||
const adapter = makeAdapter();
|
||||
expect(adapter.getContextWindow()).toBe(1_000_000);
|
||||
});
|
||||
@@ -164,10 +149,11 @@ describe('BaseAdapter — listModels / healthCheck', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('BaseAdapter — fetchWithTimeout', () => {
|
||||
describe('BaseAdapter — fetchWithTimeout(P3-2 超时分类单轨化)', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('正常请求返回 Response 并清理 timer', async () => {
|
||||
@@ -181,27 +167,32 @@ describe('BaseAdapter — fetchWithTimeout', () => {
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('超时后 abort 请求(AbortError)', async () => {
|
||||
it('自身超时 → 显式 ETIMEDOUT + timed out 消息(命中引擎网络超时可重试分支)', async () => {
|
||||
const adapter = makeAdapter();
|
||||
vi.useFakeTimers();
|
||||
const fetchMock = vi.fn(
|
||||
(_url: string, init: RequestInit) =>
|
||||
new Promise<Response>((_resolve, reject) => {
|
||||
init.signal?.addEventListener('abort', () =>
|
||||
reject(new DOMException('Aborted', 'AbortError')),
|
||||
reject(new DOMException('This operation was aborted', 'AbortError')),
|
||||
);
|
||||
}),
|
||||
);
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
const promise = adapter.fetchWithTimeoutPublic('https://api.test.com/v1/chat', {}, 100);
|
||||
const expectation = expect(promise).rejects.toThrow('Aborted');
|
||||
const expectation = expect(promise).rejects.toSatisfy((e: Error & { code?: string }) => {
|
||||
expect(e.code).toBe('ETIMEDOUT');
|
||||
expect(e.message).toContain('timed out after 100ms');
|
||||
// 关键:消息不再是裸 "Aborted" —— 引擎按网络超时(而非碰巧可重试)分类
|
||||
return true;
|
||||
});
|
||||
vi.advanceTimersByTime(150);
|
||||
await expectation;
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('外部 abort 信号触发请求中断', async () => {
|
||||
it('外部 abort(用户中断)→ 原样 AbortError,不被改写为超时', async () => {
|
||||
const adapter = makeAdapter();
|
||||
const controller = new AbortController();
|
||||
adapter.setAbortSignal(controller.signal);
|
||||
@@ -210,16 +201,20 @@ describe('BaseAdapter — fetchWithTimeout', () => {
|
||||
(_url: string, init: RequestInit) =>
|
||||
new Promise<Response>((_resolve, reject) => {
|
||||
init.signal?.addEventListener('abort', () =>
|
||||
reject(new DOMException('Aborted', 'AbortError')),
|
||||
reject(new DOMException('This operation was aborted', 'AbortError')),
|
||||
);
|
||||
}),
|
||||
);
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
const promise = adapter.fetchWithTimeoutPublic('https://api.test.com/v1/chat', {}, 30_000);
|
||||
const expectation = expect(promise).rejects.toThrow('Aborted');
|
||||
controller.abort();
|
||||
await expectation;
|
||||
await promise.catch((e: Error & { code?: string }) => {
|
||||
expect(e.name).toBe('AbortError');
|
||||
// 未被转译为字符串型 ETIMEDOUT(注意 Node DOMException 自带数字 code=20)
|
||||
expect(e.code).not.toBe('ETIMEDOUT');
|
||||
expect(e.message).not.toContain('timed out after');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user