π€― 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(agent-share): clear visitor topic running marks and refuse stale reconnects (#19140)
YuTengjing13316907a1a6
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.test.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.test.tsindex 554fe149d1e..a48da102af4 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.test.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.test.ts@@ -1,5 +1,6 @@import { beforeEach, describe, expect, it, vi } from 'vitest';+import { TopicModel } from '@/database/models/topic';import type { LobeChatDatabase } from '@/database/type';import { ServerOperationStore } from './ServerOperationStore';@@ -32,6 +33,22 @@ describe('ServerOperationStore', () => {});describe('clearRunningMark', () => {+ // Regression: agent-share visitor runs execute under the creator's userId+ // on a topic whose `senderId` is the visitor. The default topic scope hides+ // those rows, so `findById` returned nothing, the clear silently bailed,+ // and every visitor topic kept a stale `runningOperation` forever β each+ // later open reconnected to a finished run and froze the message list.+ it('looks the topic up with the share-visitor scope so visitor topics can be cleared', async () => {+ topicMock.findById.mockResolvedValue(markedWith('op-main'));++ await createStore('op-main').clearRunningMark();++ expect(TopicModel).toHaveBeenCalledWith(db, 'user-1', undefined, undefined, {+ includeShareVisitor: true,+ });+ expect(topicMock.settleRunningOperation).toHaveBeenCalledWith('topic-1', 'op-main', 'unread');+ });+it('clears the mark when this operation owns it', async () => {topicMock.findById.mockResolvedValue(markedWith('op-main'));diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.tsindex 30f9fa6cca6..03b71ac0714 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.ts@@ -35,7 +35,17 @@ export class ServerOperationStore implements OperationStore {async clearRunningMark(): Promise<void> {if (!this.topicId || !this.userId) return;try {- const topicModel = new TopicModel(this.serverDB, this.userId, this.workspaceId);+ // Agent-share visitor runs execute under the CREATOR's userId on a topic+ // whose `senderId` is the visitor. The default topic scope hides those+ // rows, so without the opt-in `findById` returned nothing here, the+ // early return below treated it as "already cleared", and every visitor+ // topic kept its `runningOperation` marker forever β each later open+ // reconnected to a finished run and froze the visitor's message list.+ // Widening is safe: the compare-and-clear below still requires the mark+ // to name this very operation.+ const topicModel = new TopicModel(this.serverDB, this.userId, this.workspaceId, undefined, {+ includeShareVisitor: true,+ });const topic = await topicModel.findById(this.topicId);const marker = topic?.metadata?.runningOperation;const markedOperationId = marker?.operationId;diff --git a/apps/server/src/routers/lambda/__tests__/shareChat.test.ts b/apps/server/src/routers/lambda/__tests__/shareChat.test.tsindex 5e8597b6291..233e7113f13 100644--- a/apps/server/src/routers/lambda/__tests__/shareChat.test.ts+++ b/apps/server/src/routers/lambda/__tests__/shareChat.test.ts@@ -53,9 +53,11 @@ vi.mock('@/database/models/agentShare', () => ({const mockFindById = vi.fn();const mockCountBySender = vi.fn();const mockQueryBySender = vi.fn();+const mockIsRunningOperationAlive = vi.fn();const TopicModelMock = vi.fn(() => ({countBySender: mockCountBySender,findById: mockFindById,+ isRunningOperationAlive: mockIsRunningOperationAlive,queryBySender: mockQueryBySender,}));vi.mock('@/database/models/topic', () => ({@@ -144,6 +146,7 @@ describe('shareChatRouter', () => {mockGetFeatureFlagsState.mockResolvedValue({ enableAgentShare: true });mockAccessCheck.mockResolvedValue(share);mockFindById.mockResolvedValue(visitorTopic);+ mockIsRunningOperationAlive.mockResolvedValue(true);mockCountBySender.mockResolvedValue(0);mockQueryBySender.mockResolvedValue([]);mockMessageCountByTopic.mockResolvedValue(0);@@ -538,6 +541,23 @@ describe('shareChatRouter', () => {).rejects.toMatchObject({ code: 'NOT_FOUND' });expect(mockSignUserJWT).not.toHaveBeenCalled();});++ // The marker is cleared best-effort at finish, so a stale one must not+ // send the visitor's browser to reconnect to a finished run (it would+ // register the topic as "running" locally and freeze its message list).+ it('rejects when the marker points at a run that already ended', async () => {+ mockIsRunningOperationAlive.mockResolvedValue(false);+ const caller = await createCaller();++ await expect(+ caller.refreshGatewayToken({ shareId: 'share-1', topicId: 'tpc_visitor' }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect(mockIsRunningOperationAlive).toHaveBeenCalledWith(+ expect.anything(),+ visitorTopic.metadata.runningOperation,+ );+ expect(mockSignUserJWT).not.toHaveBeenCalled();+ });});it('requires authentication', async () => {diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.tsindex 413c7e28814..685d3e8fd11 100644--- a/apps/server/src/routers/lambda/aiAgent.ts+++ b/apps/server/src/routers/lambda/aiAgent.ts@@ -3700,7 +3700,14 @@ export const aiAgentRouter = router({// `shareChat.refreshGatewayToken` instead.const topic = await ctx.topicModel.findOwnTopicById(input.topicId);- if (!topic?.metadata?.runningOperation) {+ // Same liveness check as `shareChat.refreshGatewayToken`: the marker is+ // cleared best-effort, so refuse to reconnect a client to a run that has+ // already ended β the client treats NOT_FOUND as "stale marker, clear it".+ const runningOperation = topic?.metadata?.runningOperation;+ if (+ !runningOperation ||+ !(await ctx.topicModel.isRunningOperationAlive(ctx.serverDB, runningOperation))+ ) {throw new TRPCError({code: 'NOT_FOUND',message: 'No running operation found on this topic',diff --git a/apps/server/src/routers/lambda/shareChat.ts b/apps/server/src/routers/lambda/shareChat.tsindex f55d410747c..605c8843d9e 100644--- a/apps/server/src/routers/lambda/shareChat.ts+++ b/apps/server/src/routers/lambda/shareChat.ts@@ -505,7 +505,16 @@ export const shareChatRouter = router({visitorUserId: ctx.userId,});- if (!topic.metadata?.runningOperation) {+ // A present marker is not proof of a live run: it is cleared best-effort+ // at finish, so a stale one would send the visitor's browser to reconnect+ // to a finished operation, register it as "running" locally, and drop the+ // topic's fetched history as in-flight noise (a frozen skeleton list).+ // NOT_FOUND is what the client already treats as "stale marker, clear it".+ const runningOperation = topic.metadata?.runningOperation;+ if (+ !runningOperation ||+ !(await topicModel.isRunningOperationAlive(ctx.serverDB, runningOperation))+ ) {throw new TRPCError({code: 'NOT_FOUND',message: 'No running operation found on this topic',diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.tsindex d5f51371628..9fe90f4d8b5 100644--- a/packages/database/src/models/topic.ts+++ b/packages/database/src/models/topic.ts@@ -2072,6 +2072,10 @@ export class TopicModel {* Whether the run a `runningOperation` marker points at is still the topic's* legitimate owner.*+ * Public so the gateway-token refresh routers can refuse to reconnect a+ * client to a marker whose run has already ended (the marker is cleared+ * best-effort, so a stale one must not be taken at face value).+ ** The marker itself cannot answer this β it carries no heartbeat and is* cleared best-effort β so the authority is the operation row, which both the* in-process runtime (`createOperation`) and the heterogeneous path@@ -2082,7 +2086,7 @@ export class TopicModel {* with a marker and no row. A marker with neither a row nor a stamp cannot be* proven live and must not keep an already-stuck topic stuck.*/- private isRunningOperationAlive = async (+ isRunningOperationAlive = async (tx: Pick<LobeChatDatabase, 'select'>,runningOperation: NonNullable<ChatTopicMetadata['runningOperation']>,): Promise<boolean> => {