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(agent): keep the topic running mark owned by the main run (#18039)

Arvin Xu435f5eb4d004
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.test.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.test.ts
new file mode 100644
index 00000000000..cf33e9d8e13
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.test.ts
@@ -0,0 +1,78 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { LobeChatDatabase } from '@/database/type';
+
+import { ServerOperationStore } from './ServerOperationStore';
+
+const topicMock = {
+ findById: vi.fn(),
+ updateMetadata: vi.fn(),
+};
+
+vi.mock('@/database/models/topic', () => ({
+ TopicModel: vi.fn().mockImplementation(() => topicMock),
+}));
+
+const db = {} as LobeChatDatabase;
+
+const createStore = (operationId: string | undefined, topicId: string | undefined = 'topic-1') =>
+ new ServerOperationStore(db, 'user-1', undefined, topicId, operationId);
+
+const createTopiclessStore = () =>
+ new ServerOperationStore(db, 'user-1', undefined, undefined, 'op-main');
+
+const markedWith = (operationId: string) => ({
+ metadata: { runningOperation: { assistantMessageId: 'asst-1', operationId } },
+});
+
+describe('ServerOperationStore', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ topicMock.updateMetadata.mockResolvedValue(undefined);
+ });
+
+ describe('clearRunningMark', () => {
+ it('clears the mark when this operation owns it', async () => {
+ topicMock.findById.mockResolvedValue(markedWith('op-main'));
+
+ await createStore('op-main').clearRunningMark();
+
+ expect(topicMock.updateMetadata).toHaveBeenCalledWith('topic-1', { runningOperation: null });
+ });
+
+ it('leaves the mark alone when it belongs to another operation', async () => {
+ // Regression: a `callSubAgent` / group-member child runs in an isolation
+ // thread on its PARENT's topic and finishes minutes before the parent. The
+ // unconditional clear wiped the parent's reconnect anchor mid-run, so every
+ // later client open saw no `runningOperation`, never opened a gateway
+ // WebSocket, and rendered a frozen REST snapshot until the run ended.
+ topicMock.findById.mockResolvedValue(markedWith('op-parent'));
+
+ await createStore('op-child').clearRunningMark();
+
+ expect(topicMock.updateMetadata).not.toHaveBeenCalled();
+ });
+
+ it('is a no-op when the topic carries no mark', async () => {
+ topicMock.findById.mockResolvedValue({ metadata: {} });
+
+ await createStore('op-main').clearRunningMark();
+
+ expect(topicMock.updateMetadata).not.toHaveBeenCalled();
+ });
+
+ it('skips the lookup entirely without a topic', async () => {
+ await createTopiclessStore().clearRunningMark();
+
+ expect(topicMock.findById).not.toHaveBeenCalled();
+ expect(topicMock.updateMetadata).not.toHaveBeenCalled();
+ });
+
+ it('swallows lookup failures β€” clearing the mark is best-effort', async () => {
+ topicMock.findById.mockRejectedValue(new Error('db down'));
+
+ await expect(createStore('op-main').clearRunningMark()).resolves.toBeUndefined();
+ expect(topicMock.updateMetadata).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.ts
index 83a93ecada1..b614681b515 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerOperationStore.ts
@@ -15,13 +15,32 @@ export class ServerOperationStore implements OperationStore {
private readonly userId: string | undefined,
private readonly workspaceId: string | undefined,
private readonly topicId: string | undefined,
+ private readonly operationId: string | undefined,
private readonly loadAgentState?: (operationId: string) => Promise<AgentState | null>,
) {}
+ /**
+ * Compare-and-clear: only the operation the mark points at may clear it.
+ *
+ * A topic can host several concurrent operations β€” a `callAgent` /
+ * `callSubAgent` / group-member run executes in an isolation thread on its
+ * parent's topic and finishes long before the parent does. Clearing
+ * unconditionally there wiped the parent's reconnect anchor mid-run, so every
+ * later client open found no `runningOperation`, never opened a gateway
+ * WebSocket, and rendered a frozen REST snapshot for the rest of the run.
+ *
+ * Mirrors the ownership guard the abandon path already applies
+ * (`AbandonOperationService`).
+ */
async clearRunningMark(): Promise<void> {
if (!this.topicId || !this.userId) return;
try {
const topicModel = new TopicModel(this.serverDB, this.userId, this.workspaceId);
+ const topic = await topicModel.findById(this.topicId);
+ const markedOperationId = topic?.metadata?.runningOperation?.operationId;
+ // No mark (already cleared) or someone else's mark β€” nothing of ours to drop.
+ if (!markedOperationId || markedOperationId !== this.operationId) return;
+
await topicModel.updateMetadata(this.topicId, { runningOperation: null });
} catch {
// best-effort β€” swallow
diff --git a/apps/server/src/modules/AgentRuntime/buildHost.ts b/apps/server/src/modules/AgentRuntime/buildHost.ts
index baac6c1422a..4f8c848548c 100644
--- a/apps/server/src/modules/AgentRuntime/buildHost.ts
+++ b/apps/server/src/modules/AgentRuntime/buildHost.ts
@@ -57,6 +57,7 @@ export const buildHost = (ctx: RuntimeExecutorContext): AgentRuntimeHost => {
ctx.userId,
ctx.workspaceId,
ctx.topicId,
+ ctx.operationId,
ctx.loadAgentState,
),
stream: new ServerStreamSink(ctx.streamManager, ctx.operationId),
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.threadId.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.threadId.test.ts
index 49a55740d31..4426d1b59f8 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.threadId.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.threadId.test.ts
@@ -4,8 +4,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { AiAgentService } from '../index';
// Use vi.hoisted to ensure mock functions are available before vi.mock runs
-const { mockMessageCreate } = vi.hoisted(() => ({
+const { mockMessageCreate, mockTopicUpdateMetadata } = vi.hoisted(() => ({
mockMessageCreate: vi.fn(),
+ mockTopicUpdateMetadata: vi.fn(),
}));
// Mock trusted client to avoid server-side env access
@@ -70,7 +71,7 @@ vi.mock('@/database/models/topic', () => ({
TopicModel: vi.fn().mockImplementation(() => ({
create: vi.fn().mockResolvedValue({ id: 'topic-1' }),
findById: vi.fn().mockResolvedValue(undefined),
- updateMetadata: vi.fn().mockResolvedValue(undefined),
+ updateMetadata: mockTopicUpdateMetadata,
})),
}));
@@ -172,6 +173,8 @@ describe('AiAgentService.execAgent - threadId handling', () => {
// Explicitly clear the shared mock to prevent state pollution between tests
mockMessageCreate.mockClear();
mockMessageCreate.mockResolvedValue({ id: 'msg-1' });
+ mockTopicUpdateMetadata.mockClear();
+ mockTopicUpdateMetadata.mockResolvedValue(undefined);
service = new AiAgentService(mockDb, userId);
});
@@ -228,6 +231,40 @@ describe('AiAgentService.execAgent - threadId handling', () => {
});
});
+ describe('topic running mark', () => {
+ const runningMarkCalls = () =>
+ mockTopicUpdateMetadata.mock.calls.filter((call) => 'runningOperation' in (call[1] ?? {}));
+
+ it('claims the mark for a main-conversation run', async () => {
+ await service.execAgent({
+ agentId: 'agent-1',
+ appContext: { topicId: 'topic-1' },
+ prompt: 'Test prompt',
+ });
+
+ expect(runningMarkCalls()).toHaveLength(1);
+ expect(runningMarkCalls()[0][1].runningOperation).toMatchObject({
+ assistantMessageId: 'msg-1',
+ operationId: expect.stringContaining('op_'),
+ });
+ });
+
+ it('does not claim the mark for an isolation-thread run', async () => {
+ // A callAgent / callSubAgent / group-member child executes on the PARENT's
+ // topic. Claiming the mark pointed every client reconnect at the child's
+ // thread stream, and clearing it on the child's (much earlier) finish left
+ // the still-running parent with no reconnect anchor at all β€” the run drawer
+ // then never opened a gateway WebSocket for the rest of the run.
+ await service.execAgent({
+ agentId: 'agent-1',
+ appContext: { isolationThread: true, threadId: 'thread-123', topicId: 'topic-1' },
+ prompt: 'Test prompt',
+ });
+
+ expect(runningMarkCalls()).toHaveLength(0);
+ });
+ });
+
describe('when threadId is not provided in appContext', () => {
it('should create user message without threadId', async () => {
await service.execAgent({
diff --git a/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts b/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts
index 031143e9918..9ba3f14a796 100644
--- a/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts
@@ -217,6 +217,8 @@ describe('AiAgentService.execSubAgent', () => {
agentId: 'agent-1',
appContext: {
groupId: 'group-1',
+ // Guest on the parent's topic β€” must not claim its running mark.
+ isolationThread: true,
isSubAgent: false,
threadId: 'thread-123',
topicId: 'topic-1',
@@ -260,6 +262,7 @@ describe('AiAgentService.execSubAgent', () => {
expect(execAgentSpy).toHaveBeenCalledWith(
expect.objectContaining({
appContext: expect.objectContaining({
+ isolationThread: true,
isSubAgent: true,
threadId: 'thread-123',
topicId: 'topic-1',
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index c3eed1a59f9..2947b3758db 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -4481,15 +4481,26 @@ 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,
- },
- });
+ // Persist running operation to topic metadata for reconnect after page reload.
+ //
+ // Skipped for isolation-thread children (callAgent / callSubAgent / group
+ // members): they run on the SPAWNER's topic and finish long before it does,
+ // so claiming the mark would first point every client reconnect at the
+ // child's thread stream, and then β€” once the child finished and cleared it β€”
+ // leave the still-running parent with no mark at all, i.e. no gateway
+ // WebSocket for the rest of the run. The parent's mark stays authoritative;
+ // a child's live progress already rides down the parent channel via
+ // `appContext.subAgentProgress`.
+ if (!appContext?.isolationThread) {
+ 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;
@@ -4987,6 +4998,10 @@ export class AiAgentService {
const appContext: NonNullable<InternalExecAgentParams['appContext']> = {
groupId,
+ // Every run spawned here executes in an isolation thread on the SPAWNER's
+ // topic, so it must not touch that topic's `runningOperation` mark β€” that
+ // mark is the main run's reconnect anchor (see execAgent).
+ isolationThread: true,
isSubAgent: options.isSubAgent,
orchestrationRole: options.orchestrationRole,
subAgentProgress,
diff --git a/packages/agent-runtime/src/transport/operation.ts b/packages/agent-runtime/src/transport/operation.ts
index ad153ca1b91..5f7d760963e 100644
--- a/packages/agent-runtime/src/transport/operation.ts
+++ b/packages/agent-runtime/src/transport/operation.ts
@@ -28,6 +28,15 @@ export interface RuntimeOperationContext {
* (interruption guard) joins here when call_tool / call_llm migrate.
*/
export interface OperationStore {
+ /**
+ * Drop the topic's running mark β€” but ONLY when this operation owns it.
+ * Several operations share one topic (a `callAgent` / `callSubAgent` / group
+ * member run executes in an isolation thread on its parent's topic), and the
+ * mark is the *main* run's reconnect anchor. An unconditional clear here lets
+ * a short-lived child strand its still-running parent: no mark means no
+ * gateway reconnect, so the conversation goes silent for the rest of the run.
+ * Implementations must compare before clearing.
+ */
clearRunningMark: () => Promise<void>;
loadState?: (operationId: string) => Promise<AgentState | null>;
}
diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.ts
index 435931fb933..ff7fc7fd71c 100644
--- a/packages/types/src/agentExecution/index.ts
+++ b/packages/types/src/agentExecution/index.ts
@@ -96,6 +96,16 @@ export interface ExecAgentAppContext {
workingDirectory?: string;
workingDirectoryConfig?: WorkingDirConfig;
};
+ /**
+ * Whether this operation runs inside an isolation thread spawned by another
+ * operation on the same topic (callAgent / callSubAgent / group member).
+ *
+ * Such a run is a guest on its parent's topic: it must not claim or clear the
+ * topic's `runningOperation` mark, which is the parent run's gateway reconnect
+ * anchor. Broader than `isSubAgent` on purpose β€” the `execSubAgent` (callAgent)
+ * path passes `isSubAgent: false` yet is just as much a guest.
+ */
+ isolationThread?: boolean;
/**
* Whether this operation is an isolated sub-agent execution. Used to disable
* recursive sub-agent dispatch.
diff --git a/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.test.tsx b/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.test.tsx
index 21d15586aa7..e0461b8d08d 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.test.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.test.tsx
@@ -1,10 +1,13 @@
/**
* @vitest-environment happy-dom
*/
+import type { TaskDetailActivity } from '@lobechat/types';
import { render } from '@testing-library/react';
import type { CSSProperties, ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { useGatewayReconnect } from '@/hooks/useGatewayReconnect';
+
import TopicChatDrawer from './index';
const mocks = vi.hoisted(() => ({
@@ -39,7 +42,7 @@ const mocks = vi.hoisted(() => ({
title: 'Topic 1',
type: 'topic',
},
- ],
+ ] as TaskDetailActivity[],
agentId: 'agt_assignee',
identifier: 'T-1',
instruction: 'Do the task',
@@ -248,8 +251,38 @@ describe('TopicChatDrawer', () => {
mocks.chatState.replaceMessages.mockClear();
mocks.taskState.closeTopicDrawer.mockClear();
mocks.taskState.activeTopicDrawerTopicId = 'topic-1';
+ mocks.taskState.taskDetailMap['T-1'].activities[0] = {
+ id: 'topic-1',
+ status: 'completed',
+ time: '2026-04-29T00:00:00.000Z',
+ title: 'Topic 1',
+ type: 'topic',
+ };
mocks.permission.allowed = true;
mocks.serverConfigState.serverConfig.enableBusinessFeatures = false;
+ vi.mocked(useGatewayReconnect).mockClear();
+ });
+
+ // The run drawer also mounts on the home inbox, where the chat store has no
+ // active agent β€” reconnecting against it would stream the run into a bucket
+ // this panel never reads, so the run's own agent has to be passed down.
+ it('reconnects a running topic against the drawer agent', () => {
+ mocks.taskState.taskDetailMap['T-1'].activities[0] = {
+ id: 'topic-1',
+ runningOperation: { assistantMessageId: 'ast-1', operationId: 'op-1' },
+ status: 'running',
+ time: '2026-04-29T00:00:00.000Z',
+ title: 'Topic 1',
+ type: 'topic',
+ };
+
+ render(<TopicChatDrawer />);
+
+ expect(useGatewayReconnect).toHaveBeenCalledWith(
+ 'topic-1',
+ expect.objectContaining({ operationId: 'op-1' }),
+ 'agt_assignee',
+ );
});
it('hydrates the task assignee agent config for drawer messages', () => {
diff --git a/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.tsx b/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.tsx
index 54a9883a94e..43afc52815a 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.tsx
@@ -65,7 +65,9 @@ export const TopicChatDrawerBody = memo<TopicChatDrawerBodyProps>(
const runningOperation = useTaskStore(
(s) => taskActivitySelectors.activeDrawerTopicActivity(s)?.runningOperation,
);
- useGatewayReconnect(topicId, runningOperation);
+ // Pass this drawer's agent explicitly β€” the run drawer also mounts on the
+ // home surface, where the chat store's `activeAgentId` is unset.
+ useGatewayReconnect(topicId, runningOperation, agentId);
const itemContent = useCallback(
(index: number, id: string) => (
diff --git a/src/hooks/useGatewayReconnect.ts b/src/hooks/useGatewayReconnect.ts
index 3ae121cc320..d8aa5bc5cce 100644
--- a/src/hooks/useGatewayReconnect.ts
+++ b/src/hooks/useGatewayReconnect.ts
@@ -29,6 +29,12 @@ interface RunningOperation {
export const useGatewayReconnect = (
topicId: string | null | undefined,
runningOperation: RunningOperation | null | undefined,
+ /**
+ * Agent owning the rendered conversation. Required off the agent route (task
+ * detail / home run drawer), where the chat store's `activeAgentId` is stale or
+ * unset β€” see `reconnectToGatewayOperation`.
+ */
+ agentId?: string,
) => {
const agentGatewayUrl = useServerConfigStore((s) => s.serverConfig.agentGatewayUrl);
@@ -40,6 +46,7 @@ export const useGatewayReconnect = (
if (!runningOperation || !topicId) return;
await useChatStore.getState().reconnectToGatewayOperation({
+ agentId,
assistantMessageId: runningOperation.assistantMessageId,
operationId: runningOperation.operationId,
scope: runningOperation.scope,
diff --git a/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx b/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx
index d0e9eae6f3b..59e59303d21 100644
--- a/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx
+++ b/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx
@@ -99,7 +99,7 @@ const Conversation = memo(() => {
? topicSelectors.getTopicById(context.topicId)(s)?.metadata?.runningOperation
: undefined,
);
- useGatewayReconnect(context.topicId, runningOperation);
+ useGatewayReconnect(context.topicId, runningOperation, context.agentId);
// While the topic is parked as `scheduled`, pull the cron dispatch into the
// store when `runAt` passes β€” nothing pushes it, and the reconnect above
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 395909a083f..872a336f664 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
@@ -1678,6 +1678,42 @@ describe('GatewayActionImpl', () => {
);
});
+ // Surfaces that mount the run drawer off the agent route (task detail, home
+ // inbox) own an agent the chat store knows nothing about β€” `activeAgentId` is
+ // whatever the last agent page left behind, or undefined on home. Binding the
+ // run to it streams every event into a bucket no one renders, so the panel
+ // stays frozen even though the WebSocket is live.
+ it('binds the run to the caller-provided agent', async () => {
+ const { action, startOperation } = createReconnectTestAction({ createdAt: 1, id: 'ast-1' });
+
+ await action.reconnectToGatewayOperation({
+ agentId: 'agent-drawer',
+ assistantMessageId: 'ast-1',
+ operationId: 'server-op-1',
+ topicId: 'topic-1',
+ });
+
+ expect(startOperation).toHaveBeenCalledWith(
+ expect.objectContaining({
+ context: expect.objectContaining({ agentId: 'agent-drawer', topicId: 'topic-1' }),
+ }),
+ );
+ });
+
+ it('falls back to the active agent when the caller passes none', async () => {
+ const { action, startOperation } = createReconnectTestAction({ createdAt: 1, id: 'ast-1' });
+
+ await action.reconnectToGatewayOperation({
+ assistantMessageId: 'ast-1',
+ operationId: 'server-op-1',
+ topicId: 'topic-1',
+ });
+
+ expect(startOperation).toHaveBeenCalledWith(
+ expect.objectContaining({ context: expect.objectContaining({ agentId: 'agent-1' }) }),
+ );
+ });
+
// Captures the onSessionComplete handed to connectToGateway so we can drive
// both close paths directly. Provides the methods that callback reaches.
function createOnSessionCompleteHarness() {
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 71f7e491439..d2b36578c13 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -845,6 +845,14 @@ export class GatewayActionImpl {
* and establishes a new WebSocket connection with event replay.
*/
reconnectToGatewayOperation = async (params: {
+ /**
+ * Agent that owns the rendered conversation. Callers outside the agent route
+ * (task detail / home run drawer) MUST pass it: `activeAgentId` is whatever
+ * the last agent page left behind β€” `undefined` on the home surface β€” and the
+ * streamed messages would land in a `main_undefined_<topicId>` bucket nobody
+ * renders, leaving a connected-but-frozen panel.
+ */
+ agentId?: string;
assistantMessageId: string;
operationId: string;
scope?: string;
@@ -899,7 +907,7 @@ export class GatewayActionImpl {
?.runningOperation?.operationId;
if (topicOpIdAfterRefresh && topicOpIdAfterRefresh !== operationId) return;
- const agentId = this.#get().activeAgentId;
+ const agentId = params.agentId ?? this.#get().activeAgentId;
const context = {
agentId,
scope: (scope ?? 'main') as ConversationContext['scope'],