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: stop stale running topics without alive ops (#16816)

Arvin Xu1c7e5104efcb
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Body.tsx b/src/routes/(main)/agent/_layout/Sidebar/Body.tsx
index fe21efc4f65..041a51be560 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Body.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Body.tsx
@@ -51,7 +51,10 @@ const Body = memo(() => {
<Flexbox paddingInline={4}>
<Accordion expandedKeys={expandedKeys} gap={8} onExpandedChange={handleExpandedChange}>
<TaskList itemKey={ChatSidebarKey.Tasks} />
- <Topic itemKey={ChatSidebarKey.Topic} />
+ <Topic
+ expanded={expandedKeys.includes(ChatSidebarKey.Topic)}
+ itemKey={ChatSidebarKey.Topic}
+ />
</Accordion>
</Flexbox>
);
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/index.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/index.tsx
index 14edfba52ca..b87e266d6ac 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/index.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/index.tsx
@@ -1,7 +1,7 @@
'use client';
import { AccordionItem, ContextMenuTrigger, Flexbox, Text } from '@lobehub/ui';
-import React, { memo, Suspense } from 'react';
+import React, { memo, Suspense, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
@@ -17,14 +17,24 @@ import ToggleGroups from './ToggleGroups';
import { useTopicActionsDropdownMenu } from './useDropdownMenu';
interface TopicProps {
+ expanded: boolean;
itemKey: string;
}
-const Topic = memo<TopicProps>(({ itemKey }) => {
+const Topic = memo<TopicProps>(({ expanded, itemKey }) => {
const { t } = useTranslation(['topic', 'common']);
- const [topicCount] = useChatStore((s) => [topicSelectors.currentTopicCount(s)]);
+ const topicCount = useChatStore((s) => topicSelectors.currentTopicCount(s));
+ const cleanupStaleRunningTopics = useChatStore((s) => s.cleanupStaleRunningTopics);
const dropdownMenu = useTopicActionsDropdownMenu();
const { isRevalidating } = useFetchChatTopics();
+ const hasRunWatchdogRef = useRef(false);
+
+ useEffect(() => {
+ if (!expanded || hasRunWatchdogRef.current) return;
+
+ hasRunWatchdogRef.current = true;
+ void cleanupStaleRunningTopics();
+ }, [cleanupStaleRunningTopics, expanded]);
return (
<AccordionItem
diff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.ts
index 70f7c127eb3..35215c7e4d4 100644
--- a/src/store/chat/slices/topic/action.test.ts
+++ b/src/store/chat/slices/topic/action.test.ts
@@ -37,10 +37,12 @@ vi.mock('@/services/topic', () => ({
cloneTopic: vi.fn(),
createTopic: vi.fn(),
updateTopicFavorite: vi.fn(),
+ updateTopicMetadata: vi.fn(),
updateTopicTitle: vi.fn(),
updateTopic: vi.fn(),
batchRemoveTopics: vi.fn(),
getTopics: vi.fn(),
+ queryTopics: vi.fn(),
searchTopics: vi.fn(),
},
}));
@@ -1474,6 +1476,239 @@ describe('topic action', () => {
expect(useChatStore.getState().topicLoadingIdCounts[topicId]).toBeUndefined();
});
});
+
+ describe('cleanupStaleRunningTopics', () => {
+ it('should mark stale running topics active when no alive operation exists', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const agentId = 'agent-1';
+ const topicId = 'topic-1';
+ const key = topicMapKey({ agentId });
+ const topic = {
+ agentId,
+ createdAt: Date.now() - 3 * 60 * 60 * 1000,
+ id: topicId,
+ metadata: {
+ runningOperation: {
+ assistantMessageId: 'assistant-1',
+ operationId: 'server-op-1',
+ },
+ },
+ sessionId: agentId,
+ status: 'running',
+ title: 'Stale running topic',
+ updatedAt: Date.now() - 3 * 60 * 60 * 1000,
+ } as ChatTopic & { agentId: string };
+
+ vi.spyOn(topicService, 'queryTopics').mockResolvedValue([topic]);
+ const updateTopicMock = vi.spyOn(topicService, 'updateTopic').mockResolvedValue([]);
+ const updateTopicMetadataMock = vi
+ .spyOn(topicService, 'updateTopicMetadata')
+ .mockResolvedValue([]);
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: agentId,
+ messageOperationMap: {},
+ operations: {},
+ operationsByContext: {},
+ operationsByMessage: {},
+ topicDataMap: {
+ [key]: {
+ currentPage: 0,
+ hasMore: false,
+ items: [topic],
+ pageSize: 20,
+ total: 1,
+ },
+ },
+ });
+ });
+
+ let cleaned = 0;
+ await act(async () => {
+ cleaned = await result.current.cleanupStaleRunningTopics();
+ });
+
+ expect(cleaned).toBe(1);
+ expect(topicService.queryTopics).toHaveBeenCalledWith({
+ pageSize: 500,
+ statuses: ['running'],
+ });
+ expect(updateTopicMock).toHaveBeenCalledWith(topicId, { status: 'active' });
+ expect(updateTopicMetadataMock).toHaveBeenCalledWith(topicId, {
+ runningOperation: null,
+ });
+ expect(updateTopicMetadataMock.mock.invocationCallOrder[0]).toBeLessThan(
+ updateTopicMock.mock.invocationCallOrder[0],
+ );
+ expect(useChatStore.getState().topicDataMap[key].items[0]).toMatchObject({
+ metadata: { runningOperation: null },
+ status: 'active',
+ });
+ });
+
+ it('should patch group main topic scope when stale group rows include supervisor agent id', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const agentId = 'supervisor-agent';
+ const groupId = 'group-1';
+ const topicId = 'topic-1';
+ const groupKey = topicMapKey({ groupId });
+ const groupAgentKey = topicMapKey({ agentId, groupId });
+ const topic = {
+ agentId,
+ createdAt: Date.now() - 3 * 60 * 60 * 1000,
+ groupId,
+ id: topicId,
+ metadata: {
+ runningOperation: {
+ assistantMessageId: 'assistant-1',
+ operationId: 'server-op-1',
+ },
+ },
+ sessionId: agentId,
+ status: 'running',
+ title: 'Stale group topic',
+ updatedAt: Date.now() - 3 * 60 * 60 * 1000,
+ } as ChatTopic & { agentId: string; groupId: string };
+
+ vi.spyOn(topicService, 'queryTopics').mockResolvedValue([topic]);
+ vi.spyOn(topicService, 'updateTopic').mockResolvedValue([]);
+ vi.spyOn(topicService, 'updateTopicMetadata').mockResolvedValue([]);
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: agentId,
+ activeGroupId: groupId,
+ messageOperationMap: {},
+ operations: {},
+ operationsByContext: {},
+ operationsByMessage: {},
+ topicDataMap: {
+ [groupKey]: {
+ currentPage: 0,
+ hasMore: false,
+ items: [topic],
+ pageSize: 20,
+ total: 1,
+ },
+ },
+ });
+ });
+
+ let cleaned = 0;
+ await act(async () => {
+ cleaned = await result.current.cleanupStaleRunningTopics();
+ });
+
+ expect(cleaned).toBe(1);
+ expect(useChatStore.getState().topicDataMap[groupKey].items[0]).toMatchObject({
+ metadata: { runningOperation: null },
+ status: 'active',
+ });
+ expect(useChatStore.getState().topicDataMap[groupAgentKey]).toBeUndefined();
+ });
+
+ it('should not mark stale topics active when runningOperation metadata cleanup fails', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const agentId = 'agent-1';
+ const topicId = 'topic-1';
+ const key = topicMapKey({ agentId });
+ const runningOperation = {
+ assistantMessageId: 'assistant-1',
+ operationId: 'server-op-1',
+ };
+ const topic = {
+ agentId,
+ createdAt: Date.now() - 3 * 60 * 60 * 1000,
+ id: topicId,
+ metadata: { runningOperation },
+ sessionId: agentId,
+ status: 'running',
+ title: 'Stale running topic',
+ updatedAt: Date.now() - 3 * 60 * 60 * 1000,
+ } as ChatTopic & { agentId: string };
+
+ vi.spyOn(topicService, 'queryTopics').mockResolvedValue([topic]);
+ const updateTopicMock = vi.spyOn(topicService, 'updateTopic').mockResolvedValue([]);
+ const updateTopicMetadataMock = vi
+ .spyOn(topicService, 'updateTopicMetadata')
+ .mockRejectedValue(new Error('metadata persist failed'));
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: agentId,
+ messageOperationMap: {},
+ operations: {},
+ operationsByContext: {},
+ operationsByMessage: {},
+ topicDataMap: {
+ [key]: {
+ currentPage: 0,
+ hasMore: false,
+ items: [topic],
+ pageSize: 20,
+ total: 1,
+ },
+ },
+ });
+ });
+
+ let cleaned = 0;
+ await act(async () => {
+ cleaned = await result.current.cleanupStaleRunningTopics();
+ });
+
+ expect(cleaned).toBe(0);
+ expect(updateTopicMetadataMock).toHaveBeenCalledWith(topicId, { runningOperation: null });
+ expect(updateTopicMock).not.toHaveBeenCalled();
+ expect(useChatStore.getState().topicDataMap[key].items[0]).toMatchObject({
+ metadata: { runningOperation },
+ status: 'running',
+ });
+ });
+
+ it('should keep stale running topics when an alive operation exists', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const agentId = 'agent-1';
+ const topicId = 'topic-1';
+ const topic = {
+ agentId,
+ createdAt: Date.now() - 3 * 60 * 60 * 1000,
+ id: topicId,
+ sessionId: agentId,
+ status: 'running',
+ title: 'Still running topic',
+ updatedAt: Date.now() - 3 * 60 * 60 * 1000,
+ } as ChatTopic & { agentId: string };
+
+ vi.spyOn(topicService, 'queryTopics').mockResolvedValue([topic]);
+ vi.spyOn(topicService, 'updateTopic').mockResolvedValue([]);
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: agentId,
+ messageOperationMap: {},
+ operations: {},
+ operationsByContext: {},
+ operationsByMessage: {},
+ });
+
+ result.current.startOperation({
+ context: { agentId, topicId },
+ type: 'execHeterogeneousAgent',
+ });
+ });
+
+ let cleaned = 0;
+ await act(async () => {
+ cleaned = await result.current.cleanupStaleRunningTopics();
+ });
+
+ expect(cleaned).toBe(0);
+ expect(topicService.updateTopic).not.toHaveBeenCalledWith(topicId, { status: 'active' });
+ });
+ });
describe('updateTopicLoading', () => {
it('should call update topicLoadingId', async () => {
const { result } = renderHook(() => useChatStore());
diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.ts
index 655d34da6f7..8df7964758b 100644
--- a/src/store/chat/slices/topic/action.ts
+++ b/src/store/chat/slices/topic/action.ts
@@ -17,8 +17,9 @@ import { messageService } from '@/services/message';
import { topicService } from '@/services/topic';
import { type ChatStore } from '@/store/chat';
import { evictMessageCache } from '@/store/chat/utils/evictMessageCache';
-import { topicMapKey } from '@/store/chat/utils/topicMapKey';
+import { topicMapKey, type TopicMapScope } from '@/store/chat/utils/topicMapKey';
import { useGlobalStore } from '@/store/global';
+import { getHomeStoreState } from '@/store/home';
import { type StoreSetter } from '@/store/types';
import { useUserStore } from '@/store/user';
import { systemAgentSelectors, userGeneralSettingsSelectors } from '@/store/user/selectors';
@@ -39,12 +40,27 @@ import { topicSelectors } from './selectors';
const n = setNamespace('t');
+const STALE_RUNNING_TOPIC_TIMEOUT = 2 * 60 * 60 * 1000;
+const STALE_RUNNING_TOPIC_QUERY_PAGE_SIZE = 500;
+
type CronTopicsGroupWithJobInfo = {
cronJob: unknown;
cronJobId: string;
topics: ChatTopic[];
};
+type RunningTopicForWatchdog = Omit<ChatTopic, 'updatedAt'> & {
+ agentId?: string | null;
+ groupId?: string | null;
+ updatedAt: Date | number | string;
+};
+
+type TopicPatchScope = {
+ agentId?: string;
+ groupId?: string;
+ scope?: TopicMapScope;
+};
+
/**
* Options for switchTopic action
*/
@@ -81,6 +97,8 @@ export class ChatTopicActionImpl {
// clobber the newer topic (see ).
#switchTopicEpoch = 0;
+ #staleRunningTopicCleanupInFlight = false;
+
constructor(set: Setter, get: () => ChatStore, _api?: unknown) {
void _api;
this.#set = set;
@@ -396,14 +414,18 @@ export class ChatTopicActionImpl {
updateTopicStatus = async (params: {
agentId?: string;
groupId?: string;
+ scope?: TopicMapScope;
status: ChatTopicStatus;
topicId: string;
}): Promise<void> => {
- const { topicId, status, agentId, groupId } = params;
+ const { topicId, status, agentId, groupId, scope } = params;
const state = this.#get();
+ const scopedAgentId = scope ? agentId : (agentId ?? state.activeAgentId);
+ const scopedGroupId = scope ? groupId : (groupId ?? state.activeGroupId);
const key = topicMapKey({
- agentId: agentId ?? state.activeAgentId,
- groupId: groupId ?? state.activeGroupId,
+ agentId: scopedAgentId,
+ groupId: scopedGroupId,
+ scope,
});
const topic = state.topicDataMap[key]?.items?.find((t) => t.id === topicId);
@@ -421,6 +443,7 @@ export class ChatTopicActionImpl {
value: { status },
agentId,
groupId,
+ scope,
});
await topicService.updateTopic(topicId, { status }).catch((err) => {
@@ -430,6 +453,112 @@ export class ChatTopicActionImpl {
});
};
+ #getTopicUpdatedAt = (topic: RunningTopicForWatchdog): number | undefined => {
+ const timestamp =
+ typeof topic.updatedAt === 'number' ? topic.updatedAt : new Date(topic.updatedAt).getTime();
+
+ return Number.isFinite(timestamp) ? timestamp : undefined;
+ };
+
+ #hasAliveOperationForTopic = (topicId: string): boolean => {
+ const operations = Object.values(this.#get().operations);
+
+ return operations.some((operation) => {
+ if (operation.status !== 'running') return false;
+ if (operation.metadata.isAborting) return false;
+ if (operation.abortController.signal.aborted) return false;
+
+ return operation.context.topicId === topicId;
+ });
+ };
+
+ #getStaleRunningTopicPatchScope = (topic: RunningTopicForWatchdog): TopicPatchScope => {
+ const groupId = topic.groupId ?? undefined;
+
+ // Group main topic rows are persisted with the supervisor agentId, but the
+ // sidebar topic bucket is `group_${groupId}`. Patch that bucket explicitly
+ // instead of falling into `group_agent_${groupId}_${agentId}`.
+ if (groupId) return { groupId, scope: 'group' };
+
+ return { agentId: topic.agentId ?? undefined };
+ };
+
+ #clearStaleRunningOperationMetadata = async (
+ topic: RunningTopicForWatchdog,
+ patchScope: TopicPatchScope,
+ ): Promise<void> => {
+ if (!topic.metadata?.runningOperation) return;
+
+ const key = topicMapKey(patchScope);
+ const currentTopic = this.#get().topicDataMap[key]?.items.find((item) => item.id === topic.id);
+ const metadata = currentTopic?.metadata ?? topic.metadata;
+
+ await topicService.updateTopicMetadata(topic.id, { runningOperation: null });
+
+ this.#get().internal_dispatchTopic({
+ ...patchScope,
+ id: topic.id,
+ type: 'updateTopic',
+ value: { metadata: { ...metadata, runningOperation: null } },
+ });
+ };
+
+ cleanupStaleRunningTopics = async (): Promise<number> => {
+ if (this.#staleRunningTopicCleanupInFlight) return 0;
+
+ this.#staleRunningTopicCleanupInFlight = true;
+
+ try {
+ const runningTopics = (await topicService.queryTopics({
+ pageSize: STALE_RUNNING_TOPIC_QUERY_PAGE_SIZE,
+ statuses: ['running'],
+ })) as RunningTopicForWatchdog[];
+
+ const now = Date.now();
+ const staleTopics = runningTopics.filter((topic) => {
+ const updatedAt = this.#getTopicUpdatedAt(topic);
+ if (!updatedAt) return false;
+ if (now - updatedAt <= STALE_RUNNING_TOPIC_TIMEOUT) return false;
+
+ return !this.#hasAliveOperationForTopic(topic.id);
+ });
+
+ const cleanedResults = await Promise.all(
+ staleTopics.map(async (topic) => {
+ try {
+ const patchScope = this.#getStaleRunningTopicPatchScope(topic);
+
+ await this.#clearStaleRunningOperationMetadata(topic, patchScope);
+
+ await this.updateTopicStatus({
+ ...patchScope,
+ status: 'active',
+ topicId: topic.id,
+ });
+
+ return true;
+ } catch (err) {
+ console.error('[cleanupStaleRunningTopics] retire stale topic failed:', err);
+ return false;
+ }
+ }),
+ );
+
+ const cleanedCount = cleanedResults.filter(Boolean).length;
+
+ if (cleanedCount > 0) {
+ void getHomeStoreState().refreshAgentList?.();
+ }
+
+ return cleanedCount;
+ } catch (err) {
+ console.error('[cleanupStaleRunningTopics] failed:', err);
+ return 0;
+ } finally {
+ this.#staleRunningTopicCleanupInFlight = false;
+ }
+ };
+
autoRenameTopicTitle = async (id: string): Promise<void> => {
const { activeAgentId: agentId, summaryTopicTitle, internal_updateTopicLoading } = this.#get();
@@ -911,7 +1040,7 @@ export class ChatTopicActionImpl {
}
this.#set(
- { activeTopicId: !id ? (null as any) : id, activeThreadId: undefined },
+ { activeTopicId: id || (null as any), activeThreadId: undefined },
false,
n('toggleTopic'),
);
@@ -1179,9 +1308,12 @@ export class ChatTopicActionImpl {
*/
internal_dispatchTopic = (payload: ChatTopicDispatch, action?: any): void => {
const { activeAgentId, activeGroupId } = this.#get();
+ const scopedAgentId = payload.scope ? payload.agentId : (payload.agentId ?? activeAgentId);
+ const scopedGroupId = payload.scope ? payload.groupId : (payload.groupId ?? activeGroupId);
const key = topicMapKey({
- agentId: payload.agentId ?? activeAgentId,
- groupId: payload.groupId ?? activeGroupId,
+ agentId: scopedAgentId,
+ groupId: scopedGroupId,
+ scope: payload.scope,
});
const currentData = this.#get().topicDataMap[key];
const nextItems = topicReducer(currentData?.items, payload);
diff --git a/src/store/chat/slices/topic/reducer.test.ts b/src/store/chat/slices/topic/reducer.test.ts
index 962cb7d3c09..f00a7f6b89d 100644
--- a/src/store/chat/slices/topic/reducer.test.ts
+++ b/src/store/chat/slices/topic/reducer.test.ts
@@ -200,7 +200,7 @@ describe('topicReducer', () => {
},
};
- const newState = topicReducer(state, payload);
+ topicReducer(state, payload);
expect(state).toEqual([]);
});
diff --git a/src/store/chat/slices/topic/reducer.ts b/src/store/chat/slices/topic/reducer.ts
index 0093ab0e6ad..d8d9cc8d4f3 100644
--- a/src/store/chat/slices/topic/reducer.ts
+++ b/src/store/chat/slices/topic/reducer.ts
@@ -1,6 +1,7 @@
import isEqual from 'fast-deep-equal';
import { current, produce } from 'immer';
+import { type TopicMapScope } from '@/store/chat/utils/topicMapKey';
import { type ChatTopic, type CreateTopicParams } from '@/types/topic';
/**
@@ -13,6 +14,7 @@ import { type ChatTopic, type CreateTopicParams } from '@/types/topic';
interface ChatTopicScope {
agentId?: string;
groupId?: string;
+ scope?: TopicMapScope;
}
type AddChatTopicAction = ChatTopicScope & {
@@ -50,7 +52,7 @@ export const topicReducer = (state: ChatTopic[] = [], payload: ChatTopicDispatch
createdAt: Date.now(),
favorite: false,
id: payload.value.id ?? Date.now().toString(),
- sessionId: payload.value.sessionId ? payload.value.sessionId : undefined,
+ sessionId: payload.value.sessionId || undefined,
updatedAt: Date.now(),
});