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.

πŸ› fix(openapi): mirror streaming responses to the agent gateway (#20276)

Arvin Xuc278de8a3ffd
diff --git a/apps/server/src/modules/AgentRuntime/factory.ts b/apps/server/src/modules/AgentRuntime/factory.ts
index 2103bdb0e3c..9e627e918d1 100644
--- a/apps/server/src/modules/AgentRuntime/factory.ts
+++ b/apps/server/src/modules/AgentRuntime/factory.ts
@@ -54,26 +54,45 @@ export const createAgentStateManager = (): IAgentStateManager => {
* - If Redis is available: RedisStreamEventManager
* - If Redis is unavailable and enableQueueAgentRuntime=false (default): InMemoryStreamEventManager
* - If Redis is unavailable and enableQueueAgentRuntime=true: throw
+ *
+ * Pass `inner` to supply the manager yourself β€” the gateway notifier still wraps
+ * it, so the gateway keeps seeing the events while the caller keeps whatever
+ * delivery it chose (see `CreateStreamEventManagerOptions.inner`).
*/
-export const createStreamEventManager = (
- options?: GatewayStreamNotifierOptions,
-): IStreamEventManager => {
- let manager: IStreamEventManager;
+export interface CreateStreamEventManagerOptions extends GatewayStreamNotifierOptions {
+ /**
+ * The manager events are published to and read back from, instead of the
+ * config-driven default. For a caller that owns a per-invocation subscription:
+ * the streaming Responses route consumes the run's events from the same
+ * process that produces them, so it passes a private in-memory manager rather
+ * than taking a second Redis subscriber's connection per request β€” while the
+ * wrapping notifier still carries every event to the gateway.
+ */
+ inner?: IStreamEventManager;
+}
+const createDefaultStreamEventManager = (): IStreamEventManager => {
// Prefer Redis whenever it is available so the runtime worker and SSE route
// can communicate through the same stream bus even in local mode.
if (isRedisAvailable()) {
log('Redis available, using StreamEventManager');
- manager = new StreamEventManager();
- } else if (!isQueueModeEnabled()) {
+ return new StreamEventManager();
+ }
+
+ if (!isQueueModeEnabled()) {
log('Redis unavailable and queue mode disabled, using InMemoryStreamEventManager');
- manager = inMemoryStreamEventManager;
- } else {
- throw new Error(
- 'Redis is required when AGENT_RUNTIME_MODE=queue. Please configure `REDIS_URL`.',
- );
+ return inMemoryStreamEventManager;
}
+ throw new Error('Redis is required when AGENT_RUNTIME_MODE=queue. Please configure `REDIS_URL`.');
+};
+
+export const createStreamEventManager = (
+ options?: CreateStreamEventManagerOptions,
+): IStreamEventManager => {
+ const { inner, ...notifierOptions } = options ?? {};
+ const manager = inner ?? createDefaultStreamEventManager();
+
// Wrap with Gateway notifier when configured. Server pushes prefer the internal
// URL: the public one is what browsers open, which a container may not reach.
const gatewayUrl = appEnv.AGENT_GATEWAY_INTERNAL_URL || appEnv.AGENT_GATEWAY_URL;
@@ -102,7 +121,7 @@ export const createStreamEventManager = (
return meta.visitorRedaction ?? FULL_STRIP_REDACTION;
},
{
- ...options,
+ ...notifierOptions,
// Same again for the supervisor's `member_runtime_end` declaration: the
// worker mirroring a member's terminal may never have seen its init.
resolveAcceptsMemberRuntimeEnd: async (operationId) => {
diff --git a/packages/openapi/src/services/__tests__/responses.extractOutputItems.test.ts b/packages/openapi/src/services/__tests__/responses.extractOutputItems.test.ts
index 59d343ff8f6..abfe12d6536 100644
--- a/packages/openapi/src/services/__tests__/responses.extractOutputItems.test.ts
+++ b/packages/openapi/src/services/__tests__/responses.extractOutputItems.test.ts
@@ -4,8 +4,8 @@ import { describe, expect, it, vi } from 'vitest';
import { ResponsesService } from '../responses.service';
// Stub external dependencies so ResponsesService can be imported in isolation
-vi.mock('@/server/modules/AgentRuntime/InMemoryStreamEventManager', () => ({
- InMemoryStreamEventManager: class {},
+vi.mock('@/server/modules/AgentRuntime/factory', () => ({
+ createStreamEventManager: () => ({}),
}));
vi.mock('@/server/modules/AgentRuntime/StreamEventManager', () => ({}));
vi.mock('@/server/services/agentRuntime', () => ({ AgentRuntimeService: class {} }));
diff --git a/packages/openapi/src/services/__tests__/responses.streaming.test.ts b/packages/openapi/src/services/__tests__/responses.streaming.test.ts
new file mode 100644
index 00000000000..66ed3ab47ee
--- /dev/null
+++ b/packages/openapi/src/services/__tests__/responses.streaming.test.ts
@@ -0,0 +1,129 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const { createStreamEventManagerMock, drainPushesMock, executeSyncMock, execAgentMock } = vi.hoisted(
+ () => ({
+ createStreamEventManagerMock: vi.fn(),
+ drainPushesMock: vi.fn(),
+ executeSyncMock: vi.fn(),
+ execAgentMock: vi.fn(),
+ }),
+);
+
+vi.mock('@/server/modules/AgentRuntime/factory', () => ({
+ createStreamEventManager: createStreamEventManagerMock,
+}));
+vi.mock('@/server/services/agentRuntime', () => ({
+ AgentRuntimeService: class {
+ executeSync = executeSyncMock;
+ },
+}));
+vi.mock('@/server/services/aiAgent', () => ({
+ AiAgentService: class {
+ execAgent = execAgentMock;
+ },
+}));
+vi.mock('../../common/base.service', () => ({
+ BaseService: class {
+ db: any = null;
+ userId = 'user_1';
+ workspaceId = 'ws_1';
+ constructor() {}
+ log() {}
+ },
+}));
+
+import { InMemoryStreamEventManager } from '@/server/modules/AgentRuntime/InMemoryStreamEventManager';
+
+import { ResponsesService } from '../responses.service';
+
+const buildService = () => new (ResponsesService as any)(null, 'user_1', { workspaceId: 'ws_1' });
+
+/** The private in-memory manager the service took from the factory. */
+const subscribedManager = (): InMemoryStreamEventManager =>
+ createStreamEventManagerMock.mock.calls[0][0].inner;
+
+const remainingSubscribers = (manager: InMemoryStreamEventManager, operationId: string): number =>
+ ((manager as any).subscribers.get(operationId) ?? []).length;
+
+/** Publish one text chunk through the manager, standing in for the runtime. */
+const publishChunk = async (operationId: string, content: string) => {
+ await subscribedManager().publishStreamChunk(operationId, 0, { chunkType: 'text', content });
+};
+
+describe('ResponsesService.createStreamingResponse', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ drainPushesMock.mockResolvedValue(undefined);
+ execAgentMock.mockResolvedValue({ operationId: 'op_1', success: true, topicId: 'tpc_1' });
+ createStreamEventManagerMock.mockReturnValue({ drainPushes: drainPushesMock });
+ });
+
+ it('mirrors the run to the gateway while streaming from a private in-memory manager', async () => {
+ executeSyncMock.mockImplementation(async () => {
+ await publishChunk('op_1', 'hi');
+ return { messages: [], status: 'done', stepCount: 1 };
+ });
+
+ const events: any[] = [];
+ for await (const event of buildService().createStreamingResponse({
+ input: 'hello',
+ model: 'agt_1',
+ })) {
+ events.push(event);
+ }
+
+ // Regression: `execAgent` registers the operation with the gateway DO, which
+ // only closes the session on an `agent_runtime_end`. Running the operation
+ // on a manager nothing mirrors left the DO holding a finished run as
+ // `running` until its inactivity watchdog abandoned it.
+ expect(createStreamEventManagerMock).toHaveBeenCalledTimes(1);
+ // Must match `AgentRuntimeService`'s own setup: `deferPushes` keeps a
+ // `stream_end` / `message_patch` step from blocking on its gateway HTTP
+ // push, and the generator's `finally` drains what was deferred.
+ expect(createStreamEventManagerMock).toHaveBeenCalledWith({
+ deferPushes: true,
+ inner: expect.any(InMemoryStreamEventManager),
+ });
+ expect(subscribedManager()).toBeInstanceOf(InMemoryStreamEventManager);
+
+ // Streaming still works end to end, from the in-process manager.
+ const deltas = events.filter((event) => event.type === 'response.output_text.delta');
+ expect(deltas.map((delta) => delta.delta)).toEqual(['hi']);
+ expect(events.at(-1)?.type).toBe('response.completed');
+
+ // The terminal push has to land before the invocation can be frozen.
+ expect(drainPushesMock).toHaveBeenCalledWith('op_1');
+ // …and the subscription is released with it.
+ expect(remainingSubscribers(subscribedManager(), 'op_1')).toBe(0);
+ });
+
+ it('releases the subscription and drains pushes when the client disconnects mid-stream', async () => {
+ executeSyncMock.mockImplementation(async () => {
+ await publishChunk('op_1', 'hi');
+ // The run never finishes: the client drops mid-stream instead.
+ await new Promise(() => {});
+ return { messages: [], status: 'done', stepCount: 1 };
+ });
+
+ const generator = buildService().createStreamingResponse({
+ input: 'hello',
+ model: 'agt_1',
+ });
+
+ // Consume up to the first streamed token, then close the generator the way
+ // the controller does when its `for await` is abandoned.
+ const seen: string[] = [];
+ for (let step = 0; step < 10; step += 1) {
+ const { done, value } = await generator.next();
+ if (done) break;
+ seen.push(value.type);
+ if (value.type === 'response.output_text.delta') break;
+ }
+ expect(seen).toContain('response.output_text.delta');
+
+ await generator.return(undefined);
+
+ expect(drainPushesMock).toHaveBeenCalledWith('op_1');
+ expect(remainingSubscribers(subscribedManager(), 'op_1')).toBe(0);
+ });
+});
diff --git a/packages/openapi/src/services/responses.service.ts b/packages/openapi/src/services/responses.service.ts
index f3b071c7d51..a836fb02297 100644
--- a/packages/openapi/src/services/responses.service.ts
+++ b/packages/openapi/src/services/responses.service.ts
@@ -1,5 +1,6 @@
import type { AgentState } from '@lobechat/agent-runtime';
+import { createStreamEventManager } from '@/server/modules/AgentRuntime/factory';
import { InMemoryStreamEventManager } from '@/server/modules/AgentRuntime/InMemoryStreamEventManager';
import type {
StreamChunkData,
@@ -371,6 +372,9 @@ export class ResponsesService extends BaseService {
): AsyncGenerator<ResponseStreamEvent> {
const createdAt = Math.floor(Date.now() / 1000);
let sequenceNumber = 0;
+ // Set once the run has a subscription to release; the `finally` below runs
+ // even when the consumer closes this generator early (client disconnect).
+ let releaseStream: (() => Promise<void>) | undefined;
try {
const model = params.model;
@@ -434,8 +438,34 @@ export class ResponsesService extends BaseService {
type: 'response.in_progress' as const,
};
- // 2. Create AgentRuntimeService with custom stream manager for event subscription
- const streamEventManager = new InMemoryStreamEventManager();
+ // 2. Run the operation on the gateway-aware stream pipeline, with this
+ // generator's own subscription on a private in-memory manager.
+ //
+ // `execAgent` above already registered this operation with the
+ // agent-gateway Durable Object (`publishAgentRuntimeInit`), and that DO
+ // only closes the session on an `agent_runtime_end`. Executing on a
+ // manager nothing mirrors leaves the DO holding a run that finished long
+ // ago as `running`, so its inactivity watchdog abandons the operation
+ // ~10 minutes later β€” writing an `Operation abandoned: inactivity_watchdog`
+ // failure on top of a turn that already succeeded, and handing the API
+ // caller an error after the response it already received. Going through
+ // `createStreamEventManager` puts every event, terminal included, on the
+ // gateway.
+ //
+ // The events this generator consumes stay push-style from the process that
+ // produces them: the subscription hangs off a private in-memory manager
+ // rather than taking a second Redis subscriber's connection per streamed
+ // request.
+ //
+ // `deferPushes` matches `AgentRuntimeService`'s own default: without it a
+ // `stream_end` / `message_patch` step would block on its gateway HTTP push
+ // (up to 5s whenever the gateway is slow). The `finally` below drains what
+ // this invocation deferred, which is what the option requires.
+ const localStreamManager = new InMemoryStreamEventManager();
+ const streamEventManager = createStreamEventManager({
+ deferPushes: true,
+ inner: localStreamManager,
+ });
const agentRuntimeService = new AgentRuntimeService(this.db, this.userId, {
queueService: null,
streamEventManager,
@@ -447,7 +477,7 @@ export class ResponsesService extends BaseService {
let resolveWaiting: (() => void) | null = null;
let executionDone = false;
- const unsubscribe = streamEventManager.subscribe(operationId, (events) => {
+ const unsubscribe = localStreamManager.subscribe(operationId, (events) => {
eventQueue.push(...events);
if (resolveWaiting) {
resolveWaiting();
@@ -455,6 +485,17 @@ export class ResponsesService extends BaseService {
}
});
+ // Released in the `finally` below, which also covers this generator being
+ // closed early when the API client disconnects mid-stream.
+ releaseStream = async () => {
+ unsubscribe();
+ // Make sure the gateway pushes this invocation issued β€” including the
+ // terminal event that closes the DO session β€” land before the function
+ // can be frozen. Nothing else guarantees an unawaited push survives the
+ // end of the request.
+ await streamEventManager.drainPushes?.(operationId);
+ };
+
// Helper to wait for next event batch
const waitForEvents = (): Promise<void> =>
new Promise((resolve) => {
@@ -741,7 +782,6 @@ export class ResponsesService extends BaseService {
// 6. Wait for execution to fully complete
await executionPromise;
- unsubscribe();
// If no text came through streaming, extract from final state
if (!accumulatedText && finalState) {
@@ -824,6 +864,11 @@ export class ResponsesService extends BaseService {
sequence_number: sequenceNumber,
type: 'response.failed' as const,
};
+ } finally {
+ // Runs on the normal path and when the consumer closes this generator
+ // early, so a client that disconnects mid-stream still releases the
+ // subscription and flushes the gateway pushes it triggered.
+ await releaseStream?.();
}
}