Files
Genarrative/apps/ai-game-creator-shell/tests/errorReporting.test.ts
T
kdletters 8701f43f75 AGC 渲染层网络与状态下沉 Rust,并修复画布交互与失败文案
- 删除渲染层传输层:services/clientApi.ts、clientHttp 的 fetchClientHttp 与超时封装整体退场,账户、认证、素材直传、错误上报与游戏分发发布改走 Rust typed command。
- 新增宿主封装:accountHost、editorAssetHost、platformSessionRetry、agentRuntimeErrorDetail 与 features/app-shell/workspacePreferences;渲染层不再读写 access token / refresh cookie,localStorage 只剩测试态旧键迁移 shim。
- 修复 DirectProject 失败文案 v2 映射与「查看详情」按需读取,画布标签面板高度夹紧、框选每帧重算、文档预览入口与场景标题栏 key、资源筛选面板样式。
- 补齐与调整回归:accountHost、agentRuntimeErrorDetail、clientAuthHost、clientHttp、platformSession、platformSessionRetry、resourceFilterPanelStyle、directThreadChatSubscription 等定向用例,并清理测试 harness 中无调用方的残留。
2026-09-28 14:15:02 +08:00

252 lines
8.1 KiB
TypeScript

/** @vitest-environment jsdom */
import { afterEach, describe, expect, it, vi } from 'vitest';
type FakeErrorEvent = {
eventId: string;
fingerprint: string;
source: string;
message: string;
stack?: string;
occurredAt: string;
count: number;
};
const fakeRustQueue = vi.hoisted(() => {
const events = new Map<string, FakeErrorEvent>();
let sequence = 0;
return {
events,
get sequence() {
return sequence;
},
next() {
sequence += 1;
return sequence;
},
reset() {
events.clear();
sequence = 0;
},
};
});
vi.mock('@tauri-apps/api/core', () => ({
invoke: vi.fn(async (command: string, args?: Record<string, unknown>) => {
if (command === 'report_client_error') {
const fingerprint = `${args?.source ?? 'client'}|${args?.action ?? ''}|${args?.page ?? ''}|${args?.message ?? ''}`;
const existing = fakeRustQueue.events.get(fingerprint);
if (existing) {
existing.count += 1;
return existing;
}
const event = {
eventId: `rust-error-${fakeRustQueue.next()}`,
fingerprint,
source: String(args?.source ?? 'client'),
message: String(args?.message ?? ''),
stack: typeof args?.stack === 'string' ? args.stack : undefined,
occurredAt: '1',
count: 1,
};
if (fakeRustQueue.events.size >= 100) {
const oldest = fakeRustQueue.events.keys().next().value;
if (oldest) fakeRustQueue.events.delete(oldest);
}
fakeRustQueue.events.set(fingerprint, event);
return event;
}
if (command === 'get_pending_error_reports')
return [...fakeRustQueue.events.values()];
if (command === 'ack_error_reports') {
for (const event of fakeRustQueue.events.values()) {
const eventIds = Array.isArray(args?.eventIds) ? args.eventIds : [];
if (eventIds.includes(event.eventId))
fakeRustQueue.events.delete(event.fingerprint);
}
return undefined;
}
return undefined;
}),
}));
import { invoke } from '@tauri-apps/api/core';
import {
ackClientErrorEventsWithRetry,
captureAgentRuntimeError,
captureClientError,
getPendingClientErrorEvents,
installWebviewLogBridge,
markClientErrorEventsSubmitted,
normalizeDiagnosticText,
resetClientErrorEventsForTests,
shouldCaptureClientError,
submitErrorReportBatch,
subscribeClientErrorEvents,
} from '../src/services/errorReporting';
describe('客户端错误报告池', () => {
afterEach(() => {
fakeRustQueue.reset();
resetClientErrorEventsForTests();
vi.clearAllMocks();
});
it('按 fingerprint 合并重复错误并累计次数', async () => {
const first = await captureClientError(new Error('重复错误'), {
source: 'test',
});
const second = await captureClientError(new Error('重复错误'), {
source: 'test',
});
expect(second.eventId).toBe(first.eventId);
expect(await getPendingClientErrorEvents()).toHaveLength(1);
expect((await getPendingClientErrorEvents())[0]?.count).toBe(2);
});
it('使用统一上下文采集 Agent Runtime 错误', async () => {
await captureAgentRuntimeError(
new Error('kind=codex-app-server-other fingerprint=dynamic chars=12'),
'planning-agent-v2',
);
expect(invoke).toHaveBeenCalledWith('report_client_error', {
source: 'agent-runtime',
message: 'kind=codex-app-server-other fingerprint=dynamic chars=12',
stack: expect.any(String),
action: 'agent-runtime',
page: 'planning-agent-v2',
});
});
it('限制当前进程错误池最多保留 100 条', async () => {
for (let index = 0; index < 101; index += 1) {
await captureClientError(new Error(`错误 ${index}`), { source: 'test' });
}
expect(await getPendingClientErrorEvents()).toHaveLength(100);
});
it('提交成功后只清除本次提交的事件', async () => {
const first = await captureClientError(new Error('第一个错误'), {
source: 'test',
});
const second = await captureClientError(new Error('第二个错误'), {
source: 'test',
});
await submitErrorReportBatch({ events: [first], logs: [] });
await markClientErrorEventsSubmitted([first]);
expect(await getPendingClientErrorEvents()).toEqual([second]);
});
it('提交只把脱敏事件交给 Rust,不在渲染层携带凭据或 submissionId', async () => {
const event = await captureClientError(new Error('可重试错误'), {
source: 'test',
});
vi.mocked(invoke).mockImplementationOnce(async (command: string) => {
if (command !== 'submit_error_report') {
throw new Error(`unexpected invoke ${command}`);
}
return { batchId: 'batch-1' };
});
await submitErrorReportBatch({
events: [event],
logs: [{ name: 'application.log', content: 'line' }],
userDescription: ' 说明 ',
});
expect(invoke).toHaveBeenCalledWith('submit_error_report', {
events: [event],
logs: [{ name: 'application.log', content: 'line' }],
userDescription: '说明',
});
const [, args] = vi.mocked(invoke).mock.calls.at(-1) ?? [];
const serialized = JSON.stringify(args);
expect(serialized).not.toContain('token');
expect(serialized).not.toContain('Authorization');
expect(serialized).not.toContain('submissionId');
expect(serialized).not.toContain('http');
});
it('本地 ack 失败时自动重试且不向调用方抛错', async () => {
vi.useFakeTimers();
const event = await captureClientError(new Error('ack 重试错误'), {
source: 'test',
});
vi.mocked(invoke)
.mockRejectedValueOnce(new Error('暂时不可用'))
.mockResolvedValueOnce(undefined);
const pending = ackClientErrorEventsWithRetry([event]);
await vi.advanceTimersByTimeAsync(500);
await pending;
expect(invoke).toHaveBeenCalledWith('ack_error_reports', {
eventIds: [event.eventId],
});
expect(
vi
.mocked(invoke)
.mock.calls.filter(([command]) => command === 'ack_error_reports'),
).toHaveLength(2);
vi.useRealTimers();
});
it('登录态缺失时把 Rust 的稳定分类原样透出,不清除本地事件', async () => {
const event = await captureClientError(new Error('未登录错误'), {
source: 'test',
});
vi.mocked(invoke).mockRejectedValueOnce(
new Error('authentication-required: 请先登录后再提交错误报告'),
);
await expect(
submitErrorReportBatch({ events: [event], logs: [] }),
).rejects.toThrow('请先登录');
expect(await getPendingClientErrorEvents()).toEqual([event]);
});
it('只采集网络错误、408 和 5xx', () => {
expect(shouldCaptureClientError({ status: 400 })).toBe(false);
expect(shouldCaptureClientError({ status: 401 })).toBe(false);
expect(shouldCaptureClientError({ status: 429 })).toBe(false);
expect(shouldCaptureClientError({ status: 408 })).toBe(true);
expect(shouldCaptureClientError({ status: 503 })).toBe(true);
expect(shouldCaptureClientError({ networkError: true })).toBe(true);
});
it('保留 API 路由但隐藏 URL origin 与查询参数', () => {
const sanitized = normalizeDiagnosticText(
'请求超时:https://dev.genarrative.world/api/llm/models?token=secret#fragment',
);
expect(sanitized).toBe('请求超时:<origin>/api/llm/models');
expect(sanitized).not.toContain('genarrative.world');
expect(sanitized).not.toContain('secret');
});
it('将 WebView console 输出写入普通文本日志 command', async () => {
const consoleInfo = vi.spyOn(console, 'info').mockImplementation(() => {});
const uninstall = installWebviewLogBridge();
console.info('hello', { count: 1 });
await Promise.resolve();
expect(invoke).toHaveBeenCalledWith('append_application_log', {
level: 'info',
source: 'webview',
message: 'hello {"count":1}',
});
uninstall();
consoleInfo.mockRestore();
});
it('浏览器预览中订阅错误事件不会产生未处理拒绝', async () => {
delete window.__TAURI__;
const unsubscribe = subscribeClientErrorEvents(vi.fn());
unsubscribe();
await Promise.resolve();
});
});