Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ”₯ chore(agent): remove the unused /api/agent/stream SSE endpoint (#22601)

Arvin Xue2c8eb56cad9
diff --git a/.agents/acceptance/scripts/agent-gateway/probe-events.ts b/.agents/acceptance/scripts/agent-gateway/probe-events.ts
index dd24a1f16a5..9074c1cdd57 100644
--- a/.agents/acceptance/scripts/agent-gateway/probe-events.ts
+++ b/.agents/acceptance/scripts/agent-gateway/probe-events.ts
@@ -1,7 +1,6 @@
// LobeHub gateway raw-event-stream probe.
//
-// Gateway-mode chats subscribe via WebSocket β€” NOT via the `/api/agent/stream`
-// SSE endpoint (that one belongs to the direct/client durable-agent runtime).
+// Gateway-mode chats subscribe via WebSocket.
// `AgentStreamClient` (`packages/agent-gateway-client/src/client.ts`) opens
// `new WebSocket('wss://.../ws?operationId=...')`, then parses JSON frames in
// its `onmessage` handler and re-emits `agent_event.event` objects to the
@@ -12,10 +11,6 @@
// we intercept the `onmessage` handler / `addEventListener('message')` and
// log every `agent_event` frame.
//
-// We *also* keep the `window.fetch` hook for `/api/agent/stream` so this
-// probe still works for direct-mode runs β€” but gateway-mode events come
-// through the WebSocket path.
-//
// Buffers (read via `dump`):
// __PROBE_STREAM_EVENTS β€” raw events parsed off the wire
// __PROBE_ACTION_CALLS β€” replaceMessages / refreshMessages calls (best-effort)
@@ -125,7 +120,7 @@ function shortStack(): string {
}
function recordAgentEvent(args: {
- transport: 'ws' | 'sse';
+ transport: 'ws';
opId: string | null;
agentEvent: any;
eventId?: string | null;
@@ -250,117 +245,7 @@ for (const k of Object.keys(OrigWS) as Array<keyof typeof OrigWS>) {
});
w.WebSocket = PatchedWebSocket as unknown as typeof WebSocket;
-// ── 2. Patch window.fetch for `/api/agent/stream` (direct-mode SSE) ─
-
-if (!w.__PROBE_ORIG_FETCH) w.__PROBE_ORIG_FETCH = w.fetch.bind(w);
-const origFetch = w.__PROBE_ORIG_FETCH;
-
-function isAgentStreamUrl(input: RequestInfo | URL): boolean {
- let url = '';
- if (typeof input === 'string') url = input;
- else if (input instanceof URL) url = input.toString();
- else if (input && typeof (input as Request).url === 'string') url = (input as Request).url;
- return url.includes('/api/agent/stream');
-}
-
-function extractOpIdFromHttpUrl(input: RequestInfo | URL): string | null {
- const url = typeof input === 'string' ? input : (input as Request | URL).toString();
- const m = url.match(/operationId=([^&]+)/);
- return m ? decodeURIComponent(m[1]) : null;
-}
-
-function pushFromSSEFrame(rawFrame: string, opId: string | null): void {
- const lines = rawFrame.split('\n');
- let dataJson = '';
- let evtName = 'message';
- for (const line of lines) {
- if (line.startsWith('event:')) evtName = line.slice(6).trim();
- else if (line.startsWith('data:')) dataJson += line.slice(5).trim();
- }
- if (!dataJson) return;
- let parsed: any;
- try {
- parsed = JSON.parse(dataJson);
- } catch {
- events.push({
- t: now(),
- transport: 'sse',
- opIdTail: (opId ?? '').slice(-10),
- type: '_PARSE_ERROR_',
- sseEvent: evtName,
- raw: dataJson.length > 400 ? dataJson.slice(0, 400) + '…' : dataJson,
- });
- return;
- }
- recordAgentEvent({
- transport: 'sse',
- opId,
- agentEvent: parsed,
- eventId: null,
- rawLen: dataJson.length,
- });
-}
-
-async function teeAndDrain(response: Response, opId: string | null): Promise<Response> {
- if (!response.body) return response;
- const [a, b] = response.body.tee();
-
- void (async () => {
- const reader = b.getReader();
- const decoder = new TextDecoder();
- let buf = '';
- try {
- while (true) {
- const { value, done } = await reader.read();
- if (done) break;
- buf += decoder.decode(value, { stream: true });
- let idx: number;
-
- while ((idx = buf.indexOf('\n\n')) !== -1) {
- const frame = buf.slice(0, idx);
- buf = buf.slice(idx + 2);
- if (frame.trim()) pushFromSSEFrame(frame, opId);
- }
- }
- if (buf.trim()) pushFromSSEFrame(buf, opId);
- } catch (e: any) {
- events.push({
- t: now(),
- transport: 'sse',
- opIdTail: (opId ?? '').slice(-10),
- type: '_TEE_ERROR_',
- message: String(e?.message ?? e),
- });
- }
- })();
-
- return new Response(a, {
- headers: response.headers,
- status: response.status,
- statusText: response.statusText,
- });
-}
-
-w.fetch = async function patchedFetch(input: RequestInfo | URL, init?: RequestInit) {
- const response = await origFetch(input as any, init);
- if (!isAgentStreamUrl(input)) return response;
- const opId = extractOpIdFromHttpUrl(input);
- const url =
- typeof input === 'string'
- ? input.split('?')[0]
- : (input as Request | URL).toString().split('?')[0];
- events.push({
- t: now(),
- transport: 'sse',
- opIdTail: (opId ?? '').slice(-10),
- type: '_CONNECTED_',
- url,
- status: response.status,
- });
- return teeAndDrain(response, opId);
-} as typeof fetch;
-
-// ── 3. Wrap store actions (best-effort for "who called replace") ────
+// ── 2. Wrap store actions (best-effort for "who called replace") ────
// Side-global stash for the original chat-store actions. Re-installs ALWAYS
// rewrap from the originals so updates to the probe body take effect
@@ -444,7 +329,7 @@ try {
calls.push({ t: now(), name: '_WRAP_ERROR_', error: String(e?.message ?? e) });
}
-// ── 3.5. Mutation log β€” wrap the TWO ChatStore writers (replaceMessages,
+// ── 2.5. Mutation log β€” wrap the TWO ChatStore writers (replaceMessages,
// internal_dispatchMessage) to record EVERY dbMessagesMap[key] reference
// change with a one-line "before/after last assistant message" delta. This
// reveals dispatchMessage-driven collapses that the replaceMessages wrap
@@ -560,7 +445,7 @@ try {
calls.push({ t: now(), name: '_DISPATCH_WRAP_ERROR_', error: String(e?.message ?? e) });
}
-// ── 4. Periodic per-key timeline snapshots ─────────────────────────
+// ── 3. Periodic per-key timeline snapshots ─────────────────────────
function captureTimeline(): void {
try {
@@ -602,7 +487,7 @@ captureTimeline();
if (w.__PROBE_TIMELINE_TIMER) clearInterval(w.__PROBE_TIMELINE_TIMER);
w.__PROBE_TIMELINE_TIMER = setInterval(captureTimeline, 200);
-// ── 5. Tab-switch helpers ──────────────────────────────────────────
+// ── 4. Tab-switch helpers ──────────────────────────────────────────
function listTopBarTabs(): HTMLElement[] {
return Array.from(
diff --git a/.agents/acceptance/scripts/agent-gateway/run.ts b/.agents/acceptance/scripts/agent-gateway/run.ts
index 5c4a7905380..764715b242b 100644
--- a/.agents/acceptance/scripts/agent-gateway/run.ts
+++ b/.agents/acceptance/scripts/agent-gateway/run.ts
@@ -133,8 +133,7 @@ function latestDump(): string | null {
async function cmdInstall(flags: Flags): Promise<void> {
const body = await bundle('probe-events.ts');
const installMsg = JSON.stringify(
- 'events probe installed: WebSocket+fetch interception. ' +
- 'WS captures operationId= sockets (gateway), fetch captures /api/agent/stream (direct).',
+ 'events probe installed: WebSocket interception. Captures operationId= sockets (gateway).',
);
const script = wrapIife(body, installMsg);
const out = await runAgentBrowserEval(flags, script);
diff --git a/.agents/acceptance/scripts/agent-gateway/types.ts b/.agents/acceptance/scripts/agent-gateway/types.ts
index e748c0c495c..4b7c1d00633 100644
--- a/.agents/acceptance/scripts/agent-gateway/types.ts
+++ b/.agents/acceptance/scripts/agent-gateway/types.ts
@@ -8,7 +8,6 @@ export interface ProbeStreamEvent {
dataKeys?: string[];
/** ServerMessage.id β€” gateway WS frames carry an event-id we may resume from */
eventId?: string | null;
- message?: string;
/** Last 10 chars of the operationId (full id is excessively long) */
opIdTail: string;
raw?: string;
@@ -16,13 +15,11 @@ export interface ProbeStreamEvent {
rawLen?: number;
/** For non-agent_event server frames (auth_success, heartbeat_ack, …) */
serverType?: string;
- sseEvent?: string;
- status?: number;
stepIndex?: number;
/** Milliseconds since the probe's t0 (install time). */
t: number;
- /** 'ws' for gateway WebSocket frames, 'sse' for direct /api/agent/stream */
- transport: 'ws' | 'sse';
+ /** Gateway WebSocket frames are the only captured transport */
+ transport: 'ws';
/** Either the AgentStreamEvent.type, or a probe sentinel like `_WS_OPEN_` */
type: string;
url?: string;
@@ -104,7 +101,6 @@ declare global {
__PROBE_ACTION_CALLS?: ProbeActionCall[];
__PROBE_EVENT?: (label: string) => void;
__PROBE_MSG_TIMELINE?: ProbeTimelineSample[];
- __PROBE_ORIG_FETCH?: typeof fetch;
__PROBE_ORIG_WEBSOCKET?: typeof WebSocket;
__PROBE_STREAM_EVENTS?: ProbeStreamEvent[];
__PROBE_T0?: number;
diff --git a/src/app/(backend)/api/agent/stream/__tests__/route.test.ts b/src/app/(backend)/api/agent/stream/__tests__/route.test.ts
deleted file mode 100644
index 99b8b37a953..00000000000
--- a/src/app/(backend)/api/agent/stream/__tests__/route.test.ts
+++ /dev/null
@@ -1,965 +0,0 @@
-// @vitest-environment node
-import { NextRequest } from 'next/server';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { GET } from '../route';
-
-// Mock dependencies first
-const mockStreamEventManager = {
- getStreamHistory: vi.fn(),
- subscribeStreamEvents: vi.fn(),
-};
-
-const mockAgentStateManager = {
- getOperationMetadata: vi.fn(),
-};
-
-const mockCreateLambdaContext = vi.fn();
-
-vi.mock('@/server/modules/AgentRuntime', () => ({
- createAgentStateManager: vi.fn(() => mockAgentStateManager),
- createStreamEventManager: vi.fn(() => mockStreamEventManager),
-}));
-
-vi.mock('@/libs/trpc/lambda/context', () => ({
- createLambdaContext: (...args: unknown[]) => mockCreateLambdaContext(...args),
-}));
-
-const OWNER_USER_ID = 'test-user';
-
-describe('/api/agent/stream route', () => {
- const MOCK_TIMESTAMP = 1758203237000;
-
- beforeEach(() => {
- vi.resetAllMocks();
- // Mock Date.now to return consistent timestamp
- vi.spyOn(Date, 'now').mockReturnValue(MOCK_TIMESTAMP);
-
- // Default: authenticated as the operation owner, non-share operation.
- // Individual tests override these to exercise the 401/404 paths.
- mockCreateLambdaContext.mockResolvedValue({ userId: OWNER_USER_ID });
- mockAgentStateManager.getOperationMetadata.mockResolvedValue({ userId: OWNER_USER_ID });
- });
-
- afterEach(() => {
- vi.clearAllMocks();
- });
-
- describe('GET handler', () => {
- it('should return 400 when operationId parameter is missing', async () => {
- const request = new NextRequest('https://test.com/api/agent/stream');
- const response = await GET(request);
-
- expect(response.status).toBe(400);
- const data = await response.json();
- expect(data.error).toBe('operationId parameter is required');
- });
-
- it('should return SSE stream with correct headers when operationId is provided', async () => {
- const request = new NextRequest(
- 'https://test.com/api/agent/stream?operationId=test-operation',
- );
- const response = await GET(request);
-
- expect(response.status).toBe(200);
- expect(response.headers.get('Content-Type')).toBe('text/event-stream');
- expect(response.headers.get('Cache-Control')).toBe('no-cache, no-transform');
- expect(response.headers.get('Connection')).toBe('keep-alive');
- expect(response.headers.get('Access-Control-Allow-Origin')).toBe('*');
- expect(response.headers.get('Access-Control-Allow-Methods')).toBe('GET');
- expect(response.headers.get('Access-Control-Allow-Headers')).toBe(
- 'Cache-Control, Last-Event-ID',
- );
- expect(response.headers.get('X-Accel-Buffering')).toBe('no');
- });
- });
-
- describe('Authorization', () => {
- it('should return 401 when the caller is not authenticated', async () => {
- mockCreateLambdaContext.mockResolvedValue({ userId: null });
-
- const request = new NextRequest(
- 'https://test.com/api/agent/stream?operationId=test-operation',
- );
- const response = await GET(request);
-
- expect(response.status).toBe(401);
- const data = await response.json();
- expect(data.error).toBe('unauthorized');
- expect(mockAgentStateManager.getOperationMetadata).not.toHaveBeenCalled();
- expect(mockStreamEventManager.getStreamHistory).not.toHaveBeenCalled();
- });
-
- it('should return 404 when the operation does not exist', async () => {
- mockAgentStateManager.getOperationMetadata.mockResolvedValue(null);
-
- const request = new NextRequest(
- 'https://test.com/api/agent/stream?operationId=unknown-operation',
- );
- const response = await GET(request);
-
- expect(response.status).toBe(404);
- const data = await response.json();
- expect(data.error).toBe('operation_not_found');
- expect(mockStreamEventManager.getStreamHistory).not.toHaveBeenCalled();
- });
-
- it('should return 404 when the operation belongs to another user', async () => {
- mockCreateLambdaContext.mockResolvedValue({ userId: 'other-user' });
- mockAgentStateManager.getOperationMetadata.mockResolvedValue({ userId: OWNER_USER_ID });
-
- const request = new NextRequest(
- 'https://test.com/api/agent/stream?operationId=test-operation',
- );
- const response = await GET(request);
-
- expect(response.status).toBe(404);
- const data = await response.json();
- expect(data.error).toBe('operation_not_found');
- expect(mockStreamEventManager.getStreamHistory).not.toHaveBeenCalled();
- });
-
- it('should return 404 for a share-visitor operation even when the caller is the visitor', async () => {
- mockCreateLambdaContext.mockResolvedValue({ userId: 'visitor-user' });
- mockAgentStateManager.getOperationMetadata.mockResolvedValue({
- streamOwnerUserId: 'visitor-user',
- userId: OWNER_USER_ID,
- });
-
- const request = new NextRequest(
- 'https://test.com/api/agent/stream?operationId=share-visitor-operation',
- );
- const response = await GET(request);
-
- expect(response.status).toBe(404);
- const data = await response.json();
- expect(data.error).toBe('operation_not_found');
- expect(mockStreamEventManager.getStreamHistory).not.toHaveBeenCalled();
- });
-
- it('should return 404 for a share-visitor operation even when the caller is the creator', async () => {
- mockCreateLambdaContext.mockResolvedValue({ userId: OWNER_USER_ID });
- mockAgentStateManager.getOperationMetadata.mockResolvedValue({
- streamOwnerUserId: 'visitor-user',
- userId: OWNER_USER_ID,
- });
-
- const request = new NextRequest(
- 'https://test.com/api/agent/stream?operationId=share-visitor-operation',
- );
- const response = await GET(request);
-
- expect(response.status).toBe(404);
- const data = await response.json();
- expect(data.error).toBe('operation_not_found');
- expect(mockStreamEventManager.getStreamHistory).not.toHaveBeenCalled();
- });
-
- it('should allow the owner to read their own operation', async () => {
- const request = new NextRequest(
- 'https://test.com/api/agent/stream?operationId=test-operation',
- );
- const response = await GET(request);
-
- expect(response.status).toBe(200);
- expect(mockAgentStateManager.getOperationMetadata).toHaveBeenCalledWith('test-operation');
- });
- });
-
- describe('Stream functionality with exact data verification', () => {
- it('should send connection event in exact SSE format', async () => {
- const request = new NextRequest(
- 'https://test.com/api/agent/stream?operationId=test-operation&lastEventId=123',
- );
-
- const response = await GET(request);
- const decoder = new TextDecoder();
- const reader = response.body!.getReader();
-
- // Collect all chunks
- const chunks = [];
- let readCount = 0;
- const maxReads = 1; // Only read connection event
-
- try {
- while (readCount < maxReads) {
- const readPromise = reader.read();
- const timeoutPromise = new Promise((_, reject) =>
- setTimeout(() => reject(new Error('Read timeout')), 1000),
- );
-
- const result = (await Promise.race([
- readPromise,
- timeoutPromise,
- ])) as ReadableStreamReadResult<Uint8Array>;
-
- if (result.done) break;
- if (result.value) {
- const chunk =
- result.value instanceof Uint8Array
- ? decoder.decode(result.value)
- : String(result.value);
- chunks.push(chunk);
- readCount++;
- }
- }
- } catch {
- // Timeout or error
- } finally {
- reader.releaseLock();
- }
-
- // Verify exact stream format with mocked timestamp (new SSE format)
- expect(chunks).toEqual([
- `id: conn_${MOCK_TIMESTAMP}\nevent: connected\ndata: {"lastEventId":"123","operationId":"test-operation","timestamp":${MOCK_TIMESTAMP},"type":"connected"}\n\n`,
- ]);
- });
-
- it('should verify getStreamHistory with exact historical events format', async () => {
- const request = new NextRequest(
- 'https://test.com/api/agent/stream?operationId=test-operation&includeHistory=true&lastEventId=100',
- );
-
- // Mock getStreamHistory to return specific events
- const mockEvents = [
- {
- type: 'stream_end',
- timestamp: 300,
- operationId: 'test-operation',
- data: { messageId: 'msg3' },
- },
- {
- type: 'stream_chunk',
- timestamp: 250,
- operationId: 'test-operation',
- data: { content: 'world' },
- },
- {
- type: 'stream_start',
- timestamp: 150,
- operationId: 'test-operation',
- data: { messageId: 'msg1' },
- },
- ];
- mockStreamEventManager.getStreamHistory.mockResolvedValue(mockEvents);
-
- const response = await GET(request);
- const decoder = new TextDecoder();
- const reader = response.body!.getReader();
-
- // Collect all chunks
- const chunks = [];
- let readCount = 0;
- const maxReads = 3; // connection + 2 filtered historical events (timestamp > 100)
-
- try {
- while (readCount < maxReads) {
- const readPromise = reader.read();
- const timeoutPromise = new Promise((_, reject) =>
- setTimeout(() => reject(new Error('Read timeout')), 500),
- );
-
- const result = (await Promise.race([
- readPromise,
- timeoutPromise,
- ])) as ReadableStreamReadResult<Uint8Array>;
-
- if (result.done) break;
- if (result.value) {
- const chunk =
- result.value instanceof Uint8Array
- ? decoder.decode(result.value)
- : String(result.value);
- chunks.push(chunk);
- readCount++;
- }
- }
- } catch {
- // Timeout or error
- } finally {
- reader.releaseLock();
- }
-
- // Verify exact stream format - connection event + filtered historical events (new SSE format)
- expect(chunks).toEqual([
- `id: conn_${MOCK_TIMESTAMP}\nevent: connected\ndata: {"lastEventId":"100","operationId":"test-operation","timestamp":${MOCK_TIMESTAMP},"type":"connected"}\n\n`,
- `id: test-operation\nevent: stream_start\ndata: {"type":"stream_start","timestamp":150,"operationId":"test-operation","data":{"messageId":"msg1"}}\n\n`,
- `id: test-operation\nevent: stream_chunk\ndata: {"type":"stream_chunk","timestamp":250,"operationId":"test-operation","data":{"content":"world"}}\n\n`,
- ]);
-
- // Verify API calls
- expect(mockStreamEventManager.getStreamHistory).toHaveBeenCalledWith('test-operation', 50);
- });
-
- it('should verify event filtering with exact format', async () => {
- const request = new NextRequest(
- 'https://test.com/api/agent/stream?operationId=test-operation&includeHistory=true&lastEventId=200',
- );
-
- // Mock events where some should be filtered out
- const mockEvents = [
- {
- type: 'stream_end',
- timestamp: 300,
- operationId: 'test-operation',
- data: { messageId: 'msg3' },
- }, // Should be included (300 > 200)
- {
- type: 'stream_chunk',
- timestamp: 250,
- operationId: 'test-operation',
- data: { content: 'world' },
- }, // Should be included (250 > 200)
- {
- type: 'stream_chunk',
- timestamp: 200,
- operationId: 'test-operation',
- data: { content: 'hello' },
- }, // Should be excluded (200 = 200)
- {
- type: 'stream_start',
- timestamp: 150,
- operationId: 'test-operation',
- data: { messageId: 'msg1' },
- }, // Should be excluded (150 < 200)
- ];
- mockStreamEventManager.getStreamHistory.mockResolvedValue(mockEvents);
-
- const response = await GET(request);
- const decoder = new TextDecoder();
- const reader = response.body!.getReader();
-
- // Collect all chunks
- const chunks = [];
- let readCount = 0;
- const maxReads = 3; // connection + 2 filtered events
-
- try {
- while (readCount < maxReads) {
- const readPromise = reader.read();
- const timeoutPromise = new Promise((_, reject) =>
- setTimeout(() => reject(new Error('Read timeout')), 500),
- );
-
- const result = (await Promise.race([
- readPromise,
- timeoutPromise,
- ])) as ReadableStreamReadResult<Uint8Array>;
-
- if (result.done) break;
- if (result.value) {
- const chunk =
- result.value instanceof Uint8Array
- ? decoder.decode(result.value)
- : String(result.value);
- chunks.push(chunk);
- readCount++;
- }
- }
- } catch {
- // Timeout or error
- } finally {
- reader.releaseLock();
- }
-
- // Verify exact stream format - only events with timestamp > 200 are included (new SSE format)
- // Note: indices are based on original array position, not filtered position
- expect(chunks).toEqual([
- `id: conn_${MOCK_TIMESTAMP}
-event: connected
-data: {"lastEventId":"200","operationId":"test-operation","timestamp":${MOCK_TIMESTAMP},"type":"connected"}
-
-`,
- `id: test-operation
-event: stream_chunk
-data: {"type":"stream_chunk","timestamp":250,"operationId":"test-operation","data":{"content":"world"}}
-
-`,
- `id: test-operation
-event: stream_end
-data: {"type":"stream_end","timestamp":300,"operationId":"test-operation","data":{"messageId":"msg3"}}
-\n`,
- ]);
-
- // Verify API calls
- expect(mockStreamEventManager.getStreamHistory).toHaveBeenCalledWith('test-operation', 50);
- });
-
- it('should handle errors with exact error event format', async () => {
- const request = new NextRequest(
- 'https://test.com/api/agent/stream?operationId=test-operation&includeHistory=true',
- );
-
- // Mock getStreamHistory to reject
- mockStreamEventManager.getStreamHistory.mockRejectedValue(
- new Error('Redis connection failed'),
- );
-
- const response = await GET(request);
- const decoder = new TextDecoder();
- const reader = response.body!.getReader();
-
- // Collect all chunks
- const chunks = [];
- let readCount = 0;
- const maxReads = 2; // connection + error event
-
- try {
- while (readCount < maxReads) {
- const readPromise = reader.read();
- const timeoutPromise = new Promise((_, reject) =>
- setTimeout(() => reject(new Error('Read timeout')), 500),
- );
-
- const result = (await Promise.race([
- readPromise,
- timeoutPromise,
- ])) as ReadableStreamReadResult<Uint8Array>;
-
- if (result.done) break;
- if (result.value) {
- const chunk =
- result.value instanceof Uint8Array
- ? decoder.decode(result.value)
- : String(result.value);
- chunks.push(chunk);
- readCount++;
- }
- }
- } catch {
- // Timeout or error
- } finally {
- reader.releaseLock();
- }
-
- // Verify exact stream format - connection event + error event (new SSE format)
- // Parse error event to check format (error includes stack trace dynamically)
- const errorChunk = chunks[1];
- expect(errorChunk).toMatch(/^id: error_\d+\nevent: error\ndata: \{.*"type":"error".*\}\n\n$/);
- expect(errorChunk).toContain('"error":"Redis connection failed"');
- expect(errorChunk).toContain('"phase":"history_loading"');
- expect(errorChunk).toContain('"operationId":"test-operation"');
- expect(errorChunk).toContain(`"timestamp":${MOCK_TIMESTAMP}`);
-
- // Verify connection event format
- expect(chunks[0]).toEqual(
- `id: conn_${MOCK_TIMESTAMP}\nevent: connected\ndata: {"lastEventId":"0","operationId":"test-operation","timestamp":${MOCK_TIMESTAMP},"type":"connected"}\n\n`,
- );
-
- // Verify getStreamHistory was called
- expect(mockStreamEventManager.getStreamHistory).toHaveBeenCalledWith('test-operation', 50);
- });
-
- it('should verify stream subscription with exact parameters', async () => {
- const request = new NextRequest(
- 'https://test.com/api/agent/stream?operationId=test-operation&lastEventId=456',
- );
-
- mockStreamEventManager.subscribeStreamEvents.mockResolvedValue(undefined);
-
- const response = await GET(request);
-
- expect(response.status).toBe(200);
-
- // Verify exact parameter passing
- expect(mockStreamEventManager.subscribeStreamEvents).toHaveBeenCalledWith(
- 'test-operation',
- '456',
- expect.any(Function), // callback function
- expect.any(AbortSignal), // abort signal
- );
-
- // Verify the callback function structure
- const callArgs = mockStreamEventManager.subscribeStreamEvents.mock.calls[0];
- expect(callArgs).toHaveLength(4);
- expect(typeof callArgs[2]).toBe('function'); // callback
- expect(callArgs[3]).toBeInstanceOf(AbortSignal); // signal
- });
-
- it('should verify default parameters with exact values', async () => {
- const request = new NextRequest(
- 'https://test.com/api/agent/stream?operationId=test-operation',
- );
-
- mockStreamEventManager.subscribeStreamEvents.mockResolvedValue(undefined);
-
- const response = await GET(request);
-
- expect(response.status).toBe(200);
-
- // Verify default values are used
- expect(mockStreamEventManager.subscribeStreamEvents).toHaveBeenCalledWith(
- 'test-operation',
- '0', // default lastEventId
- expect.any(Function),
- expect.any(AbortSignal),
- );
-
- // Verify getStreamHistory is NOT called when includeHistory defaults to false
- expect(mockStreamEventManager.getStreamHistory).not.toHaveBeenCalled();
- });
-
- it('should verify SSE message structure with exact format specification', async () => {
- const request = new NextRequest(
- 'https://test.com/api/agent/stream?operationId=test-operation',
- );
-
- const response = await GET(request);
- const decoder = new TextDecoder();
- const reader = response.body!.getReader();
-
- // Collect all chunks
- const chunks = [];
- let readCount = 0;
- const maxReads = 1; // Only read connection event
-
- try {
- while (readCount < maxReads) {
- const readPromise = reader.read();
- const timeoutPromise = new Promise((_, reject) =>
- setTimeout(() => reject(new Error('Read timeout')), 1000),
- );
-
- const result = (await Promise.race([
- readPromise,
- timeoutPromise,
- ])) as ReadableStreamReadResult<Uint8Array>;
-
- if (result.done) break;
- if (result.value) {
- const chunk =
- result.value instanceof Uint8Array
- ? decoder.decode(result.value)
- : String(result.value);
- chunks.push(chunk);
- readCount++;
- }
- }
- } catch {
- // Timeout or error
- } finally {
- reader.releaseLock();
- }
-
- // Verify exact stream format with default lastEventId (new SSE format)
- expect(chunks).toEqual([
- `id: conn_${MOCK_TIMESTAMP}\nevent: connected\ndata: {"lastEventId":"0","operationId":"test-operation","timestamp":${MOCK_TIMESTAMP},"type":"connected"}\n\n`,
- ]);
- });
- });
-
- describe('Agent Runtime Lifecycle', () => {
- it('should verify agent runtime event handling and connection closure logic', async () => {
- const request = new NextRequest(
- 'https://test.com/api/agent/stream?operationId=test-operation',
- );
-
- // Capture the event callback so we can test the event processing logic directly
- let capturedCallback: ((events: any[]) => void) | null = null;
- let capturedSignal: AbortSignal | null = null;
-
- mockStreamEventManager.subscribeStreamEvents.mockImplementation(
- (operationId, lastEventId, callback, signal) => {
- capturedCallback = callback;
- capturedSignal = signal;
- return Promise.resolve();
- },
- );
-
- const response = await GET(request);
-
- // Verify the subscription was set up correctly
- expect(mockStreamEventManager.subscribeStreamEvents).toHaveBeenCalledWith(
- 'test-operation',
- '0',
- expect.any(Function),
- expect.any(AbortSignal),
- );
- expect(capturedCallback).toBeDefined();
- expect(capturedSignal).toBeDefined();
-
- // Verify response headers are correct
- expect(response.status).toBe(200);
- expect(response.headers.get('Content-Type')).toBe('text/event-stream');
-
- // Test that the callback exists and can be called
- expect(typeof capturedCallback).toBe('function');
- expect(capturedSignal).toBeInstanceOf(AbortSignal);
- });
-
- it('should verify subscribeStreamEvents callback can handle agent_runtime_init events', async () => {
- const request = new NextRequest(
- 'https://test.com/api/agent/stream?operationId=test-operation',
- );
-
- let capturedCallback: ((events: any[]) => void) | null = null;
-
- mockStreamEventManager.subscribeStreamEvents.mockImplementation(
- (operationId, lastEventId, callback, _signal) => {
- capturedCallback = callback;
- return Promise.resolve();
- },
- );
-
- const response = await GET(request);
-
- // Verify we captured the callback
- expect(capturedCallback).toBeDefined();
- expect(response.status).toBe(200);
-
- // Test agent_runtime_init event processing
- const initEvent = {
- type: 'agent_runtime_init',
- timestamp: MOCK_TIMESTAMP + 100,
- operationId: 'test-operation',
- data: {
- userId: 'user-123',
- modelConfig: { model: 'gpt-4', temperature: 0.7 },
- agentType: 'assistant',
- },
- };
-
- // The callback should be callable without throwing errors
- expect(() => capturedCallback!([initEvent])).not.toThrow();
- });
-
- it('should verify subscribeStreamEvents callback can handle agent_runtime_end events', async () => {
- const request = new NextRequest(
- 'https://test.com/api/agent/stream?operationId=test-operation',
- );
-
- let capturedCallback: ((events: any[]) => void) | null = null;
-
- mockStreamEventManager.subscribeStreamEvents.mockImplementation(
- (operationId, lastEventId, callback, _signal) => {
- capturedCallback = callback;
- return Promise.resolve();
- },
- );
-
- const response = await GET(request);
-
- // Verify we captured the callback
- expect(capturedCallback).toBeDefined();
- expect(response.status).toBe(200);
-
- // Test agent_runtime_end event processing
- const endEvent = {
- type: 'agent_runtime_end',
- timestamp: MOCK_TIMESTAMP + 600,
- operationId: 'test-operation',
- data: {
- totalSteps: 1,
- executionTime: 500,
- status: 'completed',
- },
- };
-
- // The callback should be callable without throwing errors
- expect(() => capturedCallback!([endEvent])).not.toThrow();
- });
-
- it('should verify complete agent runtime lifecycle event types are supported', async () => {
- const request = new NextRequest(
- 'https://test.com/api/agent/stream?operationId=test-operation',
- );
-
- let capturedCallback: ((events: any[]) => void) | null = null;
-
- mockStreamEventManager.subscribeStreamEvents.mockImplementation(
- (operationId, lastEventId, callback, _signal) => {
- capturedCallback = callback;
- return Promise.resolve();
- },
- );
-
- const response = await GET(request);
-
- expect(capturedCallback).toBeDefined();
- expect(response.status).toBe(200);
-
- // Test complete lifecycle events can be processed
- const lifecycleEvents = [
- {
- type: 'agent_runtime_init',
- timestamp: MOCK_TIMESTAMP + 100,
- operationId: 'test-operation',
- data: { userId: 'user-123', agentType: 'assistant' },
- },
- {
- type: 'stream_start',
- timestamp: MOCK_TIMESTAMP + 200,
- operationId: 'test-operation',
- data: { messageId: 'msg-001' },
- },
- {
- type: 'stream_chunk',
- timestamp: MOCK_TIMESTAMP + 300,
- operationId: 'test-operation',
- data: { content: 'Hello world' },
- },
- {
- type: 'stream_end',
- timestamp: MOCK_TIMESTAMP + 400,
- operationId: 'test-operation',
- data: { messageId: 'msg-001' },
- },
- {
- type: 'agent_runtime_end',
- timestamp: MOCK_TIMESTAMP + 500,
- operationId: 'test-operation',
- data: { status: 'completed', totalSteps: 1 },
- },
- ];
-
- // All lifecycle events should be processable without throwing errors
- expect(() => capturedCallback!(lifecycleEvents)).not.toThrow();
- });
- });
-
- describe('Heartbeat and connection lifecycle', () => {
- it('should close connection immediately after agent_runtime_end', async () => {
- const request = new NextRequest(
- 'https://test.com/api/agent/stream?operationId=test-operation',
- );
-
- let capturedCallback: ((events: any[]) => void) | null = null;
- let capturedSignal: AbortSignal | null = null;
-
- mockStreamEventManager.subscribeStreamEvents.mockImplementation(
- (operationId, lastEventId, callback, signal) => {
- capturedCallback = callback;
- capturedSignal = signal;
- return new Promise(() => {});
- },
- );
-
- const response = await GET(request);
-
- expect(capturedCallback).toBeDefined();
- expect(capturedSignal).toBeDefined();
-
- // Signal should not be aborted initially
- expect(capturedSignal!.aborted).toBe(false);
-
- // Simulate agent_runtime_end event
- const endEvent = {
- type: 'agent_runtime_end',
- timestamp: MOCK_TIMESTAMP + 1000,
- operationId: 'test-operation',
- data: { status: 'completed' },
- };
- capturedCallback!([endEvent]);
-
- // Signal should be aborted immediately after agent_runtime_end
- expect(capturedSignal!.aborted).toBe(true);
- });
-
- it('should set streamEnded flag and close connection when agent_runtime_end is received', async () => {
- const request = new NextRequest(
- 'https://test.com/api/agent/stream?operationId=test-operation',
- );
-
- let capturedCallback: ((events: any[]) => void) | null = null;
- let capturedSignal: AbortSignal | null = null;
-
- mockStreamEventManager.subscribeStreamEvents.mockImplementation(
- (operationId, lastEventId, callback, signal) => {
- capturedCallback = callback;
- capturedSignal = signal;
- return new Promise(() => {});
- },
- );
-
- const response = await GET(request);
-
- expect(response.status).toBe(200);
- expect(capturedCallback).toBeDefined();
- expect(capturedSignal).toBeDefined();
-
- // Simulate agent_runtime_end event - this should set streamEnded = true
- const endEvent = {
- type: 'agent_runtime_end',
- timestamp: MOCK_TIMESTAMP + 1000,
- operationId: 'test-operation',
- data: { status: 'completed' },
- };
-
- // This should not throw - verifies the callback can handle the event
- expect(() => capturedCallback!([endEvent])).not.toThrow();
- });
-
- it('should handle agent_runtime_end event in callback without errors', async () => {
- const request = new NextRequest(
- 'https://test.com/api/agent/stream?operationId=test-operation',
- );
-
- let capturedCallback: ((events: any[]) => void) | null = null;
-
- mockStreamEventManager.subscribeStreamEvents.mockImplementation(
- (operationId, lastEventId, callback, _signal) => {
- capturedCallback = callback;
- return new Promise(() => {});
- },
- );
-
- const response = await GET(request);
-
- expect(response.status).toBe(200);
- expect(capturedCallback).toBeDefined();
-
- // Simulate agent_runtime_end with full data
- const endEvent = {
- type: 'agent_runtime_end',
- timestamp: MOCK_TIMESTAMP + 1000,
- operationId: 'test-operation',
- data: {
- finalState: { status: 'completed' },
- reason: 'completed',
- reasonDetail: 'Agent runtime completed successfully',
- },
- };
-
- // Verify the event is processed without throwing
- expect(() => capturedCallback!([endEvent])).not.toThrow();
- });
-
- it('should handle batch events including agent_runtime_end without errors', async () => {
- const request = new NextRequest(
- 'https://test.com/api/agent/stream?operationId=test-operation',
- );
-
- let capturedCallback: ((events: any[]) => void) | null = null;
-
- mockStreamEventManager.subscribeStreamEvents.mockImplementation(
- (operationId, lastEventId, callback, _signal) => {
- capturedCallback = callback;
- return new Promise(() => {});
- },
- );
-
- const response = await GET(request);
-
- expect(response.status).toBe(200);
- expect(capturedCallback).toBeDefined();
-
- // Simulate batch of events ending with agent_runtime_end
- const batchEvents = [
- {
- type: 'stream_chunk',
- timestamp: MOCK_TIMESTAMP + 800,
- operationId: 'test-operation',
- data: { content: 'Final chunk' },
- },
- {
- type: 'stream_end',
- timestamp: MOCK_TIMESTAMP + 900,
- operationId: 'test-operation',
- data: { messageId: 'msg-001' },
- },
- {
- type: 'agent_runtime_end',
- timestamp: MOCK_TIMESTAMP + 1000,
- operationId: 'test-operation',
- data: { status: 'completed' },
- },
- ];
-
- // All events should be processed without throwing
- expect(() => capturedCallback!(batchEvents)).not.toThrow();
- });
-
- it('should skip events after streamEnded flag is set', async () => {
- const request = new NextRequest(
- 'https://test.com/api/agent/stream?operationId=test-operation',
- );
-
- let capturedCallback: ((events: any[]) => void) | null = null;
- let capturedSignal: AbortSignal | null = null;
-
- mockStreamEventManager.subscribeStreamEvents.mockImplementation(
- (operationId, lastEventId, callback, signal) => {
- capturedCallback = callback;
- capturedSignal = signal;
- return new Promise(() => {});
- },
- );
-
- const response = await GET(request);
-
- expect(response.status).toBe(200);
- expect(capturedCallback).toBeDefined();
- expect(capturedSignal).toBeDefined();
- expect(capturedSignal!.aborted).toBe(false);
-
- // First, send agent_runtime_end to set streamEnded = true
- capturedCallback!([
- {
- type: 'agent_runtime_end',
- timestamp: MOCK_TIMESTAMP + 1000,
- operationId: 'test-operation',
- data: { status: 'completed' },
- },
- ]);
-
- // Signal should be aborted immediately
- expect(capturedSignal!.aborted).toBe(true);
-
- // Any subsequent events should be skipped (no errors)
- expect(() =>
- capturedCallback!([
- {
- type: 'step_complete',
- timestamp: MOCK_TIMESTAMP + 1100,
- operationId: 'test-operation',
- data: { stepIndex: 1 },
- },
- ]),
- ).not.toThrow();
- });
- });
-
- describe('Parameter validation', () => {
- it('should handle operationId with special characters', async () => {
- const operationId = 'test-operation-123_456';
- const request = new NextRequest(
- `https://test.com/api/agent/stream?operationId=${operationId}`,
- );
-
- const response = await GET(request);
-
- expect(response.status).toBe(200);
- });
-
- it('should handle lastEventId as string number', async () => {
- const request = new NextRequest(
- 'https://test.com/api/agent/stream?operationId=test&lastEventId=12345',
- );
-
- const response = await GET(request);
-
- expect(response.status).toBe(200);
- });
-
- it('should handle includeHistory as string boolean', async () => {
- const request = new NextRequest(
- 'https://test.com/api/agent/stream?operationId=test&includeHistory=false',
- );
-
- const response = await GET(request);
-
- expect(response.status).toBe(200);
- expect(mockStreamEventManager.getStreamHistory).not.toHaveBeenCalled();
- });
-
- it('should handle invalid URL gracefully', async () => {
- const request = new NextRequest('https://test.com/api/agent/stream?operationId=');
-
- const response = await GET(request);
-
- expect(response.status).toBe(400);
- const data = await response.json();
- expect(data.error).toBe('operationId parameter is required');
- });
- });
-});
diff --git a/src/app/(backend)/api/agent/stream/route.ts b/src/app/(backend)/api/agent/stream/route.ts
deleted file mode 100644
index 74c9df005f8..00000000000
--- a/src/app/(backend)/api/agent/stream/route.ts
+++ /dev/null
@@ -1,248 +0,0 @@
-import { createSSEHeaders, createSSEWriter } from '@lobechat/utils/server';
-import debug from 'debug';
-import { type NextRequest } from 'next/server';
-import { NextResponse } from 'next/server';
-
-import { createLambdaContext } from '@/libs/trpc/lambda/context';
-import { createAgentStateManager, createStreamEventManager } from '@/server/modules/AgentRuntime';
-
-const log = debug('api-route:agent:stream');
-const timing = debug('lobe-server:agent-runtime:timing');
-
-/**
- * Server-Sent Events (SSE) endpoint
- * Provides real-time Agent execution event stream for clients
- */
-export async function GET(request: NextRequest) {
- // Initialize stream event manager (uses InMemory singleton in local dev, Redis in production)
- const streamManager = createStreamEventManager();
-
- const { searchParams } = new URL(request.url);
- const operationId = searchParams.get('operationId');
- const lastEventId = searchParams.get('lastEventId') || '0';
- const includeHistory = searchParams.get('includeHistory') === 'true';
-
- if (!operationId) {
- return NextResponse.json(
- {
- error: 'operationId parameter is required',
- },
- { status: 400 },
- );
- }
-
- // Resolve the caller the same way the lambda tRPC context does (Better Auth
- // session cookie, `Oidc-Auth` JWT, or `X-API-Key`) so the CLI's existing
- // `getAgentStreamAuthInfo` headers keep working unchanged.
- const { userId: callerUserId } = await createLambdaContext(request);
-
- if (!callerUserId) {
- return NextResponse.json({ error: 'unauthorized' }, { status: 401 });
- }
-
- const agentStateManager = createAgentStateManager();
- const metadata = await agentStateManager.getOperationMetadata(operationId);
-
- if (!metadata) {
- return NextResponse.json({ error: 'operation_not_found' }, { status: 404 });
- }
-
- // A share-visitor run (`AgentOperationMetadata.streamOwnerUserId` set β€” see its
- // JSDoc in `AgentStateManager.ts`) executes as the creator but must only ever
- // be read back through the Gateway WS channel, which applies the owner-configured
- // visitor redaction (`gatewayVisitorRedaction.ts`). This raw endpoint replays
- // unredacted history with no projection, and the creator must never read a
- // visitor's transcript (visitor-isolation invariant) β€” so reject with 404 for
- // EVERY caller, including both the visitor and the creator.
- if (metadata.streamOwnerUserId) {
- return NextResponse.json({ error: 'operation_not_found' }, { status: 404 });
- }
-
- // Otherwise this is a normal (non-share) operation: only its owner may read it.
- // 404 rather than 403 so an unauthorized caller cannot distinguish "not mine"
- // from "does not exist".
- if (metadata.userId !== callerUserId) {
- return NextResponse.json({ error: 'operation_not_found' }, { status: 404 });
- }
-
- log(`Starting SSE connection for operation ${operationId} from eventId ${lastEventId}`);
-
- // Create Server-Sent Events stream
- const stream = new ReadableStream({
- cancel(reason) {
- log(`SSE connection cancelled for operation ${operationId}:`, reason);
-
- // Call cleanup function
- if ((this as any)._cleanup) {
- (this as any)._cleanup();
- }
- },
-
- start(controller) {
- const writer = createSSEWriter(controller);
-
- // Send connection confirmation event
- writer.writeConnection(operationId, lastEventId);
- log(`SSE connection established for operation ${operationId}`);
-
- // If needed, send historical events first
- if (includeHistory) {
- streamManager
- .getStreamHistory(operationId, 50)
- .then((history) => {
- // Send historical events in chronological order (earliest first)
- const sortedHistory = history.reverse();
-
- sortedHistory.forEach((event) => {
- // Only send events newer than lastEventId
- if (!lastEventId || lastEventId === '0' || event.timestamp.toString() > lastEventId) {
- try {
- // Add SSE-specific fields, keeping format consistent with real-time events
- const sseEvent = {
- ...event,
- operationId,
- timestamp: event.timestamp || Date.now(),
- };
- writer.writeStreamEvent(sseEvent, operationId);
- } catch (error) {
- console.error('[Agent Stream] Error sending history event:', error);
- }
- }
- });
-
- if (sortedHistory.length > 0) {
- log(`Sent ${sortedHistory.length} historical events for operation ${operationId}`);
- }
- })
- .catch((error) => {
- console.error('[Agent Stream] Failed to load history:', error);
-
- try {
- writer.writeError(error, operationId, 'history_loading');
- } catch (controllerError) {
- console.error('[Agent Stream] Failed to send error event:', controllerError);
- }
- });
- }
-
- // Create AbortController for canceling subscription
- const abortController = new AbortController();
-
- // Track if stream has ended (agent_runtime_end received)
- // Once set to true, no more events will be sent
- let streamEnded = false;
-
- // Send heartbeat periodically (every 30 seconds)
- const heartbeatInterval = setInterval(() => {
- // Skip heartbeat if stream has ended
- if (streamEnded) {
- return;
- }
-
- try {
- const heartbeat = {
- operationId,
- timestamp: Date.now(),
- type: 'heartbeat',
- };
-
- controller.enqueue(`data: ${JSON.stringify(heartbeat)}\n\n`);
- } catch (error) {
- console.error('[Agent Stream] Heartbeat error:', error);
- clearInterval(heartbeatInterval);
- }
- }, 30_000);
-
- // Cleanup function
- const cleanup = () => {
- abortController.abort();
- clearInterval(heartbeatInterval);
- log(`SSE connection closed for operation ${operationId}`);
- };
-
- // Subscribe to new streaming events
- const subscribeToEvents = async () => {
- try {
- await streamManager.subscribeStreamEvents(
- operationId,
- lastEventId,
- (events) => {
- events.forEach((event) => {
- // Skip all events if stream has ended
- if (streamEnded) {
- return;
- }
-
- try {
- // Add SSE-specific fields
- const sseEvent = {
- ...event,
- operationId,
- timestamp: event.timestamp || Date.now(),
- };
-
- const now = Date.now();
- const totalLatency = now - sseEvent.timestamp;
- writer.writeStreamEvent(sseEvent, operationId);
- timing(
- '[%s:%d] SSE sent %s, original timestamp %d, sent at %d, total latency %dms',
- operationId,
- event.stepIndex,
- event.type,
- sseEvent.timestamp,
- now,
- totalLatency,
- );
-
- // If agent_runtime_end event is received, terminate stream immediately
- if (event.type === 'agent_runtime_end') {
- log(
- `Agent runtime ended for operation ${operationId}, terminating stream immediately`,
- );
-
- // Mark stream as ended to prevent any more events
- streamEnded = true;
-
- // Immediately cleanup and close connection
- cleanup();
- controller.close();
- log(
- `SSE connection closed after agent runtime end for operation ${operationId}`,
- );
- }
- } catch (error) {
- console.error('[Agent Stream] Error sending event:', error);
- }
- });
- },
- abortController.signal,
- );
- } catch (error) {
- if (!abortController.signal.aborted) {
- console.error('[Agent Stream] Subscription error:', error);
-
- try {
- writer.writeError(error as Error, operationId, 'stream_subscription');
- } catch (controllerError) {
- console.error('[Agent Stream] Failed to send subscription error:', controllerError);
- }
- }
- }
- };
-
- // Start subscription
- subscribeToEvents();
-
- // Listen for connection close
- request.signal?.addEventListener('abort', cleanup);
-
- // Store cleanup function for calling during cancel
- (controller as any)._cleanup = cleanup;
- },
- });
-
- // Set SSE response headers
- return new Response(stream, {
- headers: createSSEHeaders(),
- });
-}