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(gateway): prevent duplicate streaming from stale reconnects (#15354)

LiJian818e67d1f0b7
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 f847a2231b8..1de3ef0b66f 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.ts
@@ -385,7 +385,7 @@ describe('GatewayActionImpl', () => {
describe('executeGatewayAgent', () => {
function createExecuteTestAction() {
const mockClient = createMockClient();
- const state: Record<string, any> = { gatewayConnections: {} };
+ const state: Record<string, any> = { gatewayConnections: {}, topicDataMap: {} };
const set = vi.fn((updater: any) => {
if (typeof updater === 'function') {
Object.assign(state, updater(state));
@@ -396,12 +396,13 @@ describe('GatewayActionImpl', () => {
const get = vi.fn(() => ({
...state,
- startOperation: vi.fn(() => ({ operationId: 'gw-op-1' })),
associateMessageWithOperation: vi.fn(),
connectToGateway: vi.fn(),
+ internal_dispatchTopic: vi.fn(),
internal_updateTopicLoading: vi.fn(),
onOperationCancel: vi.fn(),
replaceMessages: vi.fn(),
+ startOperation: vi.fn(() => ({ operationId: 'gw-op-1' })),
switchTopic: vi.fn(),
})) as any;
@@ -688,7 +689,7 @@ describe('GatewayActionImpl', () => {
const startOperation = vi.fn(() => ({ operationId: 'gw-op-local' }));
const mockClient = createMockClient();
- const state: Record<string, any> = { gatewayConnections: {} };
+ const state: Record<string, any> = { gatewayConnections: {}, topicDataMap: {} };
const set = vi.fn((updater: any) => {
if (typeof updater === 'function') Object.assign(state, updater(state));
else Object.assign(state, updater);
@@ -697,6 +698,7 @@ describe('GatewayActionImpl', () => {
...state,
associateMessageWithOperation: vi.fn(),
connectToGateway: vi.fn(),
+ internal_dispatchTopic: vi.fn(),
internal_updateTopicLoading: vi.fn(),
onOperationCancel,
replaceMessages: vi.fn(),
diff --git a/src/store/chat/slices/aiChat/actions/gateway.ts b/src/store/chat/slices/aiChat/actions/gateway.ts
index d87ddf939d6..af10c3195ea 100644
--- a/src/store/chat/slices/aiChat/actions/gateway.ts
+++ b/src/store/chat/slices/aiChat/actions/gateway.ts
@@ -452,6 +452,31 @@ export class GatewayActionImpl {
// the caller's op (e.g. `sendMessage`) to the child without a gap.
if (parentOperationId) this.#get().completeOperation(parentOperationId);
+ // Optimistically update the local store's runningOperation for this topic so
+ // useGatewayReconnect doesn't fire for a stale previous operation while the new
+ // gateway connection is being established. Also disconnect any live reconnect
+ // connection that was already established for the old operation.
+ if (result.topicId) {
+ const existingTopic = topicSelectors.getTopicById(result.topicId)(this.#get());
+ const staleOpId = existingTopic?.metadata?.runningOperation?.operationId;
+ if (staleOpId && staleOpId !== result.operationId) {
+ this.#get().internal_dispatchTopic({
+ id: result.topicId,
+ type: 'updateTopic',
+ value: {
+ metadata: {
+ ...existingTopic?.metadata,
+ runningOperation: {
+ assistantMessageId: result.assistantMessageId,
+ operationId: result.operationId,
+ },
+ },
+ },
+ });
+ this.disconnectFromGateway(staleOpId);
+ }
+ }
+
// 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
@@ -530,9 +555,24 @@ export class GatewayActionImpl {
const existingStatus = this.#get().gatewayConnections[operationId]?.status;
if (existingStatus && existingStatus !== 'disconnected') return;
+ // Skip reconnect if the topic already has a newer running operation. This
+ // happens when executeGatewayAgent was called (creating a new op) while this
+ // stale reconnect was still queued — connecting to the old op would produce
+ // duplicate streaming events alongside the new connection.
+ const topicCurrentOpId = topicSelectors.getTopicById(topicId)(this.#get())?.metadata
+ ?.runningOperation?.operationId;
+ if (topicCurrentOpId && topicCurrentOpId !== operationId) return;
+
// Get a fresh JWT token (original expired after 5 min)
const { token } = await aiAgentService.refreshGatewayToken(topicId);
+ // Re-check after the async token refresh: a newer executeGatewayAgent call may have
+ // taken over for this topic while we were waiting. If so, bail to avoid a duplicate stream.
+ // (disconnectFromGateway on the stale op is a no-op here because we haven't connected yet.)
+ const topicOpIdAfterRefresh = topicSelectors.getTopicById(topicId)(this.#get())?.metadata
+ ?.runningOperation?.operationId;
+ if (topicOpIdAfterRefresh && topicOpIdAfterRefresh !== operationId) return;
+
const agentId = this.#get().activeAgentId;
const context = {
agentId,