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(agent): seed gateway runtime init for local hetero so reconnect keeps streaming (#16369)

Arvin Xuc25ff80e4aed
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
index 818cb051a0f..1e41820729d 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
@@ -10,16 +10,33 @@ const {
mockResolveAttachmentsByFileIds,
mockSpawnHeteroSandbox,
mockIngestAttachment,
+ mockPublishAgentRuntimeInit,
+ mockPublishAgentRuntimeEnd,
} = vi.hoisted(() => ({
mockDeviceFindByDeviceId: vi.fn(),
mockDeviceFindWorkspaceDeviceById: vi.fn(),
mockDispatchAgentRun: vi.fn().mockResolvedValue({ success: true }),
mockIngestAttachment: vi.fn(),
mockMessageCreate: vi.fn(),
+ mockPublishAgentRuntimeEnd: vi.fn().mockResolvedValue('end-event-id'),
+ mockPublishAgentRuntimeInit: vi.fn().mockResolvedValue('init-event-id'),
mockResolveAttachmentsByFileIds: vi.fn(),
mockSpawnHeteroSandbox: vi.fn().mockResolvedValue(undefined),
}));
+// Local hetero (claude-code / codex) now seeds publishAgentRuntimeInit so the
+// agent-gateway DO reports `running` on a later reconnect. Stub the factory so
+// the assertion below can verify the init, and so the real one (which probes
+// Redis synchronously) doesn't throw a server-env error in the test env.
+vi.mock('@/server/modules/AgentRuntime/factory', () => ({
+ createAgentStateManager: vi.fn(),
+ createStreamEventManager: () => ({
+ publishAgentRuntimeEnd: mockPublishAgentRuntimeEnd,
+ publishAgentRuntimeInit: mockPublishAgentRuntimeInit,
+ }),
+ isRedisAvailable: vi.fn(() => false),
+}));
+
const emptyResolvedAttachments = {
fileList: [],
imageList: [],
@@ -598,5 +615,47 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>
'/api/workflows/task/on-topic-complete',
);
});
+
+ // Regression guard for the "open the window and CC stops" bug: a device-
+ // dispatched local hetero run must register the op with the agent-gateway DO
+ // (publishAgentRuntimeInit) so a later reconnect resume reports `running`
+ // instead of a terminal status that clears runningOperation and black-holes
+ // the still-running agent's heteroIngest batches.
+ it('seeds the gateway runtime init for a device-dispatched local hetero run', async () => {
+ heteroAgentConfig.agencyConfig = {
+ boundDeviceId: 'device-1',
+ executionTarget: 'device',
+ heterogeneousProvider: { type: 'claude-code' },
+ } as any;
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ prompt: 'do the task on device',
+ } as any);
+
+ expect(mockDispatchAgentRun).toHaveBeenCalled();
+ expect(mockPublishAgentRuntimeInit).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({ heteroType: 'claude-code' }),
+ );
+ });
+
+ it('seeds the gateway runtime init for a sandbox-dispatched local hetero run', async () => {
+ heteroAgentConfig.agencyConfig = {
+ heterogeneousProvider: { type: 'claude-code' },
+ } as any;
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ prompt: 'do the task in the cloud sandbox',
+ } as any);
+
+ // Sanity: this run took the sandbox path.
+ expect(mockSpawnHeteroSandbox).toHaveBeenCalled();
+ expect(mockPublishAgentRuntimeInit).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({ heteroType: 'claude-code' }),
+ );
+ });
});
});
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index ec019fad77a..87193a53a82 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -1742,6 +1742,34 @@ export class AiAgentService {
// `canUseDevice` degrades device-capable targets to the sandbox for
// denied senders (e.g. external bot users) β€” without it a synced
// local/device binding would let them run on the owner's machine.
+
+ // Register the op with the agent-gateway DO before dispatch, mirroring
+ // the remote-hetero branch above. Local CLI hetero (claude-code / codex)
+ // streams back via heteroIngest, which forwards live events the DO can
+ // relay even without an init β€” so the FIRST run renders fine. But a later
+ // `reconnectToGatewayOperation` (task topic drawer open / page reload)
+ // sends a `resume` that asks the DO for the op's status; with no session
+ // record the DO answers terminal, the client fires `session_complete`,
+ // and `onSessionComplete` clears `topic.metadata.runningOperation`. The
+ // still-running CC's next heteroIngest batch then hits
+ // StaleHeteroOperationError and is silently dropped β€” the agent appears
+ // to stop the moment the window is opened. Seeding the init keeps the DO
+ // reporting `running`, so resume stays connected and keeps streaming.
+ // Best-effort: a stream-manager/Redis failure must never block dispatch β€”
+ // the init only powers reconnect, not the run. `createStreamEventManager`
+ // probes Redis synchronously, so guard construction too, not just publish.
+ try {
+ await createStreamEventManager().publishAgentRuntimeInit(operationId, {
+ agentId: resolvedAgentId,
+ assistantMessageId: assistantMessageRecord.id,
+ heteroType,
+ topicId,
+ userId: this.userId,
+ });
+ } catch (err) {
+ log('execAgent: failed to init stream for local hetero: %O', err);
+ }
+
const heteroPlan = resolveExecutionPlan({
agencyConfig: agentConfig.agencyConfig,
canUseDevice,
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
index 897432b7a5f..faf2f1286fb 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
@@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type * as ConstVersion from '@/const/version';
import { aiAgentService } from '@/services/aiAgent';
+import { topicService } from '@/services/topic';
import type { GatewayConnection } from '../transports/gateway/gateway';
import { GatewayActionImpl } from '../transports/gateway/gateway';
@@ -1046,5 +1047,118 @@ describe('GatewayActionImpl', () => {
}),
);
});
+
+ // Captures the onSessionComplete handed to connectToGateway so we can drive
+ // both close paths directly. Provides the methods that callback reaches.
+ function createOnSessionCompleteHarness() {
+ const captured: { onSessionComplete?: (p: any) => void } = {};
+ const completeOperation = vi.fn();
+ const updateTopicStatus = vi.fn();
+ const startOperation = vi.fn(() => ({ operationId: 'gw-op-reconnect' }));
+ const state: Record<string, any> = {
+ activeAgentId: 'agent-1',
+ activeTopicId: 'topic-1',
+ gatewayConnections: {},
+ messagesMap: { 'agent-1_topic-1': [{ createdAt: 1, id: 'ast-1' }] },
+ topicDataMap: {},
+ };
+ const set = vi.fn((updater: any) => {
+ if (typeof updater === 'function') Object.assign(state, updater(state));
+ else Object.assign(state, updater);
+ });
+ const get = vi.fn(() => ({
+ ...state,
+ associateMessageWithOperation: vi.fn(),
+ completeOperation,
+ connectToGateway: (params: any) => {
+ captured.onSessionComplete = params.onSessionComplete;
+ },
+ internal_updateTopicLoading: vi.fn(),
+ onOperationCancel: vi.fn(),
+ startOperation,
+ updateTopicStatus,
+ })) as any;
+
+ (globalThis as any).window = {
+ global_serverConfigStore: {
+ getState: () => ({ serverConfig: { agentGatewayUrl: 'https://gateway.test.com' } }),
+ },
+ };
+ vi.mocked(aiAgentService.refreshGatewayToken).mockResolvedValue({
+ token: 'fresh-token',
+ } as any);
+
+ const action = new GatewayActionImpl(set as any, get, undefined);
+ action.createClient = vi.fn(() => createMockClient());
+
+ return { action, captured, completeOperation, updateTopicStatus };
+ }
+
+ // The core black-hole guard: a reconnect that closes WITHOUT witnessing a
+ // real terminal event (e.g. the gateway DO reports a terminal status for a
+ // heterogeneous CC op it has no live session for) must NOT clear
+ // runningOperation β€” otherwise the still-running agent's next heteroIngest
+ // batch is dropped as stale and it silently stops.
+ it('does NOT clear runningOperation on a non-terminal reconnect close', async () => {
+ const { action, captured, completeOperation, updateTopicStatus } =
+ createOnSessionCompleteHarness();
+
+ await action.reconnectToGatewayOperation({
+ assistantMessageId: 'ast-1',
+ operationId: 'server-op-1',
+ topicId: 'topic-1',
+ });
+
+ vi.mocked(topicService.updateTopicMetadata).mockClear().mockResolvedValue(undefined as never);
+ captured.onSessionComplete!({ authFailed: false, succeeded: false, terminalReceived: false });
+
+ expect(completeOperation).toHaveBeenCalledWith('gw-op-reconnect');
+ expect(topicService.updateTopicMetadata).not.toHaveBeenCalled();
+ expect(updateTopicStatus).not.toHaveBeenCalled();
+ });
+
+ // A genuine terminal event (agent_runtime_end / error) still finalizes the
+ // run: clear runningOperation so the topic doesn't reconnect forever.
+ it('clears runningOperation when a real terminal event was received', async () => {
+ const { action, captured, completeOperation } = createOnSessionCompleteHarness();
+
+ await action.reconnectToGatewayOperation({
+ assistantMessageId: 'ast-1',
+ operationId: 'server-op-1',
+ topicId: 'topic-1',
+ });
+
+ vi.mocked(topicService.updateTopicMetadata).mockClear().mockResolvedValue(undefined as never);
+ captured.onSessionComplete!({ authFailed: false, succeeded: true, terminalReceived: true });
+
+ // The run lifecycle owns completion when a terminal event arrives, so the
+ // reconnect path must not double-complete its local op here.
+ expect(completeOperation).not.toHaveBeenCalled();
+ expect(topicService.updateTopicMetadata).toHaveBeenCalledWith('topic-1', {
+ runningOperation: null,
+ });
+ });
+
+ // auth_failed (or a failed token refresh) is authoritative that the op is
+ // gone: clear the stale marker AND complete the local op, so reloads / drawer
+ // opens stop reconnecting to a dead operation. Without this the persisted
+ // runningOperation lingers forever.
+ it('clears runningOperation and completes the local op on auth failure', async () => {
+ const { action, captured, completeOperation } = createOnSessionCompleteHarness();
+
+ await action.reconnectToGatewayOperation({
+ assistantMessageId: 'ast-1',
+ operationId: 'server-op-1',
+ topicId: 'topic-1',
+ });
+
+ vi.mocked(topicService.updateTopicMetadata).mockClear().mockResolvedValue(undefined as never);
+ captured.onSessionComplete!({ authFailed: true, succeeded: false, terminalReceived: false });
+
+ expect(completeOperation).toHaveBeenCalledWith('gw-op-reconnect');
+ expect(topicService.updateTopicMetadata).toHaveBeenCalledWith('topic-1', {
+ runningOperation: null,
+ });
+ });
});
});
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
index 848da05ec7d..7e64b273aeb 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -103,8 +103,19 @@ export interface ConnectGatewayParams {
* cleanup. When false (terminal-missing: `session_complete` / `auth_failed` /
* token-refresh failure arrived with no terminal agent event), the callback must
* itself complete the op as the explicit fallback so it never sticks `running`.
+ *
+ * `authFailed` is true when the close was driven by the gateway rejecting auth
+ * (`auth_failed`, or a failed `auth_expired` token refresh) β€” an authoritative
+ * "this op no longer exists on the server" signal. Reconnect callers use it to
+ * distinguish a genuinely-dead op (clear the persisted marker) from a bare
+ * `resume_complete` terminal status, which can fire for a still-running op the
+ * gateway DO has no live session for (e.g. heterogeneous CC) and must NOT clear.
*/
- onSessionComplete?: (info: { succeeded: boolean; terminalReceived: boolean }) => void;
+ onSessionComplete?: (info: {
+ authFailed: boolean;
+ succeeded: boolean;
+ terminalReceived: boolean;
+ }) => void;
/**
* The operation ID returned by execAgent
*/
@@ -187,10 +198,11 @@ export class GatewayActionImpl {
let receivedTerminalEvent = false;
let terminalSucceeded = false;
let sessionCompleted = false;
- const fireSessionComplete = () => {
+ const fireSessionComplete = (opts?: { authFailed?: boolean }) => {
if (sessionCompleted) return;
sessionCompleted = true;
onSessionComplete?.({
+ authFailed: opts?.authFailed ?? false,
succeeded: terminalSucceeded,
terminalReceived: receivedTerminalEvent,
});
@@ -240,7 +252,7 @@ export class GatewayActionImpl {
client.on('auth_failed', (reason) => {
console.error(`[Gateway] Auth failed for operation ${operationId}: ${reason}`);
this.internal_cleanupGatewayConnection(operationId);
- fireSessionComplete();
+ fireSessionComplete({ authFailed: true });
});
// Handle expired-but-recoverable auth: the JWT is past `exp` but the op
@@ -260,7 +272,9 @@ export class GatewayActionImpl {
console.error(`[Gateway] Token refresh failed for operation ${operationId}:`, error);
client.disconnect();
this.internal_cleanupGatewayConnection(operationId);
- fireSessionComplete();
+ // A rejected refresh means the gateway no longer accepts this op's token
+ // β€” treat it like auth_failed so reconnect callers clear the stale marker.
+ fireSessionComplete({ authFailed: true });
}
});
@@ -734,12 +748,30 @@ export class GatewayActionImpl {
this.#get().connectToGateway({
gatewayUrl: agentGatewayUrl,
onEvent: eventHandler,
- onSessionComplete: ({ succeeded, terminalReceived }) => {
- // See executeGatewayAgent's onSessionComplete: the handler owns op
- // completion via the run lifecycle; complete here only as the
- // terminal-missing fallback.
- if (!terminalReceived) this.#get().completeOperation(gatewayOpId);
+ onSessionComplete: ({ succeeded, terminalReceived, authFailed }) => {
this.#get().internal_updateTopicLoading(topicId, false);
+
+ // A reconnect is a passive re-subscribe β€” it must not END a run it merely
+ // re-subscribed to. Only finalize when the close PROVES the op is over:
+ // - terminalReceived: a real agent_runtime_end / error streamed in, or
+ // - authFailed: the gateway rejected the op's token (GC'd / gone).
+ // A bare `resume_complete` terminal *status* with neither is ambiguous β€”
+ // it also fires for a still-running op the gateway DO has no live session
+ // for (typically a heterogeneous CC run streaming via heteroIngest).
+ // Clearing runningOperation there would black-hole every subsequent
+ // heteroIngest batch (StaleHeteroOperationError) and silently kill the
+ // live agent, so leave the marker to the real terminal sites (heteroFinish
+ // / the inactivity watchdog) and just drop our local connection op.
+ if (!terminalReceived && !authFailed) {
+ this.#get().completeOperation(gatewayOpId);
+ return;
+ }
+
+ // The run lifecycle already completed the op when a terminal event
+ // arrived; an auth failure carries no such event, so finalize it here so
+ // the local op never sticks `running`.
+ if (authFailed) this.#get().completeOperation(gatewayOpId);
+
// See executeGatewayAgent's onSessionComplete: a clean background
// completion is left to markTopicUnread (status: 'unread').
const viewing = this.#get().activeTopicId === topicId;
@@ -750,6 +782,8 @@ export class GatewayActionImpl {
topicId,
});
}
+ // Clear the persisted marker useGatewayReconnect keys off so a dead op
+ // doesn't get reconnected on every reload / task-drawer open.
topicService.updateTopicMetadata(topicId, { runningOperation: null }).catch(() => {});
},
operationId,