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.

πŸ”¨ chore: Gateway reconnect after page reload (#13685)

Arvin Xu5531ff79071d
diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.ts
index 0403f019198..56d939e4520 100644
--- a/packages/types/src/topic/topic.ts
+++ b/packages/types/src/topic/topic.ts
@@ -49,6 +49,17 @@ export interface ChatTopicMetadata {
cronJobId?: string;
model?: string;
provider?: string;
+ /**
+ * Currently running Gateway operation on this topic.
+ * Set when agent execution starts, cleared when it completes/fails.
+ * Used to reconnect WebSocket after page reload.
+ */
+ runningOperation?: {
+ assistantMessageId: string;
+ operationId: string;
+ scope?: string;
+ threadId?: string | null;
+ } | null;
userMemoryExtractRunState?: TopicUserMemoryExtractRunState;
userMemoryExtractStatus?: 'pending' | 'completed' | 'failed';
/**
diff --git a/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx b/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx
index 8392d16b106..2772ec47494 100644
--- a/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx
+++ b/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx
@@ -18,6 +18,7 @@ import MessageFromUrl from './MainChatInput/MessageFromUrl';
import ThreadHydration from './ThreadHydration';
import { useActionsBarConfig } from './useActionsBarConfig';
import { useAgentContext } from './useAgentContext';
+import { useGatewayReconnect } from './useGatewayReconnect';
const log = debug('lobe-render:agent:ConversationArea');
@@ -46,6 +47,9 @@ const Conversation = memo(() => {
// Get actionsBar config with branching support from ChatStore
const actionsBarConfig = useActionsBarConfig();
+ // Auto-reconnect to running Gateway operation on topic load
+ useGatewayReconnect(context.topicId);
+
return (
<ConversationProvider
actionsBar={actionsBarConfig}
diff --git a/src/routes/(main)/agent/features/Conversation/useGatewayReconnect.ts b/src/routes/(main)/agent/features/Conversation/useGatewayReconnect.ts
new file mode 100644
index 00000000000..e7303f9c93f
--- /dev/null
+++ b/src/routes/(main)/agent/features/Conversation/useGatewayReconnect.ts
@@ -0,0 +1,45 @@
+import useSWR from 'swr';
+
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+
+/**
+ * Hook that detects a running Gateway operation on the current topic
+ * and automatically reconnects the WebSocket after page reload.
+ *
+ * Uses SWR to manage the reconnect lifecycle β€” it only fires when
+ * runningOperation exists and deduplicates by operationId.
+ */
+export const useGatewayReconnect = (topicId?: string | null) => {
+ const isGatewayModeEnabled = useChatStore((s) => s.isGatewayModeEnabled);
+
+ // Subscribe to topic's runningOperation β€” re-evaluates when topic data arrives from SWR
+ const runningOperation = useChatStore((s) =>
+ topicId ? topicSelectors.getTopicById(topicId)(s)?.metadata?.runningOperation : undefined,
+ );
+
+ // SWR key is the operationId β€” null key means no fetch
+ // This naturally deduplicates: same operationId = same key = no re-fetch
+ useSWR(
+ runningOperation && isGatewayModeEnabled()
+ ? ['reconnectGateway', runningOperation.operationId]
+ : null,
+ async () => {
+ if (!runningOperation || !topicId) return;
+
+ await useChatStore.getState().reconnectToGatewayOperation({
+ assistantMessageId: runningOperation.assistantMessageId,
+ operationId: runningOperation.operationId,
+ scope: runningOperation.scope,
+ threadId: runningOperation.threadId,
+ topicId,
+ });
+ },
+ {
+ // Don't revalidate on focus/reconnect β€” one attempt is enough
+ revalidateIfStale: false,
+ revalidateOnFocus: false,
+ revalidateOnReconnect: false,
+ },
+ );
+};
diff --git a/src/server/routers/lambda/aiAgent.ts b/src/server/routers/lambda/aiAgent.ts
index 552ed30136a..5b5862dfb15 100644
--- a/src/server/routers/lambda/aiAgent.ts
+++ b/src/server/routers/lambda/aiAgent.ts
@@ -1225,4 +1225,27 @@ export const aiAgentRouter = router({
});
}
}),
+
+ /**
+ * Refresh Gateway JWT token for an existing operation.
+ * Used when reconnecting after page reload (original token expired).
+ */
+ refreshGatewayToken: aiAgentProcedure
+ .input(z.object({ topicId: z.string() }))
+ .query(async ({ input, ctx }) => {
+ // Verify the topic belongs to this user and has a running operation
+ const topic = await ctx.topicModel.findById(input.topicId);
+
+ if (!topic?.metadata?.runningOperation) {
+ throw new TRPCError({
+ code: 'NOT_FOUND',
+ message: 'No running operation found on this topic',
+ });
+ }
+
+ const { signUserJWT } = await import('@/libs/trpc/utils/internalJwt');
+ const token = await signUserJWT(ctx.userId);
+
+ return { token };
+ }),
});
diff --git a/src/server/routers/lambda/topic.ts b/src/server/routers/lambda/topic.ts
index e4d9208d9a0..90b35b22427 100644
--- a/src/server/routers/lambda/topic.ts
+++ b/src/server/routers/lambda/topic.ts
@@ -556,9 +556,18 @@ export const topicRouter = router({
z.object({
id: z.string(),
metadata: z.object({
+ boundDeviceId: z.string().optional(),
model: z.string().optional(),
provider: z.string().optional(),
- boundDeviceId: z.string().optional(),
+ runningOperation: z
+ .object({
+ assistantMessageId: z.string(),
+ operationId: z.string(),
+ scope: z.string().optional(),
+ threadId: z.string().nullable().optional(),
+ })
+ .nullable()
+ .optional(),
workingDirectory: z.string().optional(),
}),
}),
diff --git a/src/server/services/aiAgent/__tests__/execAgent.device.test.ts b/src/server/services/aiAgent/__tests__/execAgent.device.test.ts
index faea8472cda..e07eb0b0c55 100644
--- a/src/server/services/aiAgent/__tests__/execAgent.device.test.ts
+++ b/src/server/services/aiAgent/__tests__/execAgent.device.test.ts
@@ -366,7 +366,11 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
const createOpArgs = mockCreateOperation.mock.calls[0][0];
expect(createOpArgs.activeDeviceId).toBe('device-001');
- expect(topicMock.updateMetadata).not.toHaveBeenCalled();
+ // updateMetadata is called for runningOperation persistence, but not for device binding
+ expect(topicMock.updateMetadata).not.toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ boundDeviceId: expect.anything() }),
+ );
});
it('should not reuse topic boundDeviceId when no explicit deviceId is provided', async () => {
@@ -492,7 +496,11 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
deviceId: 'device-002',
});
- expect(topicMock.updateMetadata).not.toHaveBeenCalled();
+ // updateMetadata is called for runningOperation persistence, but not for device binding
+ expect(topicMock.updateMetadata).not.toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ boundDeviceId: expect.anything() }),
+ );
const createOpArgs = mockCreateOperation.mock.calls[0][0];
expect(createOpArgs.activeDeviceId).toBe('device-002');
});
diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.ts
index 034866e8bd6..7f11e48252d 100644
--- a/src/server/services/aiAgent/index.ts
+++ b/src/server/services/aiAgent/index.ts
@@ -1076,6 +1076,16 @@ export class AiAgentService {
log('execAgent: created operation %s (autoStarted: %s)', operationId, result.autoStarted);
+ // Persist running operation to topic metadata for reconnect after page reload
+ await this.topicModel.updateMetadata(topicId, {
+ runningOperation: {
+ assistantMessageId: assistantMessageRecord.id,
+ operationId,
+ scope: appContext?.scope ?? undefined,
+ threadId: appContext?.threadId ?? undefined,
+ },
+ });
+
// Generate a short-lived JWT for Gateway WebSocket authentication
let gatewayToken: string | undefined;
try {
diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.ts
index da1c379aa75..0bb1f84f79d 100644
--- a/src/services/aiAgent.ts
+++ b/src/services/aiAgent.ts
@@ -108,6 +108,13 @@ class AiAgentService {
* - Group mode: pass groupId, Thread will be associated with the Group
* - Single Agent mode: omit groupId, Thread will only be associated with the Agent
*/
+ /**
+ * Get a fresh JWT token for Gateway WebSocket reconnection.
+ */
+ async refreshGatewayToken(topicId: string): Promise<{ token: string }> {
+ return await lambdaClient.aiAgent.refreshGatewayToken.query({ topicId });
+ }
+
async execSubAgentTask(params: ExecSubAgentTaskParams) {
return await lambdaClient.aiAgent.execSubAgentTask.mutate(params);
}
diff --git a/src/services/topic/index.ts b/src/services/topic/index.ts
index ed5d9d91114..64a165b4fa7 100644
--- a/src/services/topic/index.ts
+++ b/src/services/topic/index.ts
@@ -81,10 +81,11 @@ export class TopicService {
updateTopicMetadata = (
id: string,
metadata: {
+ boundDeviceId?: string;
model?: string;
provider?: string;
+ runningOperation?: { assistantMessageId: string; operationId: string } | null;
workingDirectory?: string;
- boundDeviceId?: string;
},
) => {
return lambdaClient.topic.updateTopicMetadata.mutate({ id, metadata });
diff --git a/src/store/chat/slices/aiChat/actions/gateway.ts b/src/store/chat/slices/aiChat/actions/gateway.ts
index 7a5783fd5a4..d34fb0e7e1a 100644
--- a/src/store/chat/slices/aiChat/actions/gateway.ts
+++ b/src/store/chat/slices/aiChat/actions/gateway.ts
@@ -7,6 +7,7 @@ import type {
} from '@/libs/agent-stream';
import { AgentStreamClient } from '@/libs/agent-stream/client';
import { aiAgentService } from '@/services/aiAgent';
+import { topicService } from '@/services/topic';
import type { ChatStore } from '@/store/chat/store';
import type { StoreSetter } from '@/store/types';
import { useUserStore } from '@/store/user';
@@ -233,7 +234,14 @@ export class GatewayActionImpl {
onEvent: eventHandler,
onSessionComplete: () => {
this.#get().completeOperation(gatewayOpId);
- if (result.topicId) this.#get().internal_updateTopicLoading(result.topicId, false);
+ if (result.topicId) {
+ this.#get().internal_updateTopicLoading(result.topicId, false);
+ // Clear running operation from topic metadata (best-effort from frontend;
+ // if browser was closed, reconnect logic will handle stale entries)
+ topicService
+ .updateTopicMetadata(result.topicId, { runningOperation: null })
+ .catch(() => {});
+ }
},
operationId: result.operationId,
token: result.token || '',
@@ -242,6 +250,63 @@ export class GatewayActionImpl {
return result;
};
+ /**
+ * Reconnect to an existing Gateway operation after page reload.
+ * Reads runningOperation from topic metadata, refreshes the JWT token,
+ * and establishes a new WebSocket connection with event replay.
+ */
+ reconnectToGatewayOperation = async (params: {
+ assistantMessageId: string;
+ operationId: string;
+ scope?: string;
+ threadId?: string | null;
+ topicId: string;
+ }): Promise<void> => {
+ const { assistantMessageId, operationId, topicId, scope, threadId } = params;
+
+ if (!this.isGatewayModeEnabled()) return;
+
+ const agentGatewayUrl =
+ window.global_serverConfigStore!.getState().serverConfig.agentGatewayUrl!;
+
+ // Get a fresh JWT token (original expired after 5 min)
+ const { token } = await aiAgentService.refreshGatewayToken(topicId);
+
+ const agentId = this.#get().activeAgentId;
+ const context = {
+ agentId,
+ scope: (scope ?? 'main') as ConversationContext['scope'],
+ threadId: threadId ?? null,
+ topicId,
+ };
+
+ // Create a local operation for UI loading state
+ const { operationId: gatewayOpId } = this.#get().startOperation({
+ context,
+ type: 'execServerAgentRuntime',
+ });
+
+ this.#get().associateMessageWithOperation(assistantMessageId, gatewayOpId);
+
+ const eventHandler = createGatewayEventHandler(this.#get, {
+ assistantMessageId,
+ context,
+ operationId: gatewayOpId,
+ });
+
+ this.#get().connectToGateway({
+ gatewayUrl: agentGatewayUrl,
+ onEvent: eventHandler,
+ onSessionComplete: () => {
+ this.#get().completeOperation(gatewayOpId);
+ this.#get().internal_updateTopicLoading(topicId, false);
+ topicService.updateTopicMetadata(topicId, { runningOperation: null }).catch(() => {});
+ },
+ operationId,
+ token,
+ });
+ };
+
private internal_cleanupGatewayConnection = (operationId: string): void => {
this.#set(
(state) => {