π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(agent): prevent gateway init race for hetero runs (#18868)
Tsukie1069fad6f50
diff --git a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.tsindex aa8782f2c8f..56b4bee072f 100644--- a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts+++ b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts@@ -16,8 +16,9 @@ const POST_TIMEOUT = 5000; // 5s per requestconst MAX_INFLIGHT = 20; // bounded concurrency/**- * Decorator that wraps an IStreamEventManager and additionally- * pushes events to the Agent Gateway via HTTP (fire-and-forget).+ * Decorator that wraps an IStreamEventManager and additionally pushes events+ * to the Agent Gateway via HTTP. Runtime init is an awaited ordering barrier;+ * subsequent event delivery remains best-effort and mostly fire-and-forget.** Redis SSE remains the primary event storage / subscription mechanism.* The Gateway is an additional push channel for WebSocket delivery.@@ -110,10 +111,24 @@ export class GatewayStreamNotifier implements IStreamEventManager {log('mirror registered: %s β %s', operationId, mirrorTo);}- this.httpPost('/api/operations/init', {- operationId,- userId: initialState?.userId || 'unknown',- });+ // Ordering barrier: a subscriber connects immediately after execAgent+ // returns and asks the Gateway for the operation's authoritative status.+ // If init is still fire-and-forget, that resume can win the race and report+ // a live heterogeneous/device run as terminal before its first producer+ // event arrives. httpPost intentionally swallows Gateway failures, so+ // awaiting it preserves best-effort semantics while preventing the normal+ // success path from exposing an operation before the Gateway knows it. Init+ // uses the non-lossy request lane: ordinary stream events may be dropped at+ // MAX_INFLIGHT, but dropping this control-plane barrier would recreate the+ // exact resume-before-init race under load.+ try {+ await this.httpPostAwait('/api/operations/init', {+ operationId,+ userId: initialState?.userId || 'unknown',+ });+ } catch (error) {+ log('Gateway /api/operations/init failed: %O', error);+ }void this.pushEvent(operationId, {data: initialState,diff --git a/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.tsindex f1c10f3a471..ceb9003f974 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts@@ -159,6 +159,92 @@ describe('GatewayStreamNotifier', () => {expect(urls).toContain(`${gatewayUrl}/api/operations/init`);expect(urls).toContain(`${gatewayUrl}/api/operations/push-event`);});++ it('waits for gateway init before exposing the operation to subscribers', async () => {+ let resolveInit!: () => void;+ mockFetch.mockImplementation((url: string) => {+ if (url.endsWith('/api/operations/init')) {+ return new Promise((resolve) => {+ resolveInit = () => resolve({ ok: true, text: () => Promise.resolve('') });+ });+ }++ return Promise.resolve({ ok: true, text: () => Promise.resolve('') });+ });++ const result = notifier.publishAgentRuntimeInit('op-1', { userId: 'user-1' });+ let resolved = false;+ void result.then(() => {+ resolved = true;+ });++ await vi.waitFor(() => {+ expect(mockFetch).toHaveBeenCalledWith(+ `${gatewayUrl}/api/operations/init`,+ expect.objectContaining({ method: 'POST' }),+ );+ });+ expect(resolved).toBe(false);+ expect(mockFetch.mock.calls.map((call: any[]) => call[0])).not.toContain(+ `${gatewayUrl}/api/operations/push-event`,+ );++ resolveInit();++ await expect(result).resolves.toBe('publishAgentRuntimeInit-result');+ expect(resolved).toBe(true);+ await vi.waitFor(() => {+ expect(mockFetch.mock.calls.map((call: any[]) => call[0])).toContain(+ `${gatewayUrl}/api/operations/push-event`,+ );+ });+ });++ it('does not drop the awaited init when the event lane is saturated', async () => {+ const pending: Array<{+ resolve: () => void;+ url: string;+ }> = [];+ mockFetch.mockImplementation(+ (url: string) =>+ new Promise((resolve) => {+ pending.push({+ resolve: () => resolve({ ok: true, text: () => Promise.resolve('') }),+ url,+ });+ }),+ );++ for (let index = 0; index < 20; index++) {+ await notifier.publishStreamEvent(`op-event-${index}`, {+ data: {},+ stepIndex: 0,+ type: 'step_start',+ });+ }+ await vi.waitFor(() => expect(mockFetch).toHaveBeenCalledTimes(20));++ const result = notifier.publishAgentRuntimeInit('op-init', { userId: 'user-1' });+ let resolved = false;+ void result.then(() => {+ resolved = true;+ });++ await vi.waitFor(() => {+ expect(pending.some(({ url }) => url.endsWith('/api/operations/init'))).toBe(true);+ });+ expect(mockFetch).toHaveBeenCalledTimes(21);+ expect(resolved).toBe(false);++ pending.find(({ url }) => url.endsWith('/api/operations/init'))!.resolve();+ await expect(result).resolves.toBe('publishAgentRuntimeInit-result');++ for (const request of pending.filter(({ url }) =>+ url.endsWith('/api/operations/push-event'),+ )) {+ request.resolve();+ }+ });});describe('publishAgentRuntimeEnd', () => {diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.tsindex 64303516558..993c470854f 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts@@ -458,16 +458,23 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>type: 'claude-code',} as any;- await service.execAgent({+ const result = await service.execAgent({agentId: 'agent-1',prompt: 'Use the selected Claude Code model',});+ expect(result.heteroType).toBe('claude-code');expect(mockSpawnHeteroSandbox).toHaveBeenCalledWith(expect.objectContaining({args: ['--model', 'opus', '--effort', 'high'],}),);+ expect(topicMock.updateMetadata).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({+ runningOperation: expect.objectContaining({ heteroType: 'claude-code' }),+ }),+ );});it.each(['claude-code', 'codex'] as const)(diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.tsindex 5b190ce12ab..df1b610f843 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts@@ -550,6 +550,70 @@ describe('AiAgentService.execAgent - resumeApproval', () => {);});+ it('marks a reused ready continuation as a normal runtime', async () => {+ const approvalResolutionRequestId = '018fbd8e-7baf-7c6d-8000-000000000099';+ const identity = { resolutionRequestId: approvalResolutionRequestId, userId: 'user-1' };+ const continuationOperationId = deriveAgentInterventionContinuationOperationId(identity);+ const assistantMessageId = deriveAgentInterventionContinuationMessageId(identity);+ const provenance = {+ resolutionRequestId: approvalResolutionRequestId,+ sourceOperationId: 'op-parked',+ sourceToolMessageIds: ['tool-msg-1'],+ };+ mockFindMessagePlugin.mockResolvedValue({+ ...pendingToolPlugin,+ intervention: { operationId: 'op-parked', status: 'pending' },+ });+ mockLoadInterventionContinuationState.mockResolvedValue({+ metadata: {+ agentId: 'agent-1',+ agentInterventionContinuation: provenance,+ agentInterventionPreparation: {+ resolutionRequestId: approvalResolutionRequestId,+ state: 'ready',+ },+ sourceMessageId: 'tool-msg-1',+ topicId: 'topic-1',+ userId: 'user-1',+ },+ operationId: continuationOperationId,+ status: 'idle',+ });+ mockFindOperationById.mockResolvedValue({+ agentId: 'agent-1',+ appContext: { sourceMessageId: 'tool-msg-1' },+ metadata: { agentInterventionContinuation: provenance },+ topicId: 'topic-1',+ });+ mockFindById.mockImplementation(async (id: string) =>+ id === assistantMessageId+ ? { id, role: 'assistant', topicId: 'topic-1' }+ : id === pendingToolMessage.id+ ? pendingToolMessage+ : undefined,+ );++ await expect(+ service.execAgent({+ ...baseParams,+ approvalResolutionRequestId,+ approvalSourceOperationId: 'op-parked',+ resumeApproval: {+ decision: 'approved',+ parentMessageId: 'tool-msg-1',+ toolCallId: 'call_xyz',+ },+ }),+ ).resolves.toMatchObject({+ heteroType: null,+ operationId: continuationOperationId,+ success: true,+ });++ expect(mockEnsureInterventionContinuationStarted).toHaveBeenCalledWith(continuationOperationId);+ expect(mockCreateOperation).not.toHaveBeenCalled();+ });+it('uses a non-reentrant short fence for a thread continuation without replacing the main anchor', async () => {const approvalResolutionRequestId = '018fbd8e-7baf-7c6d-8000-000000000095';const reservationId = deriveAgentInterventionContinuationOperationId({diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex 333a1376540..dc77886f729 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -2405,6 +2405,7 @@ export class AiAgentService {assistantMessageId: continuationAssistantId,autoStarted: true,createdAt: now,+ heteroType: null,message: 'Agent intervention continuation already created',operationId: continuationOperationId,status: 'created',@@ -2976,6 +2977,7 @@ export class AiAgentService {// boundary in queue mode.const childOperation = {assistantMessageId: assistantMessageRecord.id,+ heteroType,hooks: serializedHooks,startedAt: new Date().toISOString(),...(isRemoteHetero && remoteDeviceId@@ -2983,7 +2985,6 @@ export class AiAgentService {deviceId: remoteDeviceId,deviceUserId: remoteDeviceUserId,deviceWorkspaceId: remoteDeviceWorkspaceId,- heteroType,}: {}),operationId,@@ -3495,6 +3496,7 @@ export class AiAgentService {assistantMessageId: assistantMessageRecord.id,autoStarted: true,createdAt: new Date().toISOString(),+ heteroType,message: 'Hetero agent dispatched successfully',operationId,status: 'created',@@ -5399,6 +5401,7 @@ export class AiAgentService {await this.topicModel.updateMetadata(topicId, {runningOperation: {assistantMessageId: assistantMessageRecord.id,+ heteroType: null,operationId,scope: appContext?.scope ?? undefined,// Liveness stamp β without it this marker can never be proven dead@@ -5424,6 +5427,7 @@ export class AiAgentService {assistantMessageId: assistantMessageRecord.id,autoStarted: result.autoStarted,createdAt: new Date().toISOString(),+ heteroType: null,message: 'Agent operation created successfully',messageId: result.messageId,operationId,diff --git a/packages/agent-gateway-client/src/client.test.ts b/packages/agent-gateway-client/src/client.test.tsindex 8922a30eb18..935eff57ab4 100644--- a/packages/agent-gateway-client/src/client.test.ts+++ b/packages/agent-gateway-client/src/client.test.ts@@ -355,6 +355,7 @@ describe('AgentStreamClient', () => {ws.simulateMessage({ type: 'session_complete' });expect(onComplete).toHaveBeenCalledOnce();+ expect(onComplete).toHaveBeenCalledWith({ source: 'raw_session_complete' });expect(client.connectionStatus).toBe('disconnected');});});@@ -434,6 +435,7 @@ describe('AgentStreamClient', () => {ws.simulateMessage({ status: 'completed', type: 'resume_complete' });expect(onComplete).toHaveBeenCalledOnce();+ expect(onComplete).toHaveBeenCalledWith({ source: 'resume_status', status: 'completed' });expect(client.connectionStatus).toBe('disconnected');});diff --git a/packages/agent-gateway-client/src/client.ts b/packages/agent-gateway-client/src/client.tsindex 80227b3ea96..1c1d60e2ba7 100644--- a/packages/agent-gateway-client/src/client.ts+++ b/packages/agent-gateway-client/src/client.ts@@ -341,7 +341,10 @@ export class AgentStreamClient extends TypedEmitter {if (terminal) {this.sessionEnded = true;- this.emit('session_complete');+ this.emit('session_complete', {+ source: 'resume_status',+ status: message.status,+ });this.disconnect();}// Non-terminal (running / waiting_input / waiting_confirmation): the@@ -357,7 +360,7 @@ export class AgentStreamClient extends TypedEmitter {if (this.resumeMode) {this.flushResumeBuffer();}- this.emit('session_complete');+ this.emit('session_complete', { source: 'raw_session_complete' });this.disconnect();break;}diff --git a/packages/agent-gateway-client/src/index.ts b/packages/agent-gateway-client/src/index.tsindex 62a8d18c34a..beb741b895a 100644--- a/packages/agent-gateway-client/src/index.ts+++ b/packages/agent-gateway-client/src/index.ts@@ -12,6 +12,7 @@ export type {AgentStreamClientOptions,AgentStreamEvent,AgentStreamEventType,+ AgentStreamSessionCompletion,ConnectionStatus,StepCompleteData,StreamChunkData,diff --git a/packages/agent-gateway-client/src/types.ts b/packages/agent-gateway-client/src/types.tsindex 6b621a1d656..98a42b0f44f 100644--- a/packages/agent-gateway-client/src/types.ts+++ b/packages/agent-gateway-client/src/types.ts@@ -402,6 +402,16 @@ export interface SessionCompleteMessage {export type SessionStatus ='running' | 'waiting_input' | 'waiting_confirmation' | 'completed' | 'error' | 'interrupted';+/** Provenance for a terminal session signal emitted by AgentStreamClient. */+export type AgentStreamSessionCompletion =+ | {+ source: 'raw_session_complete';+ }+ | {+ source: 'resume_status';+ status: Extract<SessionStatus, 'completed' | 'error' | 'interrupted'>;+ };+/*** Server β Client: sent right after a `resume` replay, carrying the DO's* authoritative `status` from storage. Because the DO's in-memory event buffer@@ -444,7 +454,7 @@ export interface AgentStreamClientEvents {disconnected: () => void;error: (error: Error) => void;reconnecting: (delay: number) => void;- session_complete: () => void;+ session_complete: (completion: AgentStreamSessionCompletion) => void;status_changed: (status: ConnectionStatus) => void;}diff --git a/packages/database/src/models/__tests__/topics/topic.update.test.ts b/packages/database/src/models/__tests__/topics/topic.update.test.tsindex 0b8eece4ce2..94374cd6f00 100644--- a/packages/database/src/models/__tests__/topics/topic.update.test.ts+++ b/packages/database/src/models/__tests__/topics/topic.update.test.ts@@ -614,6 +614,7 @@ describe('TopicModel - Update', () => {const topic = await topicModel.findById(topicId);expect(topic?.metadata?.runningOperation).toMatchObject({assistantMessageId: 'assistant-continuation',+ heteroType: null,operationId: 'operation-continuation',scope: 'main',});diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.tsindex d339688c697..946b4055b9f 100644--- a/packages/database/src/models/topic.ts+++ b/packages/database/src/models/topic.ts@@ -1901,6 +1901,7 @@ export class TopicModel {? {...(current?.operationId === params.continuationOperationId ? current : {}),assistantMessageId: params.assistantMessageId,+ heteroType: null,operationId: params.continuationOperationId,scope: params.scope ?? undefined,startedAt: params.startedAt,diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.tsindex 1b00d617ab4..17b90952426 100644--- a/packages/types/src/agentExecution/index.ts+++ b/packages/types/src/agentExecution/index.ts@@ -313,6 +313,12 @@ export interface ExecAgentResult {createdThreadId?: string;/** Error message if operation failed to start */error?: string;+ /**+ * External heterogeneous producer for this run. `null` explicitly denotes+ * the normal AgentRuntime path; `undefined` is reserved for rolling clients+ * talking to an older server that did not yet return this discriminator.+ */+ heteroType?: string | null;/** Status message */message: string;/** Queue message ID if auto-started */diff --git a/packages/types/src/task/index.ts b/packages/types/src/task/index.tsindex 4e920e974b7..c8cd72386fe 100644--- a/packages/types/src/task/index.ts+++ b/packages/types/src/task/index.ts@@ -425,6 +425,7 @@ export interface TaskDetailActivity {*/runningOperation?: {assistantMessageId: string;+ heteroType?: string | null;operationId: string;scope?: string;threadId?: string | null;diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.tsindex 126f1866b79..17db3b6f399 100644--- a/packages/types/src/topic/topic.ts+++ b/packages/types/src/topic/topic.ts@@ -234,7 +234,7 @@ export interface ChatTopicMetadata {deviceId?: string;deviceUserId?: string;deviceWorkspaceId?: string;- heteroType?: string;+ heteroType?: string | null;hooks?: SerializedAgentHook[];operationId: string;orchestrationRole?: 'supervisor' | 'member';@@ -248,7 +248,7 @@ export interface ChatTopicMetadata {/** Workspace principal used for a workspace-enrolled device. */deviceWorkspaceId?: string;/** Notify-based platform type used to select the cancellation protocol. */- heteroType?: string;+ heteroType?: string | null;/*** Serialized lifecycle hooks (onComplete / onError) registered for this run.*@@ -524,7 +524,7 @@ export const chatTopicMetadataUpdateSchema = z.object({deviceId: z.string().optional(),deviceUserId: z.string().optional(),deviceWorkspaceId: z.string().optional(),- heteroType: z.string().optional(),+ heteroType: z.string().nullable().optional(),hooks: z.array(serializedAgentHookSchema).optional(),operationId: z.string(),orchestrationRole: z.enum(['supervisor', 'member']).optional(),@@ -536,7 +536,7 @@ export const chatTopicMetadataUpdateSchema = z.object({deviceId: z.string().optional(),deviceUserId: z.string().optional(),deviceWorkspaceId: z.string().optional(),- heteroType: z.string().optional(),+ heteroType: z.string().nullable().optional(),hooks: z.array(serializedAgentHookSchema).optional(),operationId: z.string(),orchestrationRole: z.enum(['supervisor', 'member']).optional(),diff --git a/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.test.tsx b/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.test.tsxindex 92b09309b20..a6190f58ad6 100644--- a/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.test.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.test.tsx@@ -275,7 +275,11 @@ describe('TopicChatDrawer', () => {it('reconnects a running topic against the drawer agent', () => {mocks.taskState.taskDetailMap['T-1'].activities[0] = {id: 'topic-1',- runningOperation: { assistantMessageId: 'ast-1', operationId: 'op-1' },+ runningOperation: {+ assistantMessageId: 'ast-1',+ heteroType: 'claude-code',+ operationId: 'op-1',+ },status: 'running',time: '2026-04-29T00:00:00.000Z',title: 'Topic 1',@@ -286,7 +290,7 @@ describe('TopicChatDrawer', () => {expect(useGatewayReconnect).toHaveBeenCalledWith('topic-1',- expect.objectContaining({ operationId: 'op-1' }),+ expect.objectContaining({ heteroType: 'claude-code', operationId: 'op-1' }),'agt_assignee',);});diff --git a/src/hooks/useGatewayReconnect.ts b/src/hooks/useGatewayReconnect.tsindex d8aa5bc5cce..e9c232cc9ea 100644--- a/src/hooks/useGatewayReconnect.ts+++ b/src/hooks/useGatewayReconnect.ts@@ -7,6 +7,7 @@ import { isTrpcErrorCode } from '@/utils/trpcError';interface RunningOperation {assistantMessageId: string;+ heteroType?: string | null;operationId: string;scope?: string;threadId?: string | null;@@ -48,6 +49,7 @@ export const useGatewayReconnect = (await useChatStore.getState().reconnectToGatewayOperation({agentId,assistantMessageId: runningOperation.assistantMessageId,+ heteroType: runningOperation.heteroType,operationId: runningOperation.operationId,scope: runningOperation.scope,threadId: runningOperation.threadId,diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.tsindex de58277f841..95b85c6546c 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts@@ -302,9 +302,15 @@ describe('GatewayActionImpl', () => {topicId: TEST_TOPIC_ID,});- mockClient.emitEvent('session_complete');+ mockClient.emitEvent('session_complete', { source: 'raw_session_complete' });expect(state.gatewayConnections['op-1']).toBeUndefined();expect(onComplete).toHaveBeenCalledOnce();+ expect(onComplete).toHaveBeenCalledWith({+ authFailed: false,+ completion: { source: 'raw_session_complete' },+ succeeded: false,+ terminalReceived: false,+ });});it('should cleanup on disconnected', () => {@@ -1423,6 +1429,7 @@ describe('GatewayActionImpl', () => {assistantMessageId: 'ast-1',autoStarted: true,createdAt: new Date().toISOString(),+ heteroType: null,message: 'ok',operationId: 'server-op-1',status: 'created',@@ -1438,6 +1445,20 @@ describe('GatewayActionImpl', () => {message: 'Hello',});+ expect(internalDispatchTopic).toHaveBeenCalledWith(+ expect.objectContaining({+ value: expect.objectContaining({+ metadata: expect.objectContaining({+ runningOperation: {+ assistantMessageId: 'ast-1',+ heteroType: null,+ operationId: 'server-op-1',+ },+ }),+ }),+ }),+ );+const { onSessionComplete } = connectToGateway.mock.calls[0][0];// Ignore any dispatches / writes from the optimistic-update path during setup.internalDispatchTopic.mockClear();@@ -1456,6 +1477,149 @@ describe('GatewayActionImpl', () => {expect(updateTopicStatus).not.toHaveBeenCalled();});+ it('preserves only external-producer resume status without a terminal event', async () => {+ const runCompletion = async ({+ activeTopicId = 'topic-1',+ authFailed = false,+ completion,+ heteroType,+ }: {+ activeTopicId?: string | null;+ authFailed?: boolean;+ completion:+ { source: 'raw_session_complete' } | { source: 'resume_status'; status: 'completed' };+ heteroType: string | null | undefined;+ }) => {+ const connectToGateway = vi.fn();+ const completeOperation = vi.fn();+ const internalDispatchTopic = vi.fn();+ const startOperation = vi.fn(() => ({ operationId: 'gw-op-1' }));+ const state: Record<string, any> = {+ activeAgentId: 'agent-1',+ activeTopicId,+ gatewayConnections: {},+ topicDataMap: {+ 'agent_agent-1': {+ items: [+ {+ id: 'topic-1',+ metadata: {+ runningOperation: { assistantMessageId: 'ast-1', operationId: 'server-op-1' },+ },+ status: 'running',+ },+ ],+ },+ },+ };+ 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,+ internal_dispatchTopic: internalDispatchTopic,+ moveQueuedMessages: vi.fn(),+ moveVoiceMessages: vi.fn(),+ onOperationCancel: vi.fn(),+ startOperation,+ updateTopicStatus: vi.fn(),+ })) as any;++ (globalThis as any).window = {+ global_serverConfigStore: {+ getState: () => ({ serverConfig: { agentGatewayUrl: 'https://gateway.test.com' } }),+ },+ };++ const action = new GatewayActionImpl(set as any, get, undefined);+ action.createClient = vi.fn(() => createMockClient());++ vi.mocked(aiAgentService.execAgentTask).mockResolvedValue({+ agentId: 'agent-1',+ assistantMessageId: 'ast-1',+ autoStarted: true,+ createdAt: new Date().toISOString(),+ heteroType,+ message: 'ok',+ operationId: 'server-op-1',+ status: 'created',+ success: true,+ timestamp: new Date().toISOString(),+ token: 'test-token',+ topicId: 'topic-1',+ userMessageId: 'usr-1',+ });++ await action.executeGatewayAgent({+ context: { agentId: 'agent-1', scope: 'main', threadId: null, topicId: 'topic-1' },+ message: 'Hello',+ });++ const { onSessionComplete } = connectToGateway.mock.calls[0][0];+ completeOperation.mockClear();+ internalDispatchTopic.mockClear();+ vi.mocked(topicService.settleRunningOperation).mockClear();++ onSessionComplete({ authFailed, completion, succeeded: false, terminalReceived: false });++ return { completeOperation, internalDispatchTopic };+ };++ const heteroResume = await runCompletion({+ completion: { source: 'resume_status', status: 'completed' },+ heteroType: 'claude-code',+ });+ expect(heteroResume.completeOperation).toHaveBeenCalledWith('gw-op-1');+ expect(topicService.settleRunningOperation).not.toHaveBeenCalled();+ expect(heteroResume.internalDispatchTopic).not.toHaveBeenCalled();++ const rollingUnknown = await runCompletion({+ completion: { source: 'resume_status', status: 'completed' },+ heteroType: undefined,+ });+ expect(topicService.settleRunningOperation).not.toHaveBeenCalled();+ expect(rollingUnknown.internalDispatchTopic).not.toHaveBeenCalled();++ const normalResume = await runCompletion({+ completion: { source: 'resume_status', status: 'completed' },+ heteroType: null,+ });+ expect(topicService.settleRunningOperation).toHaveBeenCalledWith(+ 'topic-1',+ 'server-op-1',+ 'active',+ );+ expect(normalResume.internalDispatchTopic).toHaveBeenCalled();++ await runCompletion({+ activeTopicId: 'some-other-topic',+ completion: { source: 'resume_status', status: 'completed' },+ heteroType: null,+ });+ expect(topicService.settleRunningOperation).toHaveBeenCalledWith(+ 'topic-1',+ 'server-op-1',+ 'unread',+ );++ await runCompletion({+ completion: { source: 'raw_session_complete' },+ heteroType: 'claude-code',+ });+ expect(topicService.settleRunningOperation).toHaveBeenCalled();++ await runCompletion({+ authFailed: true,+ completion: { source: 'resume_status', status: 'completed' },+ heteroType: 'claude-code',+ });+ expect(topicService.settleRunningOperation).toHaveBeenCalled();+ });+// Regression guard: a successful run the user is watching must reset the// topic's local `status` back to 'active', not just clear the metadata// marker. `settleRunningOperation` above writes this to the DB, but it@@ -2024,12 +2188,13 @@ describe('GatewayActionImpl', () => {// 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 () => {+ it('does NOT clear runningOperation on a heterogeneous terminal resume status', async () => {const { action, captured, completeOperation, updateTopicStatus } =createOnSessionCompleteHarness();await action.reconnectToGatewayOperation({assistantMessageId: 'ast-1',+ heteroType: 'claude-code',operationId: 'server-op-1',topicId: 'topic-1',});@@ -2037,13 +2202,85 @@ describe('GatewayActionImpl', () => {vi.mocked(topicService.updateTopicMetadata).mockClear().mockResolvedValue(undefined as never);- captured.onSessionComplete!({ authFailed: false, succeeded: false, terminalReceived: false });+ captured.onSessionComplete!({+ authFailed: false,+ completion: { source: 'resume_status', status: 'completed' },+ succeeded: false,+ terminalReceived: false,+ });expect(completeOperation).toHaveBeenCalledWith('gw-op-reconnect');expect(topicService.updateTopicMetadata).not.toHaveBeenCalled();expect(updateTopicStatus).not.toHaveBeenCalled();});+ it('preserves an unknown rolling marker on terminal resume status', async () => {+ const { action, captured, completeOperation } = createOnSessionCompleteHarness();++ await action.reconnectToGatewayOperation({+ assistantMessageId: 'ast-1',+ operationId: 'server-op-1',+ topicId: 'topic-1',+ });++ vi.mocked(topicService.settleRunningOperation).mockClear();+ captured.onSessionComplete!({+ authFailed: false,+ completion: { source: 'resume_status', status: 'completed' },+ succeeded: false,+ terminalReceived: false,+ });++ expect(completeOperation).toHaveBeenCalledWith('gw-op-reconnect');+ expect(topicService.settleRunningOperation).not.toHaveBeenCalled();+ });++ it('settles normal runtime and raw heterogeneous session completions', async () => {+ const normal = createOnSessionCompleteHarness();+ await normal.action.reconnectToGatewayOperation({+ assistantMessageId: 'ast-1',+ heteroType: null,+ operationId: 'server-op-1',+ topicId: 'topic-1',+ });++ vi.mocked(topicService.settleRunningOperation).mockClear();+ normal.captured.onSessionComplete!({+ authFailed: false,+ completion: { source: 'resume_status', status: 'completed' },+ succeeded: false,+ terminalReceived: false,+ });+ expect(normal.completeOperation).toHaveBeenCalledWith('gw-op-reconnect');+ expect(topicService.settleRunningOperation).toHaveBeenCalledWith(+ 'topic-1',+ 'server-op-1',+ 'active',+ );++ const rawHetero = createOnSessionCompleteHarness();+ await rawHetero.action.reconnectToGatewayOperation({+ assistantMessageId: 'ast-1',+ heteroType: 'claude-code',+ operationId: 'server-op-1',+ topicId: 'topic-1',+ });++ vi.mocked(topicService.settleRunningOperation).mockClear();+ rawHetero.captured.onSessionComplete!({+ authFailed: false,+ completion: { source: 'raw_session_complete' },+ succeeded: false,+ terminalReceived: false,+ });+ expect(rawHetero.completeOperation).toHaveBeenCalledWith('gw-op-reconnect');+ expect(topicService.settleRunningOperation).toHaveBeenCalledWith(+ 'topic-1',+ 'server-op-1',+ 'active',+ );+ });+// 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 () => {@@ -2142,6 +2379,35 @@ describe('GatewayActionImpl', () => {expect(topicService.updateTopicMetadata).not.toHaveBeenCalled();});+ it('settles a completed normal resume status to unread when off-topic', async () => {+ const { action, captured } = createOnSessionCompleteHarness({+ activeTopicId: 'some-other-topic',+ });++ await action.reconnectToGatewayOperation({+ assistantMessageId: 'ast-1',+ heteroType: null,+ operationId: 'server-op-1',+ topicId: 'topic-1',+ });++ vi.mocked(topicService.settleRunningOperation)+ .mockClear()+ .mockResolvedValue(undefined as never);+ captured.onSessionComplete!({+ authFailed: false,+ completion: { source: 'resume_status', status: 'completed' },+ succeeded: false,+ terminalReceived: false,+ });++ expect(topicService.settleRunningOperation).toHaveBeenCalledWith(+ 'topic-1',+ 'server-op-1',+ 'unread',+ );+ });+// Seeds a topic whose local metadata still carries a runningOperation, wires up// internal_dispatchTopic + connectToGateway capture, so we can assert the local// store clear on both the NOT_FOUND refresh path and onSessionComplete.@@ -2273,19 +2539,25 @@ describe('GatewayActionImpl', () => {});});- // An ambiguous close (no terminal event, no auth failure) must NOT clear the- // local marker β same black-hole guard as the server-side clear.- it('does NOT clear the local marker on an ambiguous reconnect close', async () => {+ // A heterogeneous terminal resume status must NOT clear the local marker β+ // same black-hole guard as the server-side clear.+ it('does NOT clear the local marker on a heterogeneous resume status', async () => {const { action, captured, internalDispatchTopic } = createSeededReconnectHarness();await action.reconnectToGatewayOperation({assistantMessageId: 'ast-1',+ heteroType: 'claude-code',operationId: 'server-op-1',topicId: 'topic-1',});internalDispatchTopic.mockClear();- captured.onSessionComplete!({ authFailed: false, succeeded: true, terminalReceived: false });+ captured.onSessionComplete!({+ authFailed: false,+ completion: { source: 'resume_status', status: 'completed' },+ succeeded: true,+ terminalReceived: false,+ });expect(internalDispatchTopic).not.toHaveBeenCalled();});diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex e8fd4e477bb..6577f89feaa 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -2,6 +2,7 @@ import {AgentStreamClient,type AgentStreamClientOptions,type AgentStreamEvent,+ type AgentStreamSessionCompletion,type ConnectionStatus,} from '@lobechat/agent-gateway-client';import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';@@ -180,6 +181,10 @@ export interface ConnectGatewayParams {* completion's `markTopicUnread` and this terminal `active` write* partition the cases by `succeeded && !viewing`).*+ * `completion` identifies a raw session close versus an authoritative terminal+ * resume status. It is absent when auth failure or a terminal agent event drove+ * cleanup.+ ** `terminalReceived` is true when a terminal agent event (`agent_runtime_end` /* `error`) was processed β meaning the gateway event handler already completed* the op via the shared run lifecycle, so `onSessionComplete` is pure transport@@ -196,6 +201,7 @@ export interface ConnectGatewayParams {*/onSessionComplete?: (info: {authFailed: boolean;+ completion?: AgentStreamSessionCompletion;succeeded: boolean;terminalReceived: boolean;}) => void;@@ -219,6 +225,16 @@ export interface ConnectGatewayParams {topicId: string;}+const isSuccessfulGatewayCompletion = (params: {+ authFailed: boolean;+ completion?: AgentStreamSessionCompletion;+ succeeded: boolean;+}): boolean =>+ params.succeeded ||+ (!params.authFailed &&+ params.completion?.source === 'resume_status' &&+ params.completion.status === 'completed');+// βββ Action Implementation βββexport class GatewayActionImpl {@@ -282,12 +298,16 @@ export class GatewayActionImpl {let terminalSucceeded = false;let sessionCompleted = false;const eventBuffer = createGatewayEventBuffer((event) => onEvent?.(event));- const fireSessionComplete = (opts?: { authFailed?: boolean }) => {+ const fireSessionComplete = (opts?: {+ authFailed?: boolean;+ completion?: AgentStreamSessionCompletion;+ }) => {if (sessionCompleted) return;sessionCompleted = true;eventBuffer.flush();onSessionComplete?.({authFailed: opts?.authFailed ?? false,+ completion: opts?.completion,succeeded: terminalSucceeded,terminalReceived: receivedTerminalEvent,});@@ -320,9 +340,9 @@ export class GatewayActionImpl {});// Handle session completion- client.on('session_complete', () => {+ client.on('session_complete', (completion) => {this.internal_cleanupGatewayConnection(operationId);- fireSessionComplete();+ fireSessionComplete({ completion });});// Handle disconnection β only fire session complete if a terminal agent event@@ -869,6 +889,7 @@ export class GatewayActionImpl {...existingTopic?.metadata,runningOperation: {assistantMessageId: result.assistantMessageId,+ heteroType: result.heteroType,operationId: result.operationId,},},@@ -926,11 +947,31 @@ export class GatewayActionImpl {this.#get().connectToGateway({gatewayUrl: agentGatewayUrl,onEvent: eventRouter,- onSessionComplete: ({ succeeded, terminalReceived }) => {+ onSessionComplete: ({ authFailed, completion, succeeded, terminalReceived }) => {// The gateway event handler already completed the op via the shared run// lifecycle on `agent_runtime_end` / `error`. Only complete here as the// terminal-missing fallback so the op never sticks `running`.if (!terminalReceived) this.#get().completeOperation(gatewayOpId);++ // A terminal resume status is ambiguous only for an external hetero+ // producer: an older or degraded Gateway may have no initialized DO+ // session while the CLI is still alive and streaming via heteroIngest.+ // Preserve unknown (`undefined`) during rolling deploys; new normal+ // runtimes explicitly return `heteroType: null`. A raw session_complete,+ // real terminal event, or auth failure remains authoritative.+ const preserveExternalProducer =+ !terminalReceived &&+ !authFailed &&+ completion?.source === 'resume_status' &&+ result.heteroType !== null;+ if (preserveExternalProducer) return;++ const effectiveSucceeded = isSuccessfulGatewayCompletion({+ authFailed,+ completion,+ succeeded,+ });+if (result.topicId) {// The server already settled this topic: the runtime's `finish`// executor settles to 'unread' before it publishes the terminal event@@ -947,7 +988,7 @@ export class GatewayActionImpl {.settleRunningOperation(result.topicId,result.operationId,- viewing || !succeeded ? 'active' : 'unread',+ viewing || !effectiveSucceeded ? 'active' : 'unread',).catch(console.error);// Also clear the local store copy β the server settle above does NOT@@ -960,7 +1001,7 @@ export class GatewayActionImpl {agentId: resolvedMessageContext.agentId,groupId: resolvedMessageContext.groupId,operationId: result.operationId,- status: viewing || !succeeded ? 'active' : undefined,+ status: viewing || !effectiveSucceeded ? 'active' : undefined,topicId: result.topicId,});}@@ -989,12 +1030,13 @@ export class GatewayActionImpl {*/agentId?: string;assistantMessageId: string;+ heteroType?: string | null;operationId: string;scope?: string;threadId?: string | null;topicId: string;}): Promise<void> => {- const { assistantMessageId, operationId, topicId, scope, threadId } = params;+ const { assistantMessageId, heteroType, operationId, topicId, scope, threadId } = params;const agentGatewayUrl =window.global_serverConfigStore?.getState()?.serverConfig?.agentGatewayUrl;@@ -1116,27 +1158,33 @@ export class GatewayActionImpl {this.#get().connectToGateway({gatewayUrl: agentGatewayUrl,onEvent: eventRouter,- onSessionComplete: ({ succeeded, terminalReceived, authFailed }) => {- // 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);+ onSessionComplete: ({ authFailed, completion, succeeded, terminalReceived }) => {+ // A reconnect-local operation has no remaining work once the session+ // completion callback fires. Real streamed terminals are completed by+ // the shared run lifecycle; every terminal-missing fallback (including+ // the preserved external producer case below) must close it here.+ if (!terminalReceived) this.#get().completeOperation(gatewayOpId);++ // A reconnect is passive. Preserve only an external/rolling-unknown+ // producer whose terminal resume status may mean "Gateway session was+ // never initialized" rather than "producer ended". New normal runtime+ // markers carry `heteroType: null`; old markers omit the field, so the+ // rolling-deploy fallback is deliberately fail-safe. Raw session_complete,+ // terminal events and auth failures are authoritative and settle below.+ const preserveExternalProducer =+ !terminalReceived &&+ !authFailed &&+ completion?.source === 'resume_status' &&+ heteroType !== null;+ if (preserveExternalProducer) {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);+ const effectiveSucceeded = isSuccessfulGatewayCompletion({+ authFailed,+ completion,+ succeeded,+ });// Same supersede guard as executeGatewayAgent's onSessionComplete: a// newer run may own this topic by now, and the settle below would@@ -1173,7 +1221,7 @@ export class GatewayActionImpl {.settleRunningOperation(topicId,operationId,- viewing || !succeeded ? 'active' : 'unread',+ viewing || !effectiveSucceeded ? 'active' : 'unread',).catch(console.error);}@@ -1184,7 +1232,7 @@ export class GatewayActionImpl {this.clearLocalRunningOperation({agentId: context.agentId,operationId,- status: viewing || !succeeded ? 'active' : undefined,+ status: viewing || !effectiveSucceeded ? 'active' : undefined,topicId,});},