π€― 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): stop reconnect loop on workspace teammate runs (#21667)
Lobehub Coderefe73916c5c5
diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.test.tsindex 4595e28e945..960279d9ce7 100644--- a/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts@@ -1,6 +1,7 @@// @vitest-environment nodeimport { type LobeChatDatabase } from '@lobechat/database';import {+ agentOperations,agents,agentsToSessions,messages,@@ -662,6 +663,73 @@ describe('AI Agent Router Integration Tests', () => {});});+ describe('refreshGatewayToken in a workspace', () => {+ let workspaceId: string;+ let teammateId: string;++ beforeEach(async () => {+ teammateId = await createTestUser(serverDB);+ const [workspace] = await serverDB+ .insert(workspaces)+ .values({ name: 'Team', primaryOwnerId: userId, slug: `ws-gw-${userId}` })+ .returning();+ workspaceId = workspace.id;+ mockSignUserJWT.mockResolvedValue('gateway-jwt');+ });++ afterEach(async () => {+ await cleanupTestUser(serverDB, teammateId);+ });++ /** A workspace topic whose live run was started by `starterId`. */+ const seedRunningTopic = async (starterId: string) => {+ const operationId = `op-${starterId}`;+ const [topic] = await serverDB+ .insert(topics)+ .values({+ metadata: {+ runningOperation: {+ assistantMessageId: 'msg-1',+ operationId,+ startedAt: new Date().toISOString(),+ },+ },+ title: 'Running',+ userId: starterId,+ workspaceId,+ })+ .returning();+ await serverDB.insert(agentOperations).values({+ id: operationId,+ status: 'running',+ topicId: topic.id,+ userId: starterId,+ workspaceId,+ });+ return topic.id;+ };++ it("refuses a teammate's live run instead of signing a token the gateway rejects", async () => {+ const topicId = await seedRunningTopic(teammateId);+ const caller = aiAgentRouter.createCaller({ ...createTestContext(), workspaceId });++ await expect(caller.refreshGatewayToken({ topicId })).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ expect(mockSignUserJWT).not.toHaveBeenCalled();+ });++ it('still signs for the member who started the run', async () => {+ const topicId = await seedRunningTopic(userId);+ const caller = aiAgentRouter.createCaller({ ...createTestContext(), workspaceId });++ await expect(caller.refreshGatewayToken({ topicId })).resolves.toEqual({+ token: 'gateway-jwt',+ });+ expect(mockSignUserJWT).toHaveBeenCalledWith(userId);+ });+ });+describe('execAgent workspace use guard', () => {let workspaceId: string;let wsAgentId: string;diff --git a/apps/server/src/routers/lambda/_helpers/operationReadGuard.ts b/apps/server/src/routers/lambda/_helpers/operationReadGuard.tsindex bc682fcafd8..61f27d5065b 100644--- a/apps/server/src/routers/lambda/_helpers/operationReadGuard.ts+++ b/apps/server/src/routers/lambda/_helpers/operationReadGuard.ts@@ -106,3 +106,30 @@ const isUnpersistedRuntimeOwner = async ({ db, operationId, userId }: OperationRconst metadata = await createAgentStateManager().getOperationMetadata(operationId);return metadata?.userId === userId && !metadata.streamOwnerUserId;};++/**+ * Whether the persisted operation was started by someone other than the caller.+ *+ * Workspace reads are member-wide (a teammate can open a topic another member's+ * run is still driving), but the Gateway stream and the run's terminal settle+ * stay with the user who started it: the gateway registers each operation under+ * that user's id and refuses every other `sub`. The initial insert is+ * non-fatal, so a live run may have no row; its runtime metadata then names the+ * starter, as in {@link isUnpersistedRuntimeOwner}.+ */+export const isOperationOwnedByAnotherUser = async ({+ db,+ operationId,+ userId,+}: Pick<OperationReadParams, 'db' | 'operationId' | 'userId'>): Promise<boolean> => {+ const [row] = await db+ .select({ userId: agentOperations.userId })+ .from(agentOperations)+ .where(eq(agentOperations.id, operationId))+ .limit(1);++ if (row) return row.userId !== userId;++ const metadata = await createAgentStateManager().getOperationMetadata(operationId);+ return !!metadata?.userId && metadata.userId !== userId;+};diff --git a/apps/server/src/routers/lambda/aiAgent/gatewayRelay.ts b/apps/server/src/routers/lambda/aiAgent/gatewayRelay.tsindex ccf0465a44e..71c58fc6bca 100644--- a/apps/server/src/routers/lambda/aiAgent/gatewayRelay.ts+++ b/apps/server/src/routers/lambda/aiAgent/gatewayRelay.ts@@ -3,6 +3,7 @@ import { z } from 'zod';import { router } from '@/libs/trpc/lambda';import { signUserJWT } from '@/libs/trpc/utils/internalJwt';+import { isOperationOwnedByAnotherUser } from '@/server/routers/lambda/_helpers/operationReadGuard';import { LlmExecutorSchema } from './execSchemas';import { aiAgentProcedure, aiAgentWriteProcedure } from './procedures';@@ -81,6 +82,26 @@ export const gatewayRelayRouter = router({});}+ // A workspace member can read a teammate's topic, but the gateway only+ // streams an operation to the user who started it (it compares the+ // token's `sub` with the registered owner). A caller-signed token would+ // be refused as `auth_failed`, which the client reads as a dead run, so+ // refuse here instead: FORBIDDEN tells the client the run is alive but+ // not streamable to this caller. Signing for the owner is not an option+ // β `signUserJWT` mints full account access.+ if (+ await isOperationOwnedByAnotherUser({+ db: ctx.serverDB,+ operationId: runningOperation.operationId,+ userId: ctx.userId,+ })+ ) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'The running operation on this topic belongs to another user',+ });+ }+const token = await signUserJWT(ctx.userId);return { token };diff --git a/apps/server/src/routers/lambda/topic/update.settleRunningOperation.test.ts b/apps/server/src/routers/lambda/topic/update.settleRunningOperation.test.tsnew file mode 100644index 00000000000..0536cbc5ceb--- /dev/null+++ b/apps/server/src/routers/lambda/topic/update.settleRunningOperation.test.ts@@ -0,0 +1,120 @@+// @vitest-environment node+import { type LobeChatDatabase } from '@lobechat/database';+import { agentOperations, topics, workspaces } from '@lobechat/database/schemas';+import { getTestDB } from '@lobechat/database/test-utils';+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { cleanupTestUser, createTestUser } from '../__tests__/integration/setup';++let testDB: LobeChatDatabase;+vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(function () {+ return testDB;+ }),+}));++// The General-access `use` guard has its own tests; this file covers the+// run-ownership rule layered on top of it.+vi.mock('../_helpers/conversationResourceGuard', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ assertCanUseTopicTargets: vi.fn(async () => []),+}));++// A live run whose non-fatal `agent_operations` insert failed is known only to+// the runtime state.+const mockGetOperationMetadata = vi.hoisted(() => vi.fn());+vi.mock('@/server/modules/AgentRuntime/factory', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ createAgentStateManager: () => ({ getOperationMetadata: mockGetOperationMetadata }),+}));++const { topicRouter } = await import('./index');++describe('topic.settleRunningOperation in a workspace', () => {+ let starterId: string;+ let teammateId: string;+ let workspaceId: string;++ beforeEach(async () => {+ testDB = await getTestDB();+ starterId = await createTestUser(testDB);+ teammateId = await createTestUser(testDB);+ const [workspace] = await testDB+ .insert(workspaces)+ .values({ name: 'Team', primaryOwnerId: starterId, slug: `ws-settle-${starterId}` })+ .returning();+ workspaceId = workspace.id;+ });++ afterEach(async () => {+ mockGetOperationMetadata.mockReset();+ await cleanupTestUser(testDB, teammateId);+ await cleanupTestUser(testDB, starterId);+ });++ /** A workspace topic whose run, started by `starterId`, waits on a human. */+ const seedWaitingRun = async () => {+ const operationId = `op-${starterId}`;+ const [topic] = await testDB+ .insert(topics)+ .values({+ metadata: {+ runningOperation: {+ assistantMessageId: 'msg-1',+ operationId,+ startedAt: new Date().toISOString(),+ },+ },+ status: 'running',+ title: 'Waiting',+ userId: starterId,+ workspaceId,+ })+ .returning();+ await testDB.insert(agentOperations).values({+ id: operationId,+ status: 'waiting_for_human',+ topicId: topic.id,+ userId: starterId,+ workspaceId,+ });+ return { operationId, topicId: topic.id };+ };++ const readMarker = async (topicId: string) => {+ const [row] = await testDB.select().from(topics).where(eq(topics.id, topicId));+ return row.metadata?.runningOperation?.operationId;+ };++ it("does not let a teammate clear another member's live run", async () => {+ const { operationId, topicId } = await seedWaitingRun();+ const caller = topicRouter.createCaller({ userId: teammateId, workspaceId } as any);++ await expect(+ caller.settleRunningOperation({ id: topicId, operationId, status: 'active' }),+ ).resolves.toEqual({ activeOperationId: operationId, status: 'not_owner' });+ expect(await readMarker(topicId)).toBe(operationId);+ });++ it('still settles for the member who started the run', async () => {+ const { operationId, topicId } = await seedWaitingRun();+ const caller = topicRouter.createCaller({ userId: starterId, workspaceId } as any);++ await caller.settleRunningOperation({ id: topicId, operationId, status: 'active' });++ expect(await readMarker(topicId)).toBeUndefined();+ });++ it("guards a teammate's unpersisted run by its runtime metadata", async () => {+ const { operationId, topicId } = await seedWaitingRun();+ await testDB.delete(agentOperations).where(eq(agentOperations.id, operationId));+ mockGetOperationMetadata.mockResolvedValue({ userId: starterId });+ const caller = topicRouter.createCaller({ userId: teammateId, workspaceId } as any);++ await expect(+ caller.settleRunningOperation({ id: topicId, operationId, status: 'active' }),+ ).resolves.toEqual({ activeOperationId: operationId, status: 'not_owner' });+ expect(await readMarker(topicId)).toBe(operationId);+ });+});diff --git a/apps/server/src/routers/lambda/topic/update.ts b/apps/server/src/routers/lambda/topic/update.tsindex 8f42b1e9c8a..11e74081630 100644--- a/apps/server/src/routers/lambda/topic/update.ts+++ b/apps/server/src/routers/lambda/topic/update.ts@@ -16,6 +16,7 @@ import {assertCanUseConversationTargets,assertCanUseTopicTargets,} from '../_helpers/conversationResourceGuard';+import { isOperationOwnedByAnotherUser } from '../_helpers/operationReadGuard';import { resolveContext } from '../_helpers/resolveContext';import { assertCreatorTopicTargets } from '../_helpers/shareVisitorTargetGuard';import { guardCtx, topicProcedure } from './procedures';@@ -185,6 +186,21 @@ export const updateRouter = router({// Same visitor guard as `batchMoveTopics`/`cloneTopic` above.await assertCreatorTopicTargets(guardCtx(ctx), [input.id]);+ // Only the member who started the run may report its end. A teammate's+ // tab watching the same workspace topic has no stream to learn the end+ // from (the gateway refuses it), so any terminal it reports is a guess;+ // the in-flight check below does not cover `idle` / `waiting_for_human`,+ // where such a guess would drop a live run's marker.+ if (+ await isOperationOwnedByAnotherUser({+ db: ctx.serverDB,+ operationId: input.operationId,+ userId: ctx.userId,+ })+ ) {+ return { activeOperationId: input.operationId, status: 'not_owner' as const };+ }+// Client-reported end: never clear the marker of a run the server is still// driving (an early / mirrored terminal event would otherwise drop the// supervisor's topic reservation mid group turn).diff --git a/src/hooks/useGatewayReconnect.ts b/src/hooks/useGatewayReconnect.tsindex 95f77268b9b..cb7e507b2d4 100644--- a/src/hooks/useGatewayReconnect.ts+++ b/src/hooks/useGatewayReconnect.ts@@ -70,10 +70,12 @@ 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'),+ // Never retry the stale-marker case (operation already gone β NOT_FOUND) or a+ // teammate's run the gateway will not stream to this user (FORBIDDEN), even if+ // either 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') && !isTrpcErrorCode(error, 'FORBIDDEN'),},);};diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.reconnectTeammateRun.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.reconnectTeammateRun.test.tsnew file mode 100644index 00000000000..c021aca0184--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.reconnectTeammateRun.test.ts@@ -0,0 +1,152 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import type * as ConstVersion from '@/const/version';+import { aiAgentService } from '@/services/aiAgent';+import { topicService } from '@/services/topic';++import { GatewayActionImpl } from '../transports/gateway/gateway';++vi.mock('../transports/gateway/serverSteerQueue', () => ({+ reclaimServerQueuedMessages: vi.fn().mockResolvedValue(undefined),+ restoreServerQueuedMessages: vi.fn(),+ withdrawQueuedMessage: vi.fn(),+}));++vi.mock('@/services/aiAgent', () => ({+ aiAgentService: { execAgentTask: vi.fn(), interruptTask: vi.fn(), refreshGatewayToken: vi.fn() },+}));++vi.mock('@/services/shareChat', () => ({+ shareChatService: { interruptTask: vi.fn(), refreshGatewayToken: vi.fn() },+}));++vi.mock('@/services/message', () => ({+ messageService: { getMessages: vi.fn().mockResolvedValue([]) },+}));++vi.mock('@/services/topic', () => ({+ topicService: {+ getTopicDetail: vi.fn().mockResolvedValue(null),+ settleRunningOperation: vi.fn().mockResolvedValue(undefined),+ updateTopicMetadata: vi.fn().mockResolvedValue(undefined),+ },+}));++vi.mock('@/store/file/store', () => ({+ getFileStoreState: () => ({ moveChatContextSelections: vi.fn() }),+}));++const mockUserState = vi.hoisted(() => ({+ profile: { id: 'user-viewer' },+ workspaceUserPreference: { agentDeviceOverrides: {} as Record<string, any> },+}));++vi.mock('@/store/user', () => ({ useUserStore: { getState: vi.fn(() => mockUserState) } }));++vi.mock('@/store/user/selectors', () => ({+ labPreferSelectors: { enableGatewayMux: () => false },+ settingsSelectors: { defaultAgentConfig: () => ({ chatConfig: {} }) },+ toolInterventionSelectors: { allowList: () => [], approvalMode: () => 'manual' },+ userProfileSelectors: { userId: (state: typeof mockUserState) => state.profile.id },+}));++vi.mock('@/const/version', async (importOriginal) => ({+ ...(await importOriginal<typeof ConstVersion>()),+ isDesktop: false,+}));++vi.mock('@/services/electron/gatewayConnection', () => ({+ gatewayConnectionService: { getDeviceInfo: vi.fn() },+}));++vi.mock('@/store/agent', () => ({+ getAgentStoreState: () => ({ activeAgentId: undefined, agentMap: {} }),+}));++vi.mock('@/store/agent/selectors', () => ({+ agentByIdSelectors: {+ getAgencyConfigById: () => () => undefined,+ getAgentById: () => () => undefined,+ },+ agentSelectors: { currentAgentWorkingDirectory: () => () => undefined },+ chatConfigByIdSelectors: {+ getChatConfigById: () => () => ({}),+ isChatModeById: () => () => false,+ isLocalSystemEnabledById: () => () => false,+ },+}));++afterEach(() => {+ vi.clearAllMocks();+ delete (globalThis as any).window;+});++/** A workspace topic another member's run still holds, opened in this tab. */+const createHarness = () => {+ const connectToGateway = vi.fn();+ const completeOperation = vi.fn();+ const internalDispatchTopic = vi.fn();+ const state: Record<string, any> = {+ activeAgentId: 'agent-1',+ activeTopicId: 'topic-1',+ gatewayConnections: {},+ messagesMap: {},+ topicDataMap: {+ 'agent_agent-1': {+ items: [+ {+ id: 'topic-1',+ metadata: {+ runningOperation: { assistantMessageId: 'ast-1', operationId: 'teammate-op' },+ },+ },+ ],+ },+ },+ };+ const get = vi.fn(() => ({+ ...state,+ associateMessageWithOperation: vi.fn(),+ completeOperation,+ connectToGateway,+ internal_dispatchTopic: internalDispatchTopic,+ internal_pinTopicStatus: vi.fn(),+ onOperationCancel: vi.fn(),+ startOperation: vi.fn(() => ({ operationId: 'gw-op-reconnect' })),+ })) as any;++ (globalThis as any).window = {+ global_serverConfigStore: {+ getState: () => ({ serverConfig: { agentGatewayUrl: 'https://gateway.test.com' } }),+ },+ };++ const action = new GatewayActionImpl(vi.fn() as any, get, undefined);+ return { action, completeOperation, connectToGateway, internalDispatchTopic };+};++describe("reconnecting to a workspace teammate's run", () => {+ // Regression (T-1102): the server signed a token the gateway refused, the+ // auth_failed close was read as a dead run, the tab cleared the marker and+ // settled the teammate's run, and the next topic refresh brought the marker+ // back β reconnecting forever. The server now answers FORBIDDEN instead.+ it('keeps the marker, retires the local op and does not connect or settle', async () => {+ const { action, completeOperation, connectToGateway, internalDispatchTopic } = createHarness();+ vi.mocked(aiAgentService.refreshGatewayToken).mockRejectedValueOnce({+ data: { code: 'FORBIDDEN' },+ });++ await expect(+ action.reconnectToGatewayOperation({+ assistantMessageId: 'ast-1',+ operationId: 'teammate-op',+ topicId: 'topic-1',+ }),+ ).resolves.toBeUndefined();++ expect(completeOperation).toHaveBeenCalledWith('gw-op-reconnect');+ expect(internalDispatchTopic).not.toHaveBeenCalled();+ expect(connectToGateway).not.toHaveBeenCalled();+ expect(topicService.settleRunningOperation).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.tsindex 918a32eb3d8..67d210e1fe7 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -1889,11 +1889,10 @@ export class GatewayActionImpl {});});- // 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.+ // Get a fresh JWT token (original expired after 5 min). NOT_FOUND: no running+ // operation on this topic, so the local marker is stale β clear it. FORBIDDEN:+ // a workspace teammate's live run the gateway only streams to its starter β+ // keep the marker. Both bail silently so the reconnect SWR fetcher resolves.let token: string;try {// Share visitors have no owner-scoped access to `aiAgentService.refreshGatewayToken`@@ -1917,6 +1916,7 @@ export class GatewayActionImpl {this.clearLocalRunningOperation({ operationId, topicId });return;}+ if (isTrpcErrorCode(error, 'FORBIDDEN')) return;throw error;}