feat: 支持 Agent 运行刷新恢复

- 解耦 Runtime 与浏览器 SSE 订阅并增加 Redis 游标日志

- 支持正式聊天与草稿试运行刷新重连和权威终态恢复

- 完善显式取消、owner 丢失、容量限制与故障测试
This commit is contained in:
2026-08-20 11:18:10 +08:00
parent 310fc1fb58
commit fa07134cf8
36 changed files with 4876 additions and 322 deletions

View File

@@ -1,7 +1,8 @@
import { EventType } from '@ag-ui/client';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { EasyFlowAguiClient } from './client';
import { EasyFlowAguiClient, EasyFlowAguiProjectionError } from './client';
import { isRetryableAguiTransportError } from './reconnect';
vi.mock('#/api/request', () => ({
createEventStreamHeaders: () => ({ 'easyflow-token': 'test-token' }),
@@ -10,7 +11,12 @@ vi.mock('#/api/request', () => ({
function sse(events: unknown[]) {
return new Response(
events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join(''),
events
.map(
(event, index) =>
`id: ${index + 1}\ndata: ${JSON.stringify(event)}\n\n`,
)
.join(''),
{ headers: { 'Content-Type': 'text/event-stream' }, status: 200 },
);
}
@@ -36,15 +42,22 @@ describe('easyFlowAguiClient', () => {
vi.stubGlobal('fetch', fetchMock);
const received: string[] = [];
const cursors: number[] = [];
await new EasyFlowAguiClient().run({
forwardedProps: { easyflow: { input: { imageUploadIds: ['image-1'] } } },
onEvent: (event) => received.push(event.type),
onEvent: (event) => {
received.push(event.type);
},
onCursor: (cursor) => {
cursors.push(cursor);
},
threadId: '101',
url: '/api/v1/agent/1/agui/run',
userMessage: { content: '你好', id: 'user-1', role: 'user' },
});
expect(received).toEqual([EventType.RUN_STARTED, EventType.RUN_FINISHED]);
expect(cursors).toEqual([1, 2]);
expect(requestBody).toEqual(
expect.objectContaining({
context: [],
@@ -106,6 +119,32 @@ describe('easyFlowAguiClient', () => {
).rejects.toThrow('缺少终态');
});
it('marks deterministic event projection failures as non-retryable', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async () =>
sse([{ runId: 'run-1', threadId: '101', type: EventType.RUN_STARTED }]),
),
);
const run = new EasyFlowAguiClient().run({
onEvent: () => {
throw new Error('projection failed');
},
threadId: '101',
url: '/api/v1/agent/1/agui/run',
userMessage: { content: '你好', id: 'user-1', role: 'user' },
});
await expect(run).rejects.toBeInstanceOf(EasyFlowAguiProjectionError);
expect(
isRetryableAguiTransportError(
new EasyFlowAguiProjectionError(new Error('projection failed')),
Date.now(),
),
).toBe(false);
});
it('treats a standard cancelled terminal as an accepted stop', async () => {
vi.stubGlobal(
'fetch',
@@ -132,4 +171,132 @@ describe('easyFlowAguiClient', () => {
}),
).resolves.toBeUndefined();
});
it('does not hide projection errors raised by a cancelled terminal', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async () =>
sse([
{
code: 'RUN_CANCELLED',
message: '用户停止',
runId: 'run-1',
threadId: '101',
type: EventType.RUN_ERROR,
},
]),
),
);
await expect(
new EasyFlowAguiClient().run({
onEvent: () => {
throw new Error('cancel projection failed');
},
threadId: '101',
url: '/api/v1/agent/1/agui/run',
userMessage: { content: '你好', id: 'user-1', role: 'user' },
}),
).rejects.toBeInstanceOf(EasyFlowAguiProjectionError);
});
it('replays a completed run from the server journal after refresh', async () => {
vi.stubGlobal(
'fetch',
vi.fn(
async () =>
new Response(
[
'id: 1\ndata: {"type":"RUN_STARTED","threadId":"101","runId":"run-resume"}\n\n',
'id: 2\ndata: {"type":"TEXT_MESSAGE_START","messageId":"assistant-1","role":"assistant"}\n\n',
'id: 3\ndata: {"type":"TEXT_MESSAGE_CONTENT","messageId":"assistant-1","delta":"刷新后恢复"}\n\n',
'id: 4\ndata: {"type":"TEXT_MESSAGE_END","messageId":"assistant-1"}\n\n',
'id: 5\ndata: {"type":"RUN_FINISHED","threadId":"101","runId":"run-resume"}\n\n',
].join(''),
{ headers: { 'Content-Type': 'text/event-stream' }, status: 200 },
),
),
);
const received: string[] = [];
const cursors: number[] = [];
await new EasyFlowAguiClient().resume({
onCursor: (cursor) => {
cursors.push(cursor);
},
onEvent: (event) => {
received.push(event.type);
},
runId: 'run-resume',
});
expect(received).toEqual([
EventType.RUN_STARTED,
EventType.TEXT_MESSAGE_START,
EventType.TEXT_MESSAGE_CONTENT,
EventType.TEXT_MESSAGE_END,
EventType.RUN_FINISHED,
]);
expect(cursors).toEqual([1, 2, 3, 4, 5]);
expect(fetch).toHaveBeenCalledWith(
expect.stringContaining('/run-resume/events?after=0'),
expect.objectContaining({ method: 'GET' }),
);
});
it('uses the explicit cancel endpoint instead of treating detach as cancel', async () => {
const fetchMock = vi.fn(
async () =>
new Response(JSON.stringify({ errorCode: 0 }), {
headers: { 'Content-Type': 'application/json' },
status: 200,
}),
);
vi.stubGlobal('fetch', fetchMock);
await new EasyFlowAguiClient().cancel('run-cancel');
expect(fetchMock).toHaveBeenCalledWith(
expect.stringContaining('/run-cancel/cancel'),
expect.objectContaining({ method: 'POST' }),
);
});
it('keeps the active stream attached when the cancel request fails', async () => {
let runSignal: AbortSignal | undefined;
const fetchMock = vi.fn((url: string, init?: RequestInit) => {
if (url.includes('/cancel')) {
return Promise.resolve(
new Response(JSON.stringify({ message: '取消服务暂不可用' }), {
headers: { 'Content-Type': 'application/json' },
status: 503,
}),
);
}
runSignal = init?.signal as AbortSignal;
return new Promise<Response>((_resolve, reject) => {
runSignal?.addEventListener('abort', () =>
reject(new DOMException('Aborted', 'AbortError')),
);
});
});
vi.stubGlobal('fetch', fetchMock);
const client = new EasyFlowAguiClient();
const runPromise = client.run({
onEvent: () => undefined,
runId: 'run-cancel-failure',
threadId: '101',
url: '/api/v1/agent/1/agui/run',
userMessage: { content: '你好', id: 'user-1', role: 'user' },
});
await expect(client.cancel('run-cancel-failure')).rejects.toThrow(
'取消服务暂不可用',
);
expect(runSignal?.aborted).toBe(false);
client.detach();
expect(runSignal?.aborted).toBe(true);
await runPromise;
});
});