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: wire Gateway-mode stop via direct tRPC interrupt (#13815)

Arvin Xu18bc2716b2d0
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/conversationControl.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/conversationControl.test.ts
index 6bbc5373652..8993b457c3f 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/conversationControl.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/conversationControl.test.ts
@@ -85,6 +85,49 @@ describe('ConversationControl actions', () => {
expect(result.current.operations[operationId!].status).toBe('running');
});
+
+ it('cancels Gateway-mode execServerAgentRuntime ops and invokes their cancel handler', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: TEST_IDS.SESSION_ID,
+ activeTopicId: TEST_IDS.TOPIC_ID,
+ });
+ });
+
+ let operationId!: string;
+ act(() => {
+ const res = result.current.startOperation({
+ type: 'execServerAgentRuntime',
+ context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },
+ });
+ operationId = res.operationId;
+ });
+
+ const cancelHandler = vi.fn();
+ act(() => {
+ result.current.onOperationCancel(operationId, cancelHandler);
+ });
+
+ expect(result.current.operations[operationId].status).toBe('running');
+
+ act(() => {
+ result.current.stopGenerateMessage();
+ });
+
+ // Operation gets cancelled and the handler (which would fire the WS interrupt
+ // in real code) is invoked with the operation context.
+ expect(result.current.operations[operationId].status).toBe('cancelled');
+ expect(cancelHandler).toHaveBeenCalledWith(
+ expect.objectContaining({
+ operationId,
+ type: 'execServerAgentRuntime',
+ }),
+ );
+ // isAborting flag is also flipped so the UI loading state clears immediately.
+ expect(result.current.operations[operationId].metadata.isAborting).toBe(true);
+ });
});
describe('cancelSendMessageInServer', () => {
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.ts
index 5a9f98d3977..ef5ec038c24 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.ts
@@ -9,6 +9,7 @@ import { GatewayActionImpl } from '../gateway';
vi.mock('@/services/aiAgent', () => ({
aiAgentService: {
execAgentTask: vi.fn(),
+ interruptTask: vi.fn(),
},
}));
@@ -281,6 +282,7 @@ describe('GatewayActionImpl', () => {
associateMessageWithOperation: vi.fn(),
connectToGateway: vi.fn(),
internal_updateTopicLoading: vi.fn(),
+ onOperationCancel: vi.fn(),
replaceMessages: vi.fn(),
switchTopic: vi.fn(),
})) as any;
@@ -398,5 +400,67 @@ describe('GatewayActionImpl', () => {
}),
);
});
+
+ it('registers a cancel handler that calls aiAgentService.interruptTask with the server operationId', async () => {
+ const onOperationCancel = vi.fn();
+ const startOperation = vi.fn(() => ({ operationId: 'gw-op-local' }));
+
+ const mockClient = createMockClient();
+ const state: Record<string, any> = { gatewayConnections: {} };
+ 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_updateTopicLoading: vi.fn(),
+ onOperationCancel,
+ replaceMessages: vi.fn(),
+ startOperation,
+ 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(() => mockClient);
+ const interruptTaskSpy = vi
+ .mocked(aiAgentService.interruptTask)
+ .mockResolvedValue({ operationId: 'server-op-xyz', success: true });
+
+ vi.mocked(aiAgentService.execAgentTask).mockResolvedValue({
+ agentId: 'agent-1',
+ assistantMessageId: 'ast-1',
+ autoStarted: true,
+ createdAt: new Date().toISOString(),
+ message: 'ok',
+ operationId: 'server-op-xyz',
+ status: 'created',
+ success: true,
+ timestamp: new Date().toISOString(),
+ token: 'test-token',
+ topicId: 'topic-1',
+ userMessageId: 'usr-1',
+ });
+
+ await action.executeGatewayAgent({
+ context: { agentId: 'agent-1', topicId: 'topic-1', threadId: null, scope: 'main' },
+ message: 'Hello',
+ });
+
+ // Handler was registered against the local operation id...
+ expect(onOperationCancel).toHaveBeenCalledWith('gw-op-local', expect.any(Function));
+
+ // ...and, when invoked, fires tRPC interruptTask with the *server-side* operation id
+ const [, handler] = onOperationCancel.mock.calls[0];
+ await handler();
+ expect(interruptTaskSpy).toHaveBeenCalledWith({ operationId: 'server-op-xyz' });
+ });
});
});
diff --git a/src/store/chat/slices/aiChat/actions/conversationControl.ts b/src/store/chat/slices/aiChat/actions/conversationControl.ts
index 82b3d572a76..733fe94ee41 100644
--- a/src/store/chat/slices/aiChat/actions/conversationControl.ts
+++ b/src/store/chat/slices/aiChat/actions/conversationControl.ts
@@ -31,10 +31,15 @@ export class ConversationControlActionImpl {
stopGenerateMessage = (): void => {
const { activeAgentId, activeTopicId, cancelOperations } = this.#get();
- // Cancel all running execAgentRuntime operations in the current context
+ // Cancel running agent-runtime operations in the current context β€”
+ // both client-side (execAgentRuntime) and Gateway-mode
+ // (execServerAgentRuntime). For the Gateway-mode branch, a cancel
+ // handler registered in `executeGatewayAgent` / `reconnectToGatewayOperation`
+ // picks up the cancellation and forwards an `interrupt` frame over the
+ // Agent Gateway WebSocket so the server-side loop aborts.
cancelOperations(
{
- type: 'execAgentRuntime',
+ type: ['execAgentRuntime', 'execServerAgentRuntime'],
status: 'running',
agentId: activeAgentId,
topicId: activeTopicId,
diff --git a/src/store/chat/slices/aiChat/actions/gateway.ts b/src/store/chat/slices/aiChat/actions/gateway.ts
index 9654b7c6049..74353d2a971 100644
--- a/src/store/chat/slices/aiChat/actions/gateway.ts
+++ b/src/store/chat/slices/aiChat/actions/gateway.ts
@@ -275,6 +275,17 @@ export class GatewayActionImpl {
// Associate the server-created assistant message with the gateway operation
this.#get().associateMessageWithOperation(result.assistantMessageId, gatewayOpId);
+ // When the local operation is cancelled (e.g. user clicks stop), forward
+ // the interrupt directly to the server via the existing tRPC endpoint.
+ // Closure captures `result.operationId` (the server-side id) so we don't
+ // depend on any metadata lookup. Fire-and-forget β€” errors are logged but
+ // never block the local cancel flow.
+ this.#get().onOperationCancel(gatewayOpId, async () => {
+ await aiAgentService
+ .interruptTask({ operationId: result.operationId })
+ .catch((err) => console.error('[Gateway] interruptTask failed:', err));
+ });
+
const eventHandler = createGatewayEventHandler(this.#get, {
assistantMessageId: result.assistantMessageId,
context: execContext,
@@ -344,6 +355,14 @@ export class GatewayActionImpl {
this.#get().associateMessageWithOperation(assistantMessageId, gatewayOpId);
+ // Forward local-op cancellation to the server-side agent loop via tRPC.
+ // See note in executeGatewayAgent for details.
+ this.#get().onOperationCancel(gatewayOpId, async () => {
+ await aiAgentService
+ .interruptTask({ operationId })
+ .catch((err) => console.error('[Gateway] interruptTask failed:', err));
+ });
+
const eventHandler = createGatewayEventHandler(this.#get, {
assistantMessageId,
context,
diff --git a/src/store/chat/slices/operation/actions.ts b/src/store/chat/slices/operation/actions.ts
index 4edafe3d19d..c431599e546 100644
--- a/src/store/chat/slices/operation/actions.ts
+++ b/src/store/chat/slices/operation/actions.ts
@@ -389,9 +389,13 @@ export class OperationActionsImpl {
// Ignore abort errors
}
- // 2. Set isAborting flag immediately for execAgentRuntime operations
- // This ensures UI (loading button) responds instantly to user cancellation
- if (operation.type === 'execAgentRuntime') {
+ // 2. Set isAborting flag immediately for agent-runtime operations.
+ // This ensures UI (loading button) responds instantly to user cancellation.
+ // Applies to both client-side (execAgentRuntime) and Gateway-mode
+ // (execServerAgentRuntime) runs β€” the latter needs the flag so the UI
+ // transitions out of loading right away, without waiting for the
+ // round-trip WS `session_complete` after the server acknowledges interrupt.
+ if (operation.type === 'execAgentRuntime' || operation.type === 'execServerAgentRuntime') {
this.#get().updateOperationMetadata(operationId, { isAborting: true });
}