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(chat): clear stale local runningOperation so gateway reconnect stops looping 404 (#17332)

YuTengjing785476a20a50
diff --git a/src/hooks/useGatewayReconnect.ts b/src/hooks/useGatewayReconnect.ts
index d23fbeb27bc..3ae121cc320 100644
--- a/src/hooks/useGatewayReconnect.ts
+++ b/src/hooks/useGatewayReconnect.ts
@@ -3,6 +3,7 @@ import useSWR from 'swr';
import { gatewayKeys } from '@/libs/swr/keys';
import { useChatStore } from '@/store/chat';
import { useServerConfigStore } from '@/store/serverConfig';
+import { isTrpcErrorCode } from '@/utils/trpcError';
interface RunningOperation {
assistantMessageId: string;
@@ -50,6 +51,10 @@ export const useGatewayReconnect = (
revalidateIfStale: false,
revalidateOnFocus: false,
revalidateOnReconnect: false,
+ // Never retry the stale-marker case (operation already gone β†’ NOT_FOUND) so a
+ // dead op can't loop 404s even if it escapes the fetcher-level catch; transient
+ // network/server errors keep SWR's default retry so a live run still resumes.
+ shouldRetryOnError: (error) => !isTrpcErrorCode(error, 'NOT_FOUND'),
},
);
};
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
index 09b1780b0c5..f37c618657f 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
@@ -1062,6 +1062,265 @@ describe('GatewayActionImpl', () => {
});
});
+ // Regression (LOBE-12055): 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
+ // reconnect for a dead op and looped 404s. onSessionComplete must ALSO clear
+ // the local store marker (spreading the rest of metadata).
+ it('clears the local runningOperation marker when the gateway session completes with an error', async () => {
+ const connectToGateway = vi.fn();
+ const internalDispatchTopic = vi.fn();
+ const startOperation = vi.fn(() => ({ operationId: 'gw-op-1' }));
+ 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-1' },
+ },
+ },
+ ],
+ },
+ },
+ };
+ 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,
+ moveQueuedMessages: 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(),
+ 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];
+ // Ignore any dispatches from the optimistic-update path during setup.
+ internalDispatchTopic.mockClear();
+ vi.mocked(topicService.updateTopicMetadata).mockResolvedValue(undefined as never);
+
+ onSessionComplete({ succeeded: false, terminalReceived: true });
+
+ expect(internalDispatchTopic).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ groupId: undefined,
+ id: 'topic-1',
+ type: 'updateTopic',
+ value: { metadata: { model: 'gpt-4', runningOperation: null } },
+ });
+ });
+
+ // Background completion: the run's owning agent bucket must be targeted even
+ // after the user switched to another agent β€” the active-bucket lookup would
+ // miss the topic and leave its runningOperation marker stale.
+ it('clears the owning bucket marker even after the user switched agents', async () => {
+ const connectToGateway = vi.fn();
+ const internalDispatchTopic = vi.fn();
+ const startOperation = vi.fn(() => ({ operationId: 'gw-op-1' }));
+ 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-1' },
+ },
+ },
+ ],
+ },
+ 'agent_agent-2': { items: [] },
+ },
+ };
+ 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,
+ moveQueuedMessages: 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(),
+ 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];
+ internalDispatchTopic.mockClear();
+ vi.mocked(topicService.updateTopicMetadata).mockResolvedValue(undefined as never);
+
+ // The user switched away before the run finished in the background.
+ state.activeAgentId = 'agent-2';
+ state.activeTopicId = null;
+
+ onSessionComplete({ succeeded: false, terminalReceived: true });
+
+ expect(internalDispatchTopic).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ groupId: undefined,
+ id: 'topic-1',
+ type: 'updateTopic',
+ value: { metadata: { model: 'gpt-4', runningOperation: null } },
+ });
+ });
+
+ // A late close of a finished op must NOT wipe the marker of a NEWER operation
+ // that a racing retry/send already wrote β€” that would break reconnect-after-reload
+ // for the live run. Only a marker matching the completed op's id gets cleared.
+ it('does not clear the local marker when it already belongs to a newer operation', async () => {
+ const connectToGateway = vi.fn();
+ const internalDispatchTopic = vi.fn();
+ const startOperation = vi.fn(() => ({ operationId: 'gw-op-1' }));
+ const state: Record<string, any> = {
+ activeAgentId: 'agent-1',
+ activeTopicId: 'topic-1',
+ gatewayConnections: {},
+ topicDataMap: {
+ 'agent_agent-1': {
+ items: [
+ {
+ id: 'topic-1',
+ metadata: {
+ model: 'gpt-4',
+ // Marker already points at a newer op than the one completing below.
+ runningOperation: { assistantMessageId: 'ast-2', operationId: 'server-op-NEWER' },
+ },
+ },
+ ],
+ },
+ },
+ };
+ 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,
+ moveQueuedMessages: 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(),
+ 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];
+ // Ignore any dispatches from the optimistic-update path during setup.
+ internalDispatchTopic.mockClear();
+ vi.mocked(topicService.updateTopicMetadata).mockResolvedValue(undefined as never);
+
+ onSessionComplete({ succeeded: false, terminalReceived: true });
+
+ expect(internalDispatchTopic).not.toHaveBeenCalled();
+ });
+
// When the desktop runs against 本机 (effective runtime mode 'local'), the
// client must forward this machine's own gateway deviceId so the server can
// preset activeDeviceId and inject lobe-local-system into the first LLM
@@ -1365,5 +1624,153 @@ describe('GatewayActionImpl', () => {
runningOperation: null,
});
});
+
+ // Seeds a topic whose local metadata still carries a runningOperation, wires up
+ // internal_dispatchTopic + connectToGateway capture, so we can assert the local
+ // store clear (LOBE-12055) on both the NOT_FOUND refresh path and onSessionComplete.
+ function createSeededReconnectHarness() {
+ const captured: { onSessionComplete?: (p: any) => void } = {};
+ const connectToGateway = vi.fn((params: any) => {
+ captured.onSessionComplete = params.onSessionComplete;
+ });
+ const internalDispatchTopic = vi.fn();
+ const completeOperation = vi.fn();
+ const startOperation = vi.fn(() => ({ operationId: 'gw-op-reconnect' }));
+ const state: Record<string, any> = {
+ activeAgentId: 'agent-1',
+ activeTopicId: 'topic-1',
+ gatewayConnections: {},
+ messagesMap: { 'agent-1_topic-1': [{ createdAt: 1, id: 'ast-1' }] },
+ topicDataMap: {
+ 'agent_agent-1': {
+ items: [
+ {
+ id: 'topic-1',
+ metadata: {
+ model: 'gpt-4',
+ runningOperation: { assistantMessageId: 'ast-1', operationId: 'server-op-1' },
+ },
+ },
+ ],
+ },
+ },
+ };
+ 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,
+ onOperationCancel: vi.fn(),
+ startOperation,
+ updateTopicStatus: vi.fn(),
+ })) 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());
+
+ return { action, captured, connectToGateway, internalDispatchTopic };
+ }
+
+ // Regression (LOBE-12055): a stale local runningOperation fires a reconnect,
+ // but the server already cleared its marker and answers refreshGatewayToken
+ // with TRPC NOT_FOUND. The reconnect must clear the local marker and bail
+ // silently (no connect, no throw) so the SWR fetcher resolves instead of
+ // looping 404s.
+ it('clears the local marker and bails when refreshGatewayToken returns NOT_FOUND', async () => {
+ const { action, connectToGateway, internalDispatchTopic } = createSeededReconnectHarness();
+ vi.mocked(aiAgentService.refreshGatewayToken).mockRejectedValueOnce({
+ data: { code: 'NOT_FOUND' },
+ });
+
+ await expect(
+ action.reconnectToGatewayOperation({
+ assistantMessageId: 'ast-1',
+ operationId: 'server-op-1',
+ topicId: 'topic-1',
+ }),
+ ).resolves.toBeUndefined();
+
+ expect(internalDispatchTopic).toHaveBeenCalledWith({
+ id: 'topic-1',
+ type: 'updateTopic',
+ value: { metadata: { model: 'gpt-4', runningOperation: null } },
+ });
+ expect(connectToGateway).not.toHaveBeenCalled();
+ });
+
+ // A non-NOT_FOUND refresh failure is a real error (network, server down): it
+ // must rethrow and NOT clear the local marker (the op may still be alive).
+ it('rethrows and does not clear the local marker for a non-NOT_FOUND refresh error', async () => {
+ const { action, connectToGateway, internalDispatchTopic } = createSeededReconnectHarness();
+ vi.mocked(aiAgentService.refreshGatewayToken).mockRejectedValueOnce(
+ new Error('network down'),
+ );
+
+ await expect(
+ action.reconnectToGatewayOperation({
+ assistantMessageId: 'ast-1',
+ operationId: 'server-op-1',
+ topicId: 'topic-1',
+ }),
+ ).rejects.toThrow('network down');
+
+ expect(internalDispatchTopic).not.toHaveBeenCalled();
+ expect(connectToGateway).not.toHaveBeenCalled();
+ });
+
+ // A reconnect close that PROVES the op is over (real terminal event) must also
+ // clear the local store marker, mirroring the server-side updateTopicMetadata.
+ it('clears the local marker on a terminal reconnect close', async () => {
+ const { action, captured, internalDispatchTopic } = createSeededReconnectHarness();
+
+ await action.reconnectToGatewayOperation({
+ assistantMessageId: 'ast-1',
+ operationId: 'server-op-1',
+ topicId: 'topic-1',
+ });
+
+ internalDispatchTopic.mockClear();
+ vi.mocked(topicService.updateTopicMetadata).mockResolvedValue(undefined as never);
+ captured.onSessionComplete!({ authFailed: false, succeeded: false, terminalReceived: true });
+
+ expect(internalDispatchTopic).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ groupId: undefined,
+ id: 'topic-1',
+ type: 'updateTopic',
+ value: { metadata: { model: 'gpt-4', runningOperation: null } },
+ });
+ });
+
+ // 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 () => {
+ const { action, captured, internalDispatchTopic } = createSeededReconnectHarness();
+
+ await action.reconnectToGatewayOperation({
+ assistantMessageId: 'ast-1',
+ operationId: 'server-op-1',
+ topicId: 'topic-1',
+ });
+
+ internalDispatchTopic.mockClear();
+ captured.onSessionComplete!({ authFailed: false, 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.ts
index 11648d8f807..b3e2960b9fa 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -27,9 +27,11 @@ import { consumePendingTopicRepos, getPendingTopicRepos } from '@/store/chat/pen
import { topicSelectors } from '@/store/chat/selectors';
import type { ChatStore } from '@/store/chat/store';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+import { topicMapKey } from '@/store/chat/utils/topicMapKey';
import type { StoreSetter } from '@/store/types';
import { useUserStore } from '@/store/user';
import { settingsSelectors, toolInterventionSelectors } from '@/store/user/selectors';
+import { isTrpcErrorCode } from '@/utils/trpcError';
import { buildRunLifecycle } from '../../lifecycle/buildRunLifecycle';
import type { RunScope } from '../../lifecycle/types';
@@ -725,6 +727,14 @@ export class GatewayActionImpl {
topicService
.updateTopicMetadata(result.topicId, { runningOperation: null })
.catch(() => {});
+ // Also clear the local store copy β€” the server clear above does NOT touch
+ // the Zustand topic map that useGatewayReconnect reads (LOBE-12055).
+ this.clearLocalRunningOperation({
+ agentId: execContext.agentId,
+ groupId: execContext.groupId,
+ operationId: result.operationId,
+ topicId: result.topicId,
+ });
}
onComplete?.();
},
@@ -773,8 +783,21 @@ export class GatewayActionImpl {
?.runningOperation?.operationId;
if (topicCurrentOpId && topicCurrentOpId !== operationId) return;
- // Get a fresh JWT token (original expired after 5 min)
- const { token } = await aiAgentService.refreshGatewayToken(topicId);
+ // Get a fresh JWT token (original expired after 5 min). The server throws
+ // TRPCError NOT_FOUND when it has no running operation on this topic β€” our
+ // local marker is stale (e.g. an error run cleared the server marker but not
+ // the store). Clear it and bail silently so the reconnect SWR fetcher resolves
+ // and does not retry the 404 forever (LOBE-12055).
+ let token: string;
+ try {
+ ({ token } = await aiAgentService.refreshGatewayToken(topicId));
+ } catch (error) {
+ if (isTrpcErrorCode(error, 'NOT_FOUND')) {
+ this.clearLocalRunningOperation({ operationId, topicId });
+ return;
+ }
+ throw error;
+ }
// 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.
@@ -892,6 +915,9 @@ export class GatewayActionImpl {
// Clear the persisted marker useGatewayReconnect keys off so a dead op
// doesn't get reconnected on every reload / task-drawer open.
topicService.updateTopicMetadata(topicId, { runningOperation: null }).catch(() => {});
+ // Mirror the clear into the local store β€” the server clear above leaves the
+ // Zustand topic map stale, which useGatewayReconnect keys off (LOBE-12055).
+ this.clearLocalRunningOperation({ agentId: context.agentId, operationId, topicId });
},
operationId,
resumeOnConnect: true,
@@ -935,6 +961,51 @@ export class GatewayActionImpl {
});
};
+ /**
+ * Clear the client-store copy of `topic.metadata.runningOperation`.
+ *
+ * The server-side clear (`topicService.updateTopicMetadata(topicId, { runningOperation: null })`)
+ * alone leaves the Zustand store stale: `useGatewayReconnect` keys off the LOCAL
+ * copy, so after an error run (e.g. insufficient credits) the stale marker keeps
+ * firing `aiAgentService.refreshGatewayToken(topicId)`, which the server now answers
+ * with NOT_FOUND (404 β€” the server-side marker is already null). Raw SWR retries the
+ * 404 forever and wedges the conversation (LOBE-12055).
+ *
+ * The `updateTopic` reducer shallow-merges `value.metadata` (`{...currentTopic, ...value}`),
+ * so we spread the existing metadata to avoid dropping its other keys. Only dispatch when
+ * the topic still carries the marker for `operationId` β€” a late close of a finished op
+ * can race with a retry/send that already wrote a NEWER operation's marker, and clearing
+ * unconditionally would break reconnect-after-reload for that live run.
+ *
+ * `agentId`/`groupId` route the lookup + dispatch to the run's OWNING topic bucket
+ * (same convention as `updateTopicStatus`): a background completion can land after the
+ * user switched agent/group, when the active-bucket `getTopicById` would miss the topic
+ * and leave its marker stale.
+ */
+ private clearLocalRunningOperation = (params: {
+ agentId?: string;
+ groupId?: string;
+ operationId: string;
+ topicId: string;
+ }): void => {
+ const { topicId, operationId, agentId, groupId } = params;
+ const state = this.#get();
+ const key = topicMapKey({
+ agentId: agentId ?? state.activeAgentId,
+ groupId: groupId ?? state.activeGroupId,
+ });
+ const existingTopic = state.topicDataMap[key]?.items?.find((t) => t.id === topicId);
+ if (existingTopic?.metadata?.runningOperation?.operationId !== operationId) return;
+
+ state.internal_dispatchTopic({
+ agentId,
+ groupId,
+ id: topicId,
+ type: 'updateTopic',
+ value: { metadata: { ...existingTopic.metadata, runningOperation: null } },
+ });
+ };
+
private internal_cleanupGatewayConnection = (operationId: string): void => {
this.#set(
(state) => {
diff --git a/src/utils/trpcError.ts b/src/utils/trpcError.ts
new file mode 100644
index 00000000000..da25d76e90c
--- /dev/null
+++ b/src/utils/trpcError.ts
@@ -0,0 +1,15 @@
+import type { TRPC_ERROR_CODE_KEY } from '@trpc/server/rpc';
+
+/**
+ * Detect a tRPC client error carrying the given error code.
+ *
+ * Structural check instead of `instanceof TRPCClientError` so it also matches
+ * plain-shaped errors (e.g. rethrown/serialized across boundaries), while
+ * `TRPC_ERROR_CODE_KEY` keeps the `code` literal type-checked against tRPC's
+ * error-code table.
+ */
+export const isTrpcErrorCode = (error: unknown, code: TRPC_ERROR_CODE_KEY): boolean => {
+ if (typeof error !== 'object' || error === null) return false;
+
+ return (error as { data?: { code?: unknown } }).data?.code === code;
+};