π€― 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(gateway): retire the topic row once the server confirms a stop (#19928)
Arvin Xua183c53de7dc
diff --git a/packages/agent-gateway-client/PROTOCOL_V2.md b/packages/agent-gateway-client/PROTOCOL_V2.mdindex 67ebeb832bd..25e533f84d7 100644--- a/packages/agent-gateway-client/PROTOCOL_V2.md+++ b/packages/agent-gateway-client/PROTOCOL_V2.md@@ -156,7 +156,10 @@ Existing routes unchanged. New:status in the lifecycle notification only.Leave `interrupt` as-is (documented no-op; the web client interrupts via tRPC). Do not-attempt to implement it.+attempt to implement it. The hub still accepts and forwards the frame for wire+compatibility, but no client in this repo sends one: `sendInterrupt` was removed from both+`AgentStreamClient` and `OperationSubscription` so nothing can be wired to a stop that the+op DO silently drops.### 3.2 Init metadata@@ -325,7 +328,6 @@ interface OperationSubscription {on<K extends keyof AgentStreamClientEvents>(event: K, cb: AgentStreamClientEvents[K]): () => void;// plus 'resume_complete': (info: { status?: SessionStatus; gap: boolean; pending?: boolean }) => voidsendToolResult(result: ToolResultPayload): boolean; // queued while disconnected, TTL 120s- sendInterrupt(): boolean;unsubscribe(): void;}```@@ -348,7 +350,7 @@ Behavior:- `createOperationClient(mux, operationId, { resumeOnConnect?, lastEventId?, executor? })`returns an object structurally compatible with the store's`GatewayConnection['client']` Pick (`connect`, `disconnect`, `on`, `reconnect`,- `sendInterrupt`, `sendToolResult`, `updateToken`): `connect` = subscribe, `disconnect` =+ `sendToolResult`, `updateToken`): `connect` = subscribe, `disconnect` =unsubscribe, `reconnect` = unsubscribe+subscribe with lastEventId, `updateToken` = no-op(token comes from `getToken`). Emits the same `AgentStreamClientEvents`(`connected` when `resume_complete`/first event arrives or immediately if the socket isdiff --git a/packages/agent-gateway-client/src/client.test.ts b/packages/agent-gateway-client/src/client.test.tsindex 935eff57ab4..14c68c17ce9 100644--- a/packages/agent-gateway-client/src/client.test.ts+++ b/packages/agent-gateway-client/src/client.test.ts@@ -570,18 +570,6 @@ describe('AgentStreamClient', () => {});});- describe('interrupt', () => {- it('should send interrupt message', async () => {- const client = createClient();- const ws = await connectAndAuth(client);-- client.sendInterrupt();- const interruptMsg = ws.sent.find((s) => JSON.parse(s).type === 'interrupt');- expect(interruptMsg).toBeDefined();- expect(JSON.parse(interruptMsg!)).toEqual({ type: 'interrupt' });- });- });-describe('sendToolResult', () => {it('should send a successful tool_result message', async () => {const client = createClient();diff --git a/packages/agent-gateway-client/src/client.ts b/packages/agent-gateway-client/src/client.tsindex 1c1d60e2ba7..5e3677a8022 100644--- a/packages/agent-gateway-client/src/client.ts+++ b/packages/agent-gateway-client/src/client.ts@@ -139,13 +139,6 @@ export class AgentStreamClient extends TypedEmitter {this.emit('disconnected');}- /**- * Send an interrupt command to stop the running agent.- */- sendInterrupt(): void {- this.sendMessage({ type: 'interrupt' });- }-/*** Send a tool execution result back to the server.* Correlated by toolCallId; the server's agent loop is blocked on BLPOP until this arrives.diff --git a/packages/agent-gateway-client/src/index.ts b/packages/agent-gateway-client/src/index.tsindex 5198a9df52f..817e095db39 100644--- a/packages/agent-gateway-client/src/index.ts+++ b/packages/agent-gateway-client/src/index.ts@@ -17,7 +17,6 @@ export type {MuxHeartbeatAckMessage,MuxHeartbeatMessage,MuxInputRequestMessage,- MuxInterruptMessage,MuxOperationMessage,MuxOperationMeta,MuxOpLifecycleMessage,diff --git a/packages/agent-gateway-client/src/mux/GatewayMuxClient.test.ts b/packages/agent-gateway-client/src/mux/GatewayMuxClient.test.tsindex 76295b4fd48..9599fb2e263 100644--- a/packages/agent-gateway-client/src/mux/GatewayMuxClient.test.ts+++ b/packages/agent-gateway-client/src/mux/GatewayMuxClient.test.ts@@ -671,7 +671,7 @@ describe('GatewayMuxClient', () => {});describe('outbound op messages', () => {- it('sends tool_result and interrupt with the operationId', async () => {+ it('sends tool_result with the operationId', async () => {const { mux } = createMux();const ws = await connectAndReady(mux);const sub = mux.subscribe('op-1');@@ -679,7 +679,6 @@ describe('GatewayMuxClient', () => {expect(sub.sendToolResult({ content: '{"ok":true}', success: true, toolCallId: 'call_1' }),).toBe(true);- expect(sub.sendInterrupt()).toBe(true);expect(ws.ofType('tool_result')).toEqual([{@@ -690,7 +689,9 @@ describe('GatewayMuxClient', () => {type: 'tool_result',},]);- expect(ws.ofType('interrupt')).toEqual([{ operationId: 'op-1', type: 'interrupt' }]);+ // A subscription has no way to send `interrupt`: the op DO ignores the+ // frame, so cancellation goes through `aiAgent.interruptTask` instead.+ expect(ws.ofType('interrupt')).toEqual([]);});it('queues tool_result while disconnected and flushes after resubscribe', async () => {@@ -703,7 +704,6 @@ describe('GatewayMuxClient', () => {expect(sub.sendToolResult({ content: 'late', success: true, toolCallId: 'call_1' })).toBe(true,);- expect(sub.sendInterrupt()).toBe(false);await vi.advanceTimersByTimeAsync(500);const ws2 = await settle();@@ -748,7 +748,6 @@ describe('GatewayMuxClient', () => {const sub = mux.subscribe('op-1');sub.unsubscribe();expect(sub.sendToolResult({ content: null, success: false, toolCallId: 'x' })).toBe(false);- expect(sub.sendInterrupt()).toBe(false);});});diff --git a/packages/agent-gateway-client/src/mux/GatewayMuxClient.ts b/packages/agent-gateway-client/src/mux/GatewayMuxClient.tsindex ba6ba5b5284..97570ad9c11 100644--- a/packages/agent-gateway-client/src/mux/GatewayMuxClient.ts+++ b/packages/agent-gateway-client/src/mux/GatewayMuxClient.ts@@ -136,11 +136,6 @@ class OperationSubscriptionImpl implements OperationSubscription {});}- sendInterrupt(): boolean {- if (!this._active) return false;- return this.mux.sendForSubscription(this, { operationId: this.operationId, type: 'interrupt' });- }-sendToolConfirmation(toolCallId: string, approved: boolean): boolean {if (!this._active) return false;return this.mux.sendForSubscription(this, {diff --git a/packages/agent-gateway-client/src/mux/createOperationClient.test.ts b/packages/agent-gateway-client/src/mux/createOperationClient.test.tsindex bc92ea0922a..fd03eb1bfd1 100644--- a/packages/agent-gateway-client/src/mux/createOperationClient.test.ts+++ b/packages/agent-gateway-client/src/mux/createOperationClient.test.ts@@ -139,7 +139,7 @@ const agentEvent = (/** The store's `GatewayConnection['client']` contract (kept in sync by hand). */type StoreClient = Pick<AgentStreamClient,- 'connect' | 'disconnect' | 'on' | 'reconnect' | 'sendInterrupt' | 'sendToolResult' | 'updateToken'+ 'connect' | 'disconnect' | 'on' | 'reconnect' | 'sendToolResult' | 'updateToken'>;describe('createOperationClient', () => {@@ -323,7 +323,7 @@ describe('createOperationClient', () => {]);});- it('sendToolResult / sendInterrupt go out with the operationId; false before connect', async () => {+ it('sendToolResult goes out with the operationId; false before connect', async () => {const mux = createMux();const ws = await readyMux(mux);const client = createOperationClient(mux, 'op-1');@@ -334,8 +334,6 @@ describe('createOperationClient', () => {expect(client.sendToolResult({ content: '{"a":1}', success: true, toolCallId: 'call_1' })).toBe(true,);- client.sendInterrupt();-expect(ws.ofType('tool_result')).toEqual([{content: '{"a":1}',@@ -345,7 +343,9 @@ describe('createOperationClient', () => {type: 'tool_result',},]);- expect(ws.ofType('interrupt')).toEqual([{ operationId: 'op-1', type: 'interrupt' }]);+ // No client here can send `interrupt`: the op DO ignores it and a stop+ // must go through `aiAgent.interruptTask` instead.+ expect(ws.ofType('interrupt')).toEqual([]);});it('socket loss surfaces reconnecting, not disconnected; resubscribes after reconnect', async () => {diff --git a/packages/agent-gateway-client/src/mux/createOperationClient.ts b/packages/agent-gateway-client/src/mux/createOperationClient.tsindex 3ee333b6624..68bd742c2fd 100644--- a/packages/agent-gateway-client/src/mux/createOperationClient.ts+++ b/packages/agent-gateway-client/src/mux/createOperationClient.ts@@ -20,7 +20,7 @@ export interface OperationClientOptions {/*** Structurally compatible with the store's- * `Pick<AgentStreamClient, 'connect' | 'disconnect' | 'on' | 'reconnect' | 'sendInterrupt' | 'sendToolResult' | 'updateToken'>`.+ * `Pick<AgentStreamClient, 'connect' | 'disconnect' | 'on' | 'reconnect' | 'sendToolResult' | 'updateToken'>`.*/export interface OperationClient {/** Subscribe this operation on the shared socket (idempotent while active). */@@ -34,7 +34,6 @@ export interface OperationClient {) => () => void;/** Unsubscribe + resubscribe from the last applied event id. */reconnect: () => Promise<void>;- sendInterrupt: () => void;sendToolResult: (result: ToolResultPayload) => boolean;/** No-op: the mux fetches a fresh token via `getToken` on every dial. */updateToken: (token: string) => void;@@ -157,9 +156,6 @@ export const createOperationClient = (release();connect();},- sendInterrupt: () => {- subscription?.sendInterrupt();- },sendToolResult: (result) => subscription?.sendToolResult(result) ?? false,updateToken: () => {},};diff --git a/packages/agent-gateway-client/src/mux/types.ts b/packages/agent-gateway-client/src/mux/types.tsindex 8cf57599977..c25cc44c002 100644--- a/packages/agent-gateway-client/src/mux/types.ts+++ b/packages/agent-gateway-client/src/mux/types.ts@@ -44,14 +44,9 @@ export interface MuxUserInputMessage {type: 'user_input';}-export interface MuxInterruptMessage {- operationId: string;- type: 'interrupt';-}-+/** See `ClientMessage` in ../types for why `interrupt` is not sendable here. */export type MuxClientMessage =| MuxHeartbeatMessage- | MuxInterruptMessage| MuxSubscribeMessage| MuxToolConfirmationMessage| MuxToolResultMessage@@ -246,7 +241,6 @@ export interface OperationSubscription {listener: OperationSubscriptionEvents[K],) => () => void;operationId: string;- sendInterrupt: () => boolean;sendToolConfirmation: (toolCallId: string, approved: boolean) => boolean;/** Queued while the socket is down (TTL 120s) and flushed after resubscribe. */sendToolResult: (result: ToolResultPayload) => boolean;diff --git a/packages/agent-gateway-client/src/types.ts b/packages/agent-gateway-client/src/types.tsindex 81751070cc3..b9b5a7e1240 100644--- a/packages/agent-gateway-client/src/types.ts+++ b/packages/agent-gateway-client/src/types.ts@@ -356,10 +356,6 @@ export interface HeartbeatMessage {type: 'heartbeat';}-export interface InterruptMessage {- type: 'interrupt';-}-/*** Client β Server: tool execution result, correlated by toolCallId.*/@@ -383,8 +379,13 @@ export interface ToolResultMessage {workRegistration?: any;}-export type ClientMessage =- AuthMessage | HeartbeatMessage | InterruptMessage | ResumeMessage | ToolResultMessage;+/**+ * The gateway also accepts an `interrupt` frame, but its op DO ignores it and+ * a stop needs server-side work the socket cannot do (cancelling device/hetero+ * processes, settling the operation and topic rows). Cancellation therefore+ * goes through `aiAgent.interruptTask`, and no client here ever sends one.+ */+export type ClientMessage = AuthMessage | HeartbeatMessage | ResumeMessage | ToolResultMessage;// Server β Clientexport interface AuthSuccessMessage {diff --git a/src/store/chat/slices/agentRun/actions/__tests__/clientToolExecution.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/clientToolExecution.test.tsindex ca0753caf30..10e191dc8a5 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/clientToolExecution.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/clientToolExecution.test.ts@@ -52,7 +52,6 @@ function setup(options: { hasConnection?: boolean; sendReturns?: boolean } = {})connect: vi.fn(),disconnect: vi.fn(),on: vi.fn(),- sendInterrupt: vi.fn(),sendToolResult,},status: 'connected',@@ -501,7 +500,6 @@ describe('internal_executeClientTool', () => {connect: vi.fn(),disconnect: vi.fn(),on: vi.fn(),- sendInterrupt: vi.fn(),sendToolResult: reconnectedSend,},status: 'connected',diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.test.tsindex b183f7a77a6..11280cd728c 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.test.ts@@ -119,7 +119,6 @@ function createMockV1Client() {emit,on,reconnect: vi.fn(async () => {}),- sendInterrupt: vi.fn(),sendToolResult: vi.fn(() => true),updateToken: vi.fn(),};@@ -135,7 +134,6 @@ function createMockOperationClient(): OperationClient & Emitter {emit,on: on as OperationClient['on'],reconnect: vi.fn(async () => {}),- sendInterrupt: vi.fn(),sendToolResult: vi.fn(() => true),updateToken: vi.fn(),};diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.tsindex 0a9d1d87d01..da48383b0cc 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts@@ -149,7 +149,6 @@ function createMockClient(): GatewayConnection['client'] & {set.add(listener);}),reconnect: vi.fn(async () => {}),- sendInterrupt: vi.fn(),sendToolResult: vi.fn(() => true),updateToken: vi.fn(),};@@ -521,27 +520,6 @@ describe('GatewayActionImpl', () => {});});- describe('interruptGatewayAgent', () => {- it('should send interrupt to the client', () => {- const { action, mockClient } = createTestAction();-- action.connectToGateway({- gatewayUrl: 'https://gateway.test.com',- operationId: 'op-1',- token: 'test-token',- topicId: TEST_TOPIC_ID,- });-- action.interruptGatewayAgent('op-1');- expect(mockClient.sendInterrupt).toHaveBeenCalledOnce();- });-- it('should be a no-op for unknown operationId', () => {- const { action } = createTestAction();- action.interruptGatewayAgent('nonexistent');- });- });-describe('getGatewayConnectionStatus', () => {it('should return status for active connection', () => {const { action } = createTestAction();@@ -1390,7 +1368,29 @@ describe('GatewayActionImpl', () => {const controller = new AbortController();const mockClient = createMockClient();- const state: Record<string, any> = { gatewayConnections: {} };+ const internalDispatchTopic = vi.fn();+ const internalPinTopicStatus = vi.fn();+ // `refreshTopic` has already pulled in the server's running row: this+ // path opens no socket, so no terminal frame would ever retire it.+ const state: Record<string, any> = {+ gatewayConnections: {},+ topicDataMap: {+ 'agent_agent-1': {+ items: [+ {+ id: 'topic-1',+ metadata: {+ runningOperation: {+ assistantMessageId: 'ast-1',+ operationId: 'server-op-cancel',+ },+ },+ status: 'running',+ },+ ],+ },+ },+ };const set = vi.fn((updater: any) => {if (typeof updater === 'function') Object.assign(state, updater(state));else Object.assign(state, updater);@@ -1401,6 +1401,8 @@ describe('GatewayActionImpl', () => {completeOperation,connectToGateway,getOperationAbortSignal: vi.fn(() => controller.signal),+ internal_dispatchTopic: internalDispatchTopic,+ internal_pinTopicStatus: internalPinTopicStatus,moveQueuedMessages,moveVoiceMessages: vi.fn(),onOperationCancel,@@ -1473,6 +1475,146 @@ describe('GatewayActionImpl', () => {expect(associateMessageWithOperation).not.toHaveBeenCalled();expect(connectToGateway).not.toHaveBeenCalled();expect(completeOperation).toHaveBeenCalledWith('parent-send-msg-op');+ // The confirmed late interrupt retires the row itself.+ await vi.waitFor(() =>+ expect(internalPinTopicStatus).toHaveBeenCalledWith(+ expect.objectContaining({ status: 'active', topicId: 'topic-1' }),+ ),+ );+ expect(internalDispatchTopic).toHaveBeenCalledWith(+ expect.objectContaining({+ id: 'topic-1',+ value: { metadata: { runningOperation: null } },+ }),+ );+ });++ /**+ * @example A stop confirmed before the new topic's sidebar refetch lands still retires the row.+ */+ it('settles a late-cancelled new topic only after the sidebar refetch installs its row', async () => {+ // ROOT CAUSE:+ //+ // The late-interrupt settle ran as soon as `interruptTask` confirmed. For+ // a new topic the fire-and-forget `refreshTopic()` could land after it,+ // so the settle found no marker to clear and the refetch then installed a+ // `running` row that nothing on this socket-less path would ever retire.+ //+ // Before: settle raced the refetch and no-op'd on the missing marker.+ // After: settle waits for both the confirmation and the refetch.+ const controller = new AbortController();+ const internalDispatchTopic = vi.fn();+ const internalPinTopicStatus = vi.fn();+ const state: Record<string, any> = { gatewayConnections: {}, topicDataMap: {} };+ let landRefresh!: () => void;+ const refreshTopic = vi.fn(+ () =>+ new Promise<void>((resolve) => {+ landRefresh = () => {+ state.topicDataMap = {+ 'agent_agent-1': {+ items: [+ {+ id: 'topic-1',+ metadata: {+ runningOperation: {+ assistantMessageId: 'ast-1',+ operationId: 'server-op-late',+ },+ },+ status: 'running',+ },+ ],+ },+ };+ resolve();+ };+ }),+ );+ 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: vi.fn(),+ connectToGateway: vi.fn(),+ getOperationAbortSignal: vi.fn(() => controller.signal),+ internal_dispatchTopic: internalDispatchTopic,+ internal_pinTopicStatus: internalPinTopicStatus,+ internal_replaceTopicId: vi.fn(),+ moveQueuedMessages: vi.fn(),+ moveVoiceMessages: vi.fn(),+ onOperationCancel: vi.fn(),+ refreshTopic,+ replaceMessages: vi.fn(),+ startOperation: vi.fn(),+ switchTopic: 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.interruptTask).mockResolvedValue({+ operationId: 'server-op-late',+ success: true,+ });+ const persisted = {+ agentId: 'agent-1',+ assistantMessageId: 'ast-1',+ autoStarted: true,+ createdAt: new Date().toISOString(),+ message: 'ok',+ operationId: 'server-op-late',+ status: 'created',+ success: true,+ timestamp: new Date().toISOString(),+ token: 'test-token',+ topicId: 'topic-1',+ userMessageId: 'usr-1',+ } as const;+ let resolvePersistence!: (value: typeof persisted) => void;+ vi.mocked(aiAgentService.execAgentTask).mockReturnValue(+ new Promise((resolve) => {+ resolvePersistence = resolve;+ }),+ );++ const execution = action.executeGatewayAgent({+ context: { agentId: 'agent-1', scope: 'main', threadId: null, topicId: null },+ message: 'Hello',+ parentOperationId: 'parent-send-msg-op',+ });+ await vi.waitFor(() => expect(aiAgentService.execAgentTask).toHaveBeenCalledOnce());+ controller.abort('user cancelled');+ resolvePersistence(persisted);+ await execution;++ // The interrupt is confirmed, but the refetch has not landed yet.+ await vi.waitFor(() => expect(aiAgentService.interruptTask).toHaveBeenCalled());+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(refreshTopic).toHaveBeenCalledOnce();+ expect(internalPinTopicStatus).not.toHaveBeenCalled();++ landRefresh();++ await vi.waitFor(() =>+ expect(internalPinTopicStatus).toHaveBeenCalledWith(+ expect.objectContaining({ status: 'active', topicId: 'topic-1' }),+ ),+ );+ expect(internalDispatchTopic).toHaveBeenCalledWith(+ expect.objectContaining({+ id: 'topic-1',+ value: { metadata: { runningOperation: null } },+ }),+ );});/**@@ -1562,6 +1704,123 @@ describe('GatewayActionImpl', () => {);});+ /**+ * @example A confirmed stop settles the sidebar row without the socket's terminal frame.+ */+ it('retires the local topic row once the server confirms the stop', async () => {+ // ROOT CAUSE:+ //+ // Only `onSessionComplete` (a terminal frame over the Gateway socket)+ // cleared the local topic row's `running` status and marker. When that+ // frame never arrived after a stop, the input went idle and the message+ // showed as interrupted, but the sidebar row kept spinning and counting.+ //+ // Before: a confirmed interruptTask left the local row running.+ // After: the confirmed stop clears the marker and pins the row 'active'.+ const onOperationCancel = vi.fn();+ const connectToGateway = vi.fn();+ const internalDispatchTopic = vi.fn();+ const internalPinTopicStatus = vi.fn();+ const state: Record<string, any> = {+ activeAgentId: 'agent-1',+ activeTopicId: 'topic-1',+ gatewayConnections: {},+ topicDataMap: {+ 'agent_agent-1': {+ items: [+ {+ id: 'topic-1',+ metadata: {+ model: 'gpt-4',+ runningOperation: { assistantMessageId: 'ast-1', operationId: 'server-op-stop' },+ },+ 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: vi.fn(),+ connectToGateway,+ internal_dispatchTopic: internalDispatchTopic,+ internal_pinTopicStatus: internalPinTopicStatus,+ moveQueuedMessages: vi.fn(),+ moveVoiceMessages: vi.fn(),+ onOperationCancel,+ startOperation: vi.fn(() => ({ operationId: 'gw-op-local' })),+ 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(),+ message: 'ok',+ operationId: 'server-op-stop',+ 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 [, handler] = onOperationCancel.mock.calls[0];+ internalDispatchTopic.mockClear();+ internalPinTopicStatus.mockClear();++ // An unconfirmed stop must leave the row alone: the run may still be live.+ vi.mocked(aiAgentService.interruptTask).mockResolvedValueOnce({+ deviceCancellationConfirmed: false,+ operationId: 'server-op-stop',+ success: true,+ });+ await expect(handler()).rejects.toThrow();+ expect(internalDispatchTopic).not.toHaveBeenCalled();+ expect(internalPinTopicStatus).not.toHaveBeenCalled();++ // No terminal frame ever reaches onSessionComplete in this test.+ vi.mocked(aiAgentService.interruptTask).mockResolvedValueOnce({+ operationId: 'server-op-stop',+ success: true,+ });+ await handler();++ expect(internalDispatchTopic).toHaveBeenCalledWith({+ agentId: 'agent-1',+ groupId: undefined,+ id: 'topic-1',+ type: 'updateTopic',+ value: { metadata: { model: 'gpt-4', runningOperation: null } },+ });+ expect(internalPinTopicStatus).toHaveBeenCalledWith({+ agentId: 'agent-1',+ groupId: undefined,+ status: 'active',+ topicId: 'topic-1',+ });+ });+// Regression: after an error run the gateway session completes// and clears the SERVER-side topic metadata, but the local Zustand store copy// of `runningOperation` stayed set β so useGatewayReconnect kept firing a@@ -2452,6 +2711,81 @@ describe('GatewayActionImpl', () => {delete (globalThis as any).window;});+ it('retires the local topic row once the server confirms a stop issued after a reconnect', async () => {+ const onOperationCancel = vi.fn();+ const internalDispatchTopic = vi.fn();+ const internalPinTopicStatus = vi.fn();+ const state: Record<string, any> = {+ activeAgentId: 'agent-1',+ gatewayConnections: {},+ messagesMap: {},+ 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(),+ connectToGateway: vi.fn(),+ internal_dispatchTopic: internalDispatchTopic,+ internal_pinTopicStatus: internalPinTopicStatus,+ onOperationCancel,+ startOperation: vi.fn(() => ({ operationId: 'gw-op-reconnect' })),+ })) 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());++ await action.reconnectToGatewayOperation({+ agentId: 'agent-1',+ assistantMessageId: 'ast-1',+ heteroType: 'kimi-code',+ operationId: 'server-op-1',+ topicId: 'topic-1',+ });++ const [, handler] = onOperationCancel.mock.calls[0];+ vi.mocked(aiAgentService.interruptTask).mockResolvedValueOnce({+ operationId: 'server-op-1',+ success: true,+ });+ await handler();++ expect(internalDispatchTopic).toHaveBeenCalledWith(+ expect.objectContaining({+ id: 'topic-1',+ type: 'updateTopic',+ value: { metadata: { runningOperation: null } },+ }),+ );+ expect(internalPinTopicStatus).toHaveBeenCalledWith(+ expect.objectContaining({ status: 'active', topicId: 'topic-1' }),+ );+ });+// After a DB rehydrate (e.g. quit + relaunch), `createdAt` can arrive as an// ISO string instead of epoch ms. Anchoring startTime to it raw makes// `Date.now() - startTime` evaluate to NaN, which the elapsed-time labeldiff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex 2db8070042e..e238c5452a2 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -186,15 +186,16 @@ type Setter = StoreSetter<ChatStore>;// βββ Types βββexport interface GatewayConnection {+ /**+ * Cancellation is deliberately absent: the Gateway never carries a stop. The+ * op DO ignores an `interrupt` frame on both protocol versions, and a stop+ * also has to cancel device/hetero processes and settle the operation ++ * topic rows β work only the server can do. Stopping a run goes through+ * `cancelOperation`, whose handler calls `aiAgent.interruptTask`.+ */client: Pick<AgentStreamClient,- | 'connect'- | 'disconnect'- | 'on'- | 'reconnect'- | 'sendInterrupt'- | 'sendToolResult'- | 'updateToken'+ 'connect' | 'disconnect' | 'on' | 'reconnect' | 'sendToolResult' | 'updateToken'>;status: ConnectionStatus;}@@ -536,16 +537,6 @@ export class GatewayActionImpl {this.internal_cleanupGatewayConnection(operationId);};- /**- * Send an interrupt command to stop the agent for a specific operation.- */- interruptGatewayAgent = (operationId: string): void => {- const conn = this.#get().gatewayConnections[operationId];- if (!conn) return;-- conn.client.sendInterrupt();- };-/*** Mirror whether a conversation still has messages queued behind its running* Gateway run. See {@link syncQueuedMessagesFlag}.@@ -909,6 +900,11 @@ export class GatewayActionImpl {}let hasInterruptedAfterPersistence = false;+ // Owner-scoped late interrupt, resolved to whether the server confirmed it.+ let lateInterruptConfirmed: Promise<boolean> | undefined;+ // The fire-and-forget sidebar refetch below; it may install the server's+ // `running` row after the interrupt has already been confirmed.+ let topicRefresh: Promise<void> | undefined;const interruptIfCancelledAfterPersistence = () => {if (!abortSignal?.aborted) return false;@@ -925,10 +921,16 @@ export class GatewayActionImpl {console.error('[Gateway] share interruptTask after cancel failed:', err),);else- interruptGatewayTaskOrThrow({+ lateInterruptConfirmed = interruptGatewayTaskOrThrow({operationId: result.operationId,topicId: result.topicId,- }).catch((err) => console.error('[Gateway] interruptTask after cancel failed:', err));+ }).then(+ () => true,+ (err) => {+ console.error('[Gateway] interruptTask after cancel failed:', err);+ return false;+ },+ );}return true;@@ -1058,7 +1060,7 @@ export class GatewayActionImpl {// Share visitors have no owner topic sidebar β their list refreshes via// the share feature's own SWR hook, and refreshTopic is owner-scoped.if (!agentShareId)- this.#get()+ topicRefresh = this.#get().refreshTopic().catch((err) =>console.error('[Gateway] refreshTopic after topic creation failed:', err),@@ -1079,6 +1081,22 @@ export class GatewayActionImpl {cancelledAfterPersistence = interruptIfCancelledAfterPersistence() || cancelledAfterPersistence;if (cancelledAfterPersistence) {+ // This path never opens a socket, so no terminal frame will ever retire+ // the topic row. Settle it once the stop is confirmed AND the sidebar+ // refetch has landed: settling first would find no marker to clear, and+ // the refetch would then install a `running` row nobody retires.+ const { topicId } = result;+ if (lateInterruptConfirmed && topicId) {+ void Promise.all([lateInterruptConfirmed, topicRefresh]).then(([confirmed]) => {+ if (!confirmed) return;+ this.#settleLocalTopicAfterConfirmedStop({+ agentId: messageContext.agentId,+ groupId: messageContext.groupId,+ operationId: result.operationId,+ topicId,+ });+ });+ }if (parentOperationId) this.#get().completeOperation(parentOperationId);return result;}@@ -1175,6 +1193,15 @@ export class GatewayActionImpl {operationId: result.operationId,topicId: result.topicId,});++ if (result.topicId) {+ this.#settleLocalTopicAfterConfirmedStop({+ agentId: resolvedMessageContext.agentId,+ groupId: resolvedMessageContext.groupId,+ operationId: result.operationId,+ topicId: result.topicId,+ });+ }});const eventHandler = createGatewayEventHandler(this.#get, {@@ -1424,6 +1451,12 @@ export class GatewayActionImpl {}await interruptGatewayTaskOrThrow({ operationId });++ this.#settleLocalTopicAfterConfirmedStop({+ agentId: context.agentId,+ operationId,+ topicId,+ });});// Get a fresh JWT token (original expired after 5 min). The server throws@@ -1668,6 +1701,31 @@ export class GatewayActionImpl {return !!owner && owner !== operationId;};+ /**+ * Retire the local topic row once the server has confirmed a stop.+ *+ * The row's `running` status and `runningOperation` marker are otherwise only+ * cleared by `onSessionComplete`, i.e. by a terminal frame arriving over the+ * Gateway socket. A stop the server already acknowledged must not depend on+ * that frame: when it never lands (socket resubscribing, the op DO's event+ * buffer hibernated away, or a hetero run taking the `preserveExternalProducer`+ * early return on a resume status), the input is already idle and the message+ * shows as interrupted, yet the sidebar row keeps spinning and counting.+ *+ * Local only: the server settles its own row (device runs inside+ * `interruptTask`, native runs at the next step boundary). Ownership-guarded+ * by `clearLocalRunningOperation`, so a newer run's marker is left alone and+ * a later terminal frame for this run becomes a no-op.+ */+ #settleLocalTopicAfterConfirmedStop = (params: {+ agentId?: string;+ groupId?: string;+ operationId: string;+ topicId: string;+ }): void => {+ this.clearLocalRunningOperation({ ...params, status: 'active' });+ };+private clearLocalRunningOperation = (params: {agentId?: string;groupId?: string;