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.

♻️ refactor(topic): drive the sidebar topic spinner from operations, drop topicLoadingIds (#17926)

Arvin Xu5d30748688a7
diff --git a/src/features/AgentMockDevtools/hooks/useAgentMockPlayer.test.ts b/src/features/AgentMockDevtools/hooks/useAgentMockPlayer.test.ts
index 6edbaeecdfa..62d7771b5c7 100644
--- a/src/features/AgentMockDevtools/hooks/useAgentMockPlayer.test.ts
+++ b/src/features/AgentMockDevtools/hooks/useAgentMockPlayer.test.ts
@@ -101,7 +101,6 @@ const createChatStoreMock = (overrides: Record<string, unknown> = {}) => ({
internal_dispatchMessage: vi.fn(),
internal_dispatchTopic: vi.fn(),
internal_toggleToolCallingStreaming: vi.fn(),
- internal_updateTopicLoading: vi.fn(),
operations: {},
operationsByMessage: {},
optimisticCreateTmpMessage: vi.fn(),
diff --git a/src/features/AgentMockDevtools/hooks/useAgentMockPlayer.ts b/src/features/AgentMockDevtools/hooks/useAgentMockPlayer.ts
index 4891e01b752..f25f8719375 100644
--- a/src/features/AgentMockDevtools/hooks/useAgentMockPlayer.ts
+++ b/src/features/AgentMockDevtools/hooks/useAgentMockPlayer.ts
@@ -85,7 +85,6 @@ const clearLocalTopicRunningOperation = (chatStore: ChatStore, topicId: string |
},
'agentMock/clearRunningOperation',
);
- chatStore.internal_updateTopicLoading(topicId, false);
};
const getContextKey = (args: StartArgs) =>
diff --git a/src/features/AgentSidebar/Topic/List/Item/index.test.tsx b/src/features/AgentSidebar/Topic/List/Item/index.test.tsx
index 3cf2a081eb2..438c033624a 100644
--- a/src/features/AgentSidebar/Topic/List/Item/index.test.tsx
+++ b/src/features/AgentSidebar/Topic/List/Item/index.test.tsx
@@ -115,12 +115,8 @@ vi.mock('@/store/agent', () => ({
) => selector({ activeAgentId: 'agt_test', agentMap: {} }),
}));
vi.mock('@/store/chat', () => ({
- useChatStore: (
- selector: (state: {
- prefetchMessages: typeof prefetchMessagesMock;
- topicLoadingIds: string[];
- }) => unknown,
- ) => selector({ prefetchMessages: prefetchMessagesMock, topicLoadingIds: [] }),
+ useChatStore: (selector: (state: { prefetchMessages: typeof prefetchMessagesMock }) => unknown) =>
+ selector({ prefetchMessages: prefetchMessagesMock }),
}));
vi.mock('@/store/chat/selectors', () => ({
operationSelectors: {
@@ -129,6 +125,7 @@ vi.mock('@/store/chat/selectors', () => ({
isAgentRuntimeRunningByContext: () => () => agentRuntimeRunningMock.value,
isAgentRuntimeVisiblyRunningByContext: () => () => false,
isTopicUnreadCompleted: () => () => topicUnreadCompletedMock.value,
+ isTopicVisiblyRunning: () => () => false,
},
}));
vi.mock('@/store/electron', () => ({
diff --git a/src/features/AgentSidebar/Topic/List/Item/index.tsx b/src/features/AgentSidebar/Topic/List/Item/index.tsx
index 5b6b19aaf57..058cbcee61a 100644
--- a/src/features/AgentSidebar/Topic/List/Item/index.tsx
+++ b/src/features/AgentSidebar/Topic/List/Item/index.tsx
@@ -205,7 +205,7 @@ const TopicItemRow = memo<TopicItemRowProps>(
return buildWorkspaceAwarePath(AGENT_CHAT_TOPIC_URL(activeAgentId, id), activeWorkspaceSlug);
}, [activeAgentId, activeWorkspaceSlug, id]);
- const isLoading = useChatStore((s) => (id ? s.topicLoadingIds.includes(id) : false));
+ const isLoading = useChatStore(id ? operationSelectors.isTopicVisiblyRunning(id) : () => false);
const isUnreadCompleted = useChatStore(
id ? operationSelectors.isTopicUnreadCompleted(id) : () => false,
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx
index d2cd9fd2782..0571049d95c 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx
@@ -133,8 +133,7 @@ vi.mock('@/store/agent/selectors', () => ({
}));
vi.mock('@/store/chat', () => {
- const useChatStore = (selector: (state: { topicLoadingIds: string[] }) => unknown) =>
- selector({ topicLoadingIds: [] });
+ const useChatStore = (selector: (state: object) => unknown) => selector({});
useChatStore.getState = () => ({ switchTopic: switchTopicMock });
return { useChatStore };
});
@@ -142,6 +141,7 @@ vi.mock('@/store/chat', () => {
vi.mock('@/store/chat/selectors', () => ({
operationSelectors: {
unreadCompletedCountForTopics: () => () => 0,
+ visiblyRunningTopicIds: () => new Set<string>(),
},
}));
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx
index 191be9e6cd5..1fa8b01e9c1 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx
@@ -1,6 +1,7 @@
import { AGENT_CHAT_URL } from '@lobechat/const';
import { AccordionItem, ActionIcon, Center, Flexbox, Icon, Text, Tooltip } from '@lobehub/ui';
import { createStaticStyles, cssVar, cx } from 'antd-style';
+import isEqual from 'fast-deep-equal';
import { FolderClosedIcon, FolderOpenIcon, type LucideIcon, PlusIcon } from 'lucide-react';
import { memo, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -216,10 +217,9 @@ const GroupItem = memo<GroupItemComponentProps>(
const isDeviceMode = effectiveTarget === 'device' && !!agencyConfig?.boundDeviceId;
const canAddTopic = (isDesktop || isDeviceMode) && !!workingDirectory;
- const loadingTopicIds = useChatStore((s) => s.topicLoadingIds);
- const statusCounts = useMemo(
- () => getProjectTopicStatusCounts(children, new Set(loadingTopicIds)),
- [children, loadingTopicIds],
+ const statusCounts = useChatStore(
+ (s) => getProjectTopicStatusCounts(children, operationSelectors.visiblyRunningTopicIds(s)),
+ isEqual,
);
const childTopicIds = useMemo(() => children.map((topic) => topic.id), [children]);
const unreadCount = useChatStore(
diff --git a/src/features/Conversation/store.test.ts b/src/features/Conversation/store.test.ts
index 3b13da638b5..2d3553e1e6c 100644
--- a/src/features/Conversation/store.test.ts
+++ b/src/features/Conversation/store.test.ts
@@ -42,7 +42,6 @@ vi.mock('@/store/chat', () => ({
sendMessage: vi.fn(),
switchTopic: vi.fn(),
summaryTopicTitle: vi.fn(),
- internal_updateTopicLoading: vi.fn(),
})),
setState: vi.fn(),
},
diff --git a/src/features/Conversation/store/slices/generation/action.test.ts b/src/features/Conversation/store/slices/generation/action.test.ts
index 42e4f56c388..46653639ab4 100644
--- a/src/features/Conversation/store/slices/generation/action.test.ts
+++ b/src/features/Conversation/store/slices/generation/action.test.ts
@@ -1293,7 +1293,6 @@ describe('Generation Actions', () => {
const setupHeteroChatStore = async (overrides: Record<string, any> = {}) => {
const mockRefreshMessages = vi.fn().mockResolvedValue(undefined);
- const mockInternalUpdateTopicLoading = vi.fn();
const mockAssociateMessageWithOperation = vi.fn();
const mockHeteroStartOperation = vi
.fn()
@@ -1315,7 +1314,6 @@ describe('Generation Actions', () => {
isGatewayModeEnabled: vi.fn(() => false),
switchMessageBranch: mockSwitchMessageBranch,
refreshMessages: mockRefreshMessages,
- internal_updateTopicLoading: mockInternalUpdateTopicLoading,
associateMessageWithOperation: mockAssociateMessageWithOperation,
executeClientAgent: mockExecuteClientAgent,
executeGatewayAgent: mockExecuteGatewayAgent,
@@ -1325,7 +1323,6 @@ describe('Generation Actions', () => {
return {
mockAssociateMessageWithOperation,
mockHeteroStartOperation,
- mockInternalUpdateTopicLoading,
mockRefreshMessages,
};
};
diff --git a/src/features/Conversation/store/slices/generation/action.ts b/src/features/Conversation/store/slices/generation/action.ts
index a2aa1e3cfe6..e7f5a627c89 100644
--- a/src/features/Conversation/store/slices/generation/action.ts
+++ b/src/features/Conversation/store/slices/generation/action.ts
@@ -213,8 +213,6 @@ const runHeterogeneousFromExistingMessage = async (
// the executor runs (the executor only dispatches updates, not creates).
await chatStore.refreshMessages();
- if (context.topicId) chatStore.internal_updateTopicLoading(context.topicId, true);
-
const { operationId: heteroOpId } = chatStore.startOperation({
context,
label: 'Heterogeneous Agent Execution',
@@ -224,23 +222,18 @@ const runHeterogeneousFromExistingMessage = async (
});
chatStore.associateMessageWithOperation(assistantMsg.id, heteroOpId);
- try {
- const { executeHeterogeneousAgent } =
- await import('@/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor');
- await executeHeterogeneousAgent(() => useChatStore.getState(), {
- assistantMessageId: assistantMsg.id,
- context,
- heterogeneousProvider,
- imageList: imageList?.length ? imageList : undefined,
- message: prompt,
- operationId: heteroOpId,
- resumeSessionId,
- workingDirectory,
- });
- } finally {
- if (context.topicId)
- useChatStore.getState().internal_updateTopicLoading(context.topicId, false);
- }
+ const { executeHeterogeneousAgent } =
+ await import('@/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor');
+ await executeHeterogeneousAgent(() => useChatStore.getState(), {
+ assistantMessageId: assistantMsg.id,
+ context,
+ heterogeneousProvider,
+ imageList: imageList?.length ? imageList : undefined,
+ message: prompt,
+ operationId: heteroOpId,
+ resumeSessionId,
+ workingDirectory,
+ });
return assistantMsg.id;
};
diff --git a/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.ts b/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.ts
index d5c7cfd0675..f75ee064eec 100644
--- a/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.ts
+++ b/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.ts
@@ -120,7 +120,6 @@ vi.mock('@/store/chat', () => ({
deleteMessage: (...args: any[]) => mockChatDeleteMessage(...(args as [])),
executeGatewayAgent: (...args: any[]) => mockExecuteGatewayAgent(...(args as [])),
failOperation: noop,
- internal_updateTopicLoading: noop,
isGatewayModeEnabled: () => false,
refreshMessages: vi.fn(async () => {}),
startOperation: vi.fn(() => ({ operationId: 'op-id' })),
diff --git a/src/features/Conversation/store/slices/generation/regenerateHeteroImages.test.ts b/src/features/Conversation/store/slices/generation/regenerateHeteroImages.test.ts
index 1e7c4595217..fe5f35d4018 100644
--- a/src/features/Conversation/store/slices/generation/regenerateHeteroImages.test.ts
+++ b/src/features/Conversation/store/slices/generation/regenerateHeteroImages.test.ts
@@ -84,7 +84,6 @@ vi.mock('@/store/chat', () => ({
associateMessageWithOperation: noop,
completeOperation: noop,
failOperation: noop,
- internal_updateTopicLoading: noop,
isGatewayModeEnabled: () => false,
refreshMessages: vi.fn(async () => {}),
startOperation: vi.fn(() => ({ operationId: 'hetero-op-id' })),
diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx
index cddfcc392e7..dddbb56b2aa 100644
--- a/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx
+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx
@@ -119,7 +119,7 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId, stat
const [editing, isLoading] = useChatStore((s) => [
id ? s.topicRenamingId === id : false,
- id ? s.topicLoadingIds.includes(id) : false,
+ id ? operationSelectors.isTopicVisiblyRunning(id)(s) : false,
]);
const isUnreadCompleted = useChatStore(
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
index 0f5de616a2a..4c0349a6fdf 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
@@ -9,6 +9,7 @@ import { chatService } from '@/services/chat';
import { messageService } from '@/services/message';
import * as agentGroupStore from '@/store/agentGroup';
import { setPendingTopicRepos } from '@/store/chat/pendingTopicRepos';
+import { operationSelectors } from '@/store/chat/slices/operation/selectors';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { topicMapKey } from '@/store/chat/utils/topicMapKey';
import { getSessionStoreState } from '@/store/session';
@@ -615,7 +616,12 @@ describe('ConversationLifecycle actions', () => {
}),
);
expect(optimisticTopic?.id).toMatch(/^tpc_/);
- expect(useChatStore.getState().topicLoadingIds).toContain(optimisticTopic!.id);
+ // The running sendMessage operation (context carries the minted topic
+ // id) drives the sidebar spinner while the server round-trip is in
+ // flight.
+ expect(
+ operationSelectors.isTopicVisiblyRunning(optimisticTopic!.id)(useChatStore.getState()),
+ ).toBe(true);
await act(async () => {
resolveServerSend({
@@ -645,15 +651,20 @@ describe('ConversationLifecycle actions', () => {
const finalTopics = useChatStore.getState().topicDataMap[topicKey]?.items ?? [];
expect(finalTopics).toEqual([expect.objectContaining({ id: newTopicId })]);
expect(finalTopics.some((topic) => topic.id === optimisticTopic?.id)).toBe(false);
- expect(useChatStore.getState().topicLoadingIds).not.toContain(optimisticTopic!.id);
- expect(useChatStore.getState().topicLoadingIds).toContain(newTopicId);
await act(async () => {
resolveExecute();
await sendPromise;
});
- expect(useChatStore.getState().topicLoadingIds).not.toContain(newTopicId);
+ // Send settled: no operation left running for either id, so the
+ // sidebar spinner is off.
+ expect(operationSelectors.isTopicVisiblyRunning(newTopicId)(useChatStore.getState())).toBe(
+ false,
+ );
+ expect(
+ operationSelectors.isTopicVisiblyRunning(optimisticTopic!.id)(useChatStore.getState()),
+ ).toBe(false);
});
it('should snapshot the agent model onto the newTopic (top-level) when the send creates the topic', async () => {
@@ -710,7 +721,7 @@ describe('ConversationLifecycle actions', () => {
);
});
- it('should release the migrated topicLoadingIds owner after a gateway send creates the topic', async () => {
+ it('should stop the sidebar spinner after a gateway send creates the topic', async () => {
const { result } = renderHook(() => useChatStore());
const agentId = TEST_IDS.SESSION_ID;
const topicKey = topicMapKey({ agentId });
@@ -721,8 +732,7 @@ describe('ConversationLifecycle actions', () => {
new Promise<any>((resolve) => {
resolveGateway = () => {
// Mimic executeGatewayAgent's contract: execAgentTask resolves
- // the optimistic topic via internal_replaceTopicId, migrating
- // its topicLoadingIds owner onto the real topic id, and the
+ // the optimistic topic via internal_replaceTopicId, and the
// parent sendMessage op is completed once phase-1 init is done
// (without this the leaked running op pollutes later tests —
// resetTestEnvironment does not clear `operations`).
@@ -774,7 +784,10 @@ describe('ConversationLifecycle actions', () => {
const optimisticTopicId = useChatStore.getState().topicDataMap[topicKey]?.items[0]?.id;
expect(optimisticTopicId).toMatch(/^tpc_/);
- expect(useChatStore.getState().topicLoadingIds).toContain(optimisticTopicId);
+ // The running sendMessage op keeps the spinner on during phase-1 init.
+ expect(
+ operationSelectors.isTopicVisiblyRunning(optimisticTopicId!)(useChatStore.getState()),
+ ).toBe(true);
await act(async () => {
resolveGateway();
@@ -786,13 +799,17 @@ describe('ConversationLifecycle actions', () => {
});
// From here the run spinner is owned by the persisted
- // `status === 'running'`; the migrated creation owner must be released
- // or the sidebar spinner sticks forever (the #16745 regression).
- expect(useChatStore.getState().topicLoadingIds).not.toContain(newTopicId);
- expect(useChatStore.getState().topicLoadingIds).not.toContain(optimisticTopicId);
+ // `status === 'running'` — no client-side operation may keep spinning
+ // for either id, or the sidebar spinner sticks after the run.
+ expect(operationSelectors.isTopicVisiblyRunning(newTopicId)(useChatStore.getState())).toBe(
+ false,
+ );
+ expect(
+ operationSelectors.isTopicVisiblyRunning(optimisticTopicId!)(useChatStore.getState()),
+ ).toBe(false);
});
- it('should hold the migrated topicLoadingIds owner through a hetero new-topic run and release it at the end', async () => {
+ it('should keep the sidebar spinner on through a hetero new-topic run and stop it at the end', async () => {
mockConstEnv.isDesktop = true;
setupMockSelectors({
agentConfig: {
@@ -847,10 +864,17 @@ describe('ConversationLifecycle actions', () => {
} as any);
let resolveExecutor!: () => void;
- executeHeterogeneousAgentMock.mockReturnValue(
- new Promise<void>((resolve) => {
- resolveExecutor = resolve;
- }),
+ executeHeterogeneousAgentMock.mockImplementation(
+ (_getStore: unknown, opts: { operationId: string }) =>
+ new Promise<void>((resolve) => {
+ resolveExecutor = () => {
+ // The real executor settles its execHeterogeneousAgent op at
+ // the terminal; without this the leaked running op would keep
+ // the spinner on (and pollute later tests).
+ useChatStore.getState().completeOperation(opts.operationId);
+ resolve();
+ };
+ }),
);
let sendPromise!: ReturnType<typeof result.current.sendMessage>;
@@ -864,10 +888,12 @@ describe('ConversationLifecycle actions', () => {
await waitFor(() => expect(executeHeterogeneousAgentMock).toHaveBeenCalled());
// The executor only writes the persisted `status === 'running'` (the
- // run spinner's other driver) after startSession resolves — the
- // migrated creation owner must stay held while the executor starts up,
- // or the sidebar spinner blanks during a slow CLI startup.
- expect(useChatStore.getState().topicLoadingIds).toContain(newTopicId);
+ // run spinner's other driver) after startSession resolves — the running
+ // execHeterogeneousAgent operation must keep the spinner on while the
+ // executor starts up, or it blanks during a slow CLI startup.
+ expect(operationSelectors.isTopicVisiblyRunning(newTopicId)(useChatStore.getState())).toBe(
+ true,
+ );
await act(async () => {
resolveExecutor();
@@ -878,7 +904,9 @@ describe('ConversationLifecycle actions', () => {
await Promise.resolve();
});
- expect(useChatStore.getState().topicLoadingIds).not.toContain(newTopicId);
+ expect(operationSelectors.isTopicVisiblyRunning(newTopicId)(useChatStore.getState())).toBe(
+ false,
+ );
});
it('should keep a gateway optimistic topic in its pending repo project group', async () => {
@@ -1007,8 +1035,7 @@ describe('ConversationLifecycle actions', () => {
});
expect(useChatStore.getState().topicDataMap[topicKey]?.items ?? []).toEqual([]);
- expect(useChatStore.getState().topicLoadingIds).toEqual([]);
- expect(useChatStore.getState().topicLoadingIdCounts).toEqual({});
+ expect(operationSelectors.visiblyRunningTopicIds(useChatStore.getState()).size).toBe(0);
});
it('should show a group optimistic topic in the group topic bucket', async () => {
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 7ecc82bd77c..ad23bd39846 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
@@ -515,7 +515,6 @@ describe('GatewayActionImpl', () => {
const connectToGateway = vi.fn();
const internalDispatchTopic = vi.fn();
const internalReplaceTopicId = vi.fn();
- const internalUpdateTopicLoading = vi.fn();
const onOperationCancel = vi.fn();
const replaceMessages = vi.fn();
const refreshTopic = vi.fn().mockResolvedValue(undefined);
@@ -536,7 +535,6 @@ describe('GatewayActionImpl', () => {
connectToGateway,
internal_dispatchTopic: internalDispatchTopic,
internal_replaceTopicId: internalReplaceTopicId,
- internal_updateTopicLoading: internalUpdateTopicLoading,
moveQueuedMessages,
onOperationCancel,
replaceMessages,
@@ -565,7 +563,6 @@ describe('GatewayActionImpl', () => {
get,
internalDispatchTopic,
internalReplaceTopicId,
- internalUpdateTopicLoading,
mockClient,
moveQueuedMessages,
onOperationCancel,
@@ -989,7 +986,6 @@ describe('GatewayActionImpl', () => {
completeOperation,
connectToGateway,
getOperationAbortSignal: vi.fn(() => controller.signal),
- internal_updateTopicLoading: vi.fn(),
onOperationCancel,
replaceMessages: vi.fn(),
startOperation,
@@ -1065,7 +1061,6 @@ describe('GatewayActionImpl', () => {
associateMessageWithOperation: vi.fn(),
connectToGateway: vi.fn(),
internal_dispatchTopic: vi.fn(),
- internal_updateTopicLoading: vi.fn(),
moveQueuedMessages: vi.fn(),
onOperationCancel,
replaceMessages: vi.fn(),
@@ -1493,7 +1488,6 @@ describe('GatewayActionImpl', () => {
...state,
associateMessageWithOperation: vi.fn(),
connectToGateway: vi.fn(),
- internal_updateTopicLoading: vi.fn(),
onOperationCancel: vi.fn(),
startOperation,
})) as any;
@@ -1586,7 +1580,6 @@ describe('GatewayActionImpl', () => {
connectToGateway: (params: any) => {
captured.onSessionComplete = params.onSessionComplete;
},
- internal_updateTopicLoading: vi.fn(),
onOperationCancel: vi.fn(),
startOperation,
updateTopicStatus,
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts
index 8764b9a45e7..9f1f48c5e32 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts
@@ -53,7 +53,6 @@ function createMockStore() {
internal_dispatchMessage: vi.fn(),
internal_executeClientTool: vi.fn().mockResolvedValue(undefined),
internal_toggleToolCallingStreaming: vi.fn(),
- internal_updateTopicLoading: vi.fn(),
markTopicUnread: vi.fn(),
messagesMap: {} as Record<string, any>,
operations: {
@@ -584,7 +583,6 @@ describe('createGatewayEventHandler', () => {
visibleLoadingDone: true,
});
expect(store.completeOperation).not.toHaveBeenCalledWith('op-1');
- expect(store.internal_updateTopicLoading).not.toHaveBeenCalledWith('topic-1', false);
});
it('keeps visible loading after stream_end when tool calls need another step', async () => {
@@ -608,7 +606,6 @@ describe('createGatewayEventHandler', () => {
visibleLoadingDone: true,
});
expect(store.completeOperation).not.toHaveBeenCalledWith('op-1');
- expect(store.internal_updateTopicLoading).not.toHaveBeenCalledWith('topic-1', false);
});
it('applies finalContent before ending a reasoning-only stream', async () => {
@@ -670,11 +667,6 @@ describe('createGatewayEventHandler', () => {
visibleLoadingDone: true,
});
expect(store.completeOperation).not.toHaveBeenCalledWith('op-1');
- // Sidebar "running" spinner is driven off `topic.status === 'running'`
- // (persisted, reset at the terminal) for gateway/hetero runs — not the
- // client-only `topicLoadingIds` overlay — so visible_output_end no longer
- // clears it early.
- expect(store.internal_updateTopicLoading).not.toHaveBeenCalled();
});
});
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/helpers.ts b/src/store/chat/slices/agentRun/actions/__tests__/helpers.ts
index 622814a2ffb..23af545ed98 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/helpers.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/helpers.ts
@@ -133,8 +133,6 @@ export const resetTestEnvironment = () => {
activeTopicId: TEST_IDS.TOPIC_ID,
messagesMap: {},
toolCallingStreamIds: {},
- topicLoadingIdCounts: {},
- topicLoadingIds: [],
},
false,
);
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
index 800e53fcc31..fc3b135f7ae 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
@@ -718,7 +718,6 @@ export class ConversationLifecycleActionImpl {
},
'sendMessage/optimisticCreateTopic',
);
- this.#get().internal_updateTopicLoading(mintedTopicId, true);
await this.#get().switchTopic(mintedTopicId, { skipRefreshMessage: true });
}
@@ -834,7 +833,6 @@ export class ConversationLifecycleActionImpl {
}
: undefined;
let optimisticTopicActive = false;
- let optimisticTopicResolved = false;
const addResolvedTopicPlaceholder = (
topicId: string,
@@ -898,13 +896,11 @@ export class ConversationLifecycleActionImpl {
},
});
optimisticTopicActive = false;
- optimisticTopicResolved = true;
};
const rollbackOptimisticTopic = (action: string) => {
if (!optimisticTopic || !optimisticTopicActive) return;
- this.#get().internal_updateTopicLoading(optimisticTopic.id, false);
if (this.#get().activeTopicId === optimisticTopic.id) {
void this.#get().switchTopic(null, { skipRefreshMessage: true });
}
@@ -1079,12 +1075,6 @@ export class ConversationLifecycleActionImpl {
clearNewKey: true,
skipRefreshMessage: true,
});
- // resolveOptimisticTopic migrated the optimistic topic's loading owner
- // onto the real id; it is released in the executor `finally` below —
- // NOT here — because the persisted `status === 'running'` (the run
- // spinner's other driver) is only written after startSession resolves,
- // so releasing before the executor takes over would blank the sidebar
- // spinner during a slow CLI startup.
}
// No temp-message cleanup: the optimistic rows were created under the very
@@ -1119,10 +1109,8 @@ export class ConversationLifecycleActionImpl {
// Sidebar "running" spinner for hetero runs is driven off the persisted
// `topic.status === 'running'` (written by the executor's writeTopicStatus,
- // and bucketed by resolveStatusBucket) — no separate client-only
- // `topicLoadingIds` overlay, which used to desync: it cleared on the
- // linear sendPrompt path (below) while `status` stayed 'running' when the
- // executor's onComplete stalled, leaving the topic spinning after finish.
+ // and bucketed by resolveStatusBucket) plus the running
+ // execHeterogeneousAgent operation below (operations-driven overlay).
// Start heterogeneous agent execution
const { operationId: heteroOpId } = this.#get().startOperation({
@@ -1189,16 +1177,6 @@ export class ConversationLifecycleActionImpl {
message: e instanceof Error ? e.message : 'Unknown error',
type: 'HeterogeneousAgentError',
});
- } finally {
- // Release the creation owner migrated by resolveOptimisticTopic (run
- // end no longer clears topicLoadingIds since #16745, so without this
- // the sidebar spinner sticks forever). Held until the run settles so
- // the spinner stays continuous through the pre-`running` startup gap;
- // it can't mask `waitingForHuman` — the sidebar item renders that
- // state with higher priority than the running icon.
- if (optimisticTopic && optimisticTopicResolved && heteroData.topicId) {
- this.#get().internal_updateTopicLoading(heteroData.topicId, false);
- }
}
return {
@@ -1271,16 +1249,10 @@ export class ConversationLifecycleActionImpl {
// the store and titles it. Fire-and-forget.
if (result.topicId) {
// executeGatewayAgent resolved the optimistic topic row via
- // internal_replaceTopicId, which migrates its topicLoadingIds owner
- // onto the real topic id. From here the run spinner is owned by the
- // persisted `status === 'running'` (#16745 removed the transports'
- // run-end topicLoadingIds clears), so release the migrated creation
- // owner now — with no release left downstream, the sidebar spinner
- // would stick forever after the run completes.
- // No `optimisticTopicResolved = true` here: the gateway branch
- // returns before the client-mode code that reads it.
+ // internal_replaceTopicId; nothing to release here — the sidebar
+ // spinner is operations-driven plus the persisted
+ // `status === 'running'`.
if (optimisticTopic && optimisticTopicActive) {
- this.#get().internal_updateTopicLoading(result.topicId, false);
optimisticTopicActive = false;
}
void sendRunLifecycle
@@ -1577,10 +1549,6 @@ export class ConversationLifecycleActionImpl {
rollbackOptimisticTopic('sendMessage/rollbackUnresolvedOptimisticTopic');
- if (data.topicId && !optimisticTopicResolved) {
- this.#get().internal_updateTopicLoading(data.topicId, true);
- }
-
// Topic title auto-generation, now via the shared `afterUserMessagePersisted`
// hook. The client passes its freshly-created `data.messages`
// (not yet in the store under the real topicId); gateway/hetero call the same
@@ -1725,10 +1693,6 @@ export class ConversationLifecycleActionImpl {
}
} catch (e) {
console.error(e);
- } finally {
- if (data.topicId) {
- this.#get().internal_updateTopicLoading(data.topicId, false);
- }
}
}
diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts
index c6a4de32482..8565a375399 100644
--- a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts
+++ b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts
@@ -49,7 +49,6 @@ const makeStore = (afterCompletionCallbacks?: Array<() => void>) => {
drainQueuedMessages: vi.fn(() => []),
failOperation: vi.fn(),
internal_updateTopic: vi.fn(),
- internal_updateTopicLoading: vi.fn(),
markTopicUnread: vi.fn(),
messagesMap: {},
operations: {
@@ -405,7 +404,6 @@ describe('buildRunLifecycle.afterUserMessagePersisted — topic title (all runti
expect(store.internal_updateTopic).toHaveBeenCalledWith('t1', {
title: '阅读下面的材料,根据要求写作。',
});
- expect(store.internal_updateTopicLoading).not.toHaveBeenCalledWith('t1', false);
expect(store.summaryTopicTitle).not.toHaveBeenCalled();
} finally {
if (previous === undefined) {
diff --git a/src/store/chat/slices/operation/__tests__/selectors.test.ts b/src/store/chat/slices/operation/__tests__/selectors.test.ts
index 18222325fd8..8535edd197b 100644
--- a/src/store/chat/slices/operation/__tests__/selectors.test.ts
+++ b/src/store/chat/slices/operation/__tests__/selectors.test.ts
@@ -679,6 +679,62 @@ describe('Operation Selectors', () => {
});
});
+ describe('topic running selectors', () => {
+ it('should report a topic running while a send/run op with its id is visibly running', () => {
+ const { result } = renderHook(() => useChatStore());
+ let sendOpId = '';
+
+ act(() => {
+ sendOpId = result.current.startOperation({
+ type: 'sendMessage',
+ context: { agentId: 'agent1', topicId: 'topic1' },
+ }).operationId;
+ });
+
+ expect(operationSelectors.isTopicVisiblyRunning('topic1')(result.current)).toBe(true);
+ expect(operationSelectors.isTopicVisiblyRunning('other')(result.current)).toBe(false);
+ expect(operationSelectors.visiblyRunningTopicIds(result.current)).toEqual(
+ new Set(['topic1']),
+ );
+
+ act(() => {
+ result.current.completeOperation(sendOpId);
+ });
+
+ expect(operationSelectors.isTopicVisiblyRunning('topic1')(result.current)).toBe(false);
+ expect(operationSelectors.visiblyRunningTopicIds(result.current).size).toBe(0);
+ });
+
+ it('should not report a topic running during the masked terminal tail', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ act(() => {
+ // Visible output done, run still doing terminal bookkeeping — the
+ // sidebar shows the unread dot in this window, not the spinner.
+ result.current.startOperation({
+ type: 'execAgentRuntime',
+ context: { agentId: 'agent1', topicId: 'topic1' },
+ metadata: { visibleLoadingDone: true },
+ });
+ });
+
+ expect(operationSelectors.isTopicVisiblyRunning('topic1')(result.current)).toBe(false);
+ });
+
+ it('should ignore ops whose type is not part of the send/run pipeline', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ act(() => {
+ result.current.startOperation({
+ type: 'callLLM',
+ context: { agentId: 'agent1', topicId: 'topic1' },
+ });
+ });
+
+ expect(operationSelectors.isTopicVisiblyRunning('topic1')(result.current)).toBe(false);
+ });
+ });
+
describe('visible loading selectors', () => {
it('should hide a no-tool terminal tail without unblocking the operation', () => {
const { result } = renderHook(() => useChatStore());
diff --git a/src/store/chat/slices/operation/selectors.ts b/src/store/chat/slices/operation/selectors.ts
index daa5266c95e..1680b0b8001 100644
--- a/src/store/chat/slices/operation/selectors.ts
+++ b/src/store/chat/slices/operation/selectors.ts
@@ -434,6 +434,49 @@ const isAgentVisiblyRunning =
return false;
};
+/**
+ * Whether a turn is visibly in progress for a topic on THIS client — the whole
+ * send → run pipeline (see INPUT_LOADING_OPERATION_TYPES), matched by the
+ * operation context's topicId regardless of agent/group/thread.
+ *
+ * Drives the sidebar topic spinner. Persisted `topic.status === 'running'`
+ * covers runs owned by other clients / the server; this covers what status
+ * cannot: client-mode runs (which never persist a status) and the startup
+ * window of gateway/hetero runs before the server writes `running`.
+ */
+const isTopicVisiblyRunning =
+ (topicId: string) =>
+ (s: ChatStoreState): boolean => {
+ for (const type of INPUT_LOADING_OPERATION_TYPES) {
+ const operationIds = s.operationsByType[type] || [];
+ const hasRunning = operationIds.some((id) => {
+ const op = s.operations[id];
+ return op && isVisiblyRunningOperation(op) && op.context.topicId === topicId;
+ });
+ if (hasRunning) return true;
+ }
+ return false;
+ };
+
+/**
+ * Topic ids with a visibly-running turn on this client. Set form of
+ * `isTopicVisiblyRunning` for list-level consumers (byStatus grouping, project
+ * group badges). Builds a new Set per call — subscribe with an equality fn or
+ * use it inside a selector that already recomputes per store change.
+ */
+const visiblyRunningTopicIds = (s: ChatStoreState): Set<string> => {
+ const ids = new Set<string>();
+ for (const type of INPUT_LOADING_OPERATION_TYPES) {
+ for (const id of s.operationsByType[type] || []) {
+ const op = s.operations[id];
+ if (op && isVisiblyRunningOperation(op) && op.context.topicId) {
+ ids.add(op.context.topicId);
+ }
+ }
+ }
+ return ids;
+};
+
/**
* Check if agent runtime is running (including both main window and thread)
* Checks all AI runtime operation types (see AI_RUNTIME_OPERATION_TYPES)
@@ -890,7 +933,9 @@ export const operationSelectors = {
isRegenerating,
isSendingMessage,
isTopicUnreadCompleted,
+ isTopicVisiblyRunning,
unreadCompletedCountForTopics,
+ visiblyRunningTopicIds,
// Message Queue
getQueuedMessages,
diff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.ts
index a87a9eaab1f..fd71c359fda 100644
--- a/src/store/chat/slices/topic/action.test.ts
+++ b/src/store/chat/slices/topic/action.test.ts
@@ -81,8 +81,6 @@ beforeEach(() => {
agentTopicsViewMap: {},
searchTopics: [],
topicDataMap: {},
- topicLoadingIdCounts: {},
- topicLoadingIds: [],
// ... initial state
},
false,
@@ -205,7 +203,7 @@ describe('topic action', () => {
expect(topicId).toEqual('new-topic-id');
});
- it('should release the fire-and-forget summary loading owner when title summary finishes', async () => {
+ it('should fire the title summary without blocking saveToTopic', async () => {
const { result } = renderHook(() => useChatStore());
const messages = [{ id: 'message1' }, { id: 'message2' }] as UIChatMessage[];
let resolveSummary!: () => void;
@@ -219,30 +217,25 @@ describe('topic action', () => {
messagesMap: {
[messageMapKey({ agentId: 'session-id' })]: messages,
},
- topicLoadingIdCounts: {},
- topicLoadingIds: [],
});
});
vi.spyOn(result.current, 'internal_createTopic').mockResolvedValue('new-topic-id');
- vi.spyOn(result.current, 'summaryTopicTitle').mockReturnValue(summaryPromise);
+ const summarySpy = vi
+ .spyOn(result.current, 'summaryTopicTitle')
+ .mockReturnValue(summaryPromise);
await act(async () => {
+ // Resolves before the summary settles — the summary is fire-and-forget.
await result.current.saveToTopic();
});
- expect(useChatStore.getState().topicLoadingIds).toEqual(['new-topic-id']);
- expect(useChatStore.getState().topicLoadingIdCounts).toEqual({ 'new-topic-id': 1 });
+ expect(summarySpy).toHaveBeenCalledWith('new-topic-id', messages);
await act(async () => {
resolveSummary();
await summaryPromise;
});
-
- await waitFor(() => {
- expect(useChatStore.getState().topicLoadingIds).toEqual([]);
- expect(useChatStore.getState().topicLoadingIdCounts).toEqual({});
- });
});
});
describe('refreshTopic', () => {
@@ -1645,7 +1638,7 @@ describe('topic action', () => {
});
});
describe('internal_updateTopic', () => {
- it('should release the loading owner when updating a topic fails', async () => {
+ it('should propagate the error when updating a topic fails', async () => {
const { result } = renderHook(() => useChatStore());
const agentId = 'agent-1';
const topicId = 'topic-1';
@@ -1673,8 +1666,6 @@ describe('topic action', () => {
total: 1,
},
},
- topicLoadingIdCounts: {},
- topicLoadingIds: [],
});
});
@@ -1685,9 +1676,6 @@ describe('topic action', () => {
result.current.internal_updateTopic(topicId, { title: 'New' }),
).rejects.toThrow('rename failed');
});
-
- expect(useChatStore.getState().topicLoadingIds).not.toContain(topicId);
- expect(useChatStore.getState().topicLoadingIdCounts[topicId]).toBeUndefined();
});
});
describe('cleanupStaleRunningTopics', () => {
@@ -2089,8 +2077,6 @@ describe('topic action', () => {
total: 1,
},
},
- topicLoadingIdCounts: {},
- topicLoadingIds: [],
});
};
@@ -2124,7 +2110,6 @@ describe('topic action', () => {
repoType: 'github',
},
});
- expect(useChatStore.getState().topicLoadingIds).toEqual([]);
});
it('updates empty PR metadata when no existing PR number is anchored', async () => {
@@ -2197,52 +2182,6 @@ describe('topic action', () => {
).toEqual({ pullRequest: stalePR, pullRequestStatus: 'ok' });
});
});
- describe('updateTopicLoading', () => {
- it('should call update topicLoadingId', async () => {
- const { result } = renderHook(() => useChatStore());
- act(() => {
- useChatStore.setState({ topicLoadingIds: [] });
- });
-
- expect(result.current.topicLoadingIds).toHaveLength(0);
-
- // Call the action with the topicId and newTitle
- act(() => {
- result.current.internal_updateTopicLoading('loading-id', true);
- });
-
- expect(result.current.topicLoadingIds).toEqual(['loading-id']);
- });
-
- it('should keep a topic loading until all loading owners finish', () => {
- const { result } = renderHook(() => useChatStore());
- act(() => {
- useChatStore.setState({ topicLoadingIdCounts: {}, topicLoadingIds: [] });
- });
-
- act(() => {
- result.current.internal_updateTopicLoading('topic-1', true);
- result.current.internal_updateTopicLoading('topic-1', true);
- });
-
- expect(result.current.topicLoadingIds).toEqual(['topic-1']);
- expect(result.current.topicLoadingIdCounts).toEqual({ 'topic-1': 2 });
-
- act(() => {
- result.current.internal_updateTopicLoading('topic-1', false);
- });
-
- expect(result.current.topicLoadingIds).toEqual(['topic-1']);
- expect(result.current.topicLoadingIdCounts).toEqual({ 'topic-1': 1 });
-
- act(() => {
- result.current.internal_updateTopicLoading('topic-1', false);
- });
-
- expect(result.current.topicLoadingIds).toEqual([]);
- expect(result.current.topicLoadingIdCounts).toEqual({});
- });
- });
describe('optimistic topic preservation across refetches', () => {
const agentId = 'agent-1';
const key = topicMapKey({ agentId });
@@ -2339,7 +2278,7 @@ describe('topic action', () => {
});
describe('replaceTopicId', () => {
- it('should migrate a loading optimistic topic to the server topic id', () => {
+ it('should swap the optimistic topic row to the server topic id', () => {
const { result } = renderHook(() => useChatStore());
const agentId = 'agent-1';
const key = topicMapKey({ agentId });
@@ -2366,8 +2305,6 @@ describe('topic action', () => {
total: 1,
},
},
- topicLoadingIdCounts: { tmp_topic_1: 2 },
- topicLoadingIds: ['tmp_topic_1'],
});
});
@@ -2387,65 +2324,6 @@ describe('topic action', () => {
title: '666',
}),
]);
- expect(result.current.topicLoadingIds).toEqual(['topic-1']);
- expect(result.current.topicLoadingIdCounts).toEqual({ 'topic-1': 2 });
- });
-
- it('should not double the loading count when resolving a client-minted id to itself', () => {
- const { result } = renderHook(() => useChatStore());
- const agentId = 'agent-1';
- const key = topicMapKey({ agentId });
- const mintedId = 'tpc_minted0000000001';
- const optimisticTopic: ChatTopic = {
- createdAt: Date.now(),
- favorite: false,
- id: mintedId,
- sessionId: agentId,
- title: '666',
- updatedAt: Date.now(),
- };
-
- act(() => {
- useChatStore.setState({
- activeAgentId: agentId,
- topicDataMap: {
- [key]: {
- currentPage: 0,
- hasMore: false,
- isExpandingPageSize: false,
- isLoadingMore: false,
- items: [optimisticTopic],
- pageSize: 20,
- total: 1,
- },
- },
- topicLoadingIdCounts: {},
- topicLoadingIds: [],
- });
- });
-
- // Send flow: one loading owner opened at optimistic creation…
- act(() => {
- result.current.internal_updateTopicLoading(mintedId, true);
- });
-
- // …then the server confirms the SAME id (#17889 client-minted ids).
- act(() => {
- result.current.internal_replaceTopicId({
- agentId,
- nextId: mintedId,
- previousId: mintedId,
- value: { sessionId: agentId },
- });
- });
-
- // …and the single run-end release must fully clear the spinner.
- act(() => {
- result.current.internal_updateTopicLoading(mintedId, false);
- });
-
- expect(result.current.topicLoadingIds).toEqual([]);
- expect(result.current.topicLoadingIdCounts).toEqual({});
});
});
describe('summaryTopicTitle', () => {
diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.ts
index 4e20ccba345..04031d960d7 100644
--- a/src/store/chat/slices/topic/action.ts
+++ b/src/store/chat/slices/topic/action.ts
@@ -226,17 +226,11 @@ export class ChatTopicActionImpl {
sessionId: targetSessionId,
});
- this.#get().internal_updateTopicLoading(topicId, true);
- // 2. auto summary topic Title
- // We don't need to await the summary, but this owner keeps the new topic
- // spinning immediately until the fire-and-forget title summary settles.
- void summaryTopicTitle(topicId, messages)
- .catch((error) => {
- console.error('[saveToTopic] Failed to summarize topic title:', error);
- })
- .finally(() => {
- this.#get().internal_updateTopicLoading(topicId, false);
- });
+ // 2. auto summary topic Title — fire-and-forget; the title streams into the
+ // row as it generates, no separate loading affordance needed.
+ void summaryTopicTitle(topicId, messages).catch((error) => {
+ console.error('[saveToTopic] Failed to summarize topic title:', error);
+ });
return topicId;
};
@@ -289,7 +283,7 @@ export class ChatTopicActionImpl {
};
summaryTopicTitle = async (topicId: string, messages: UIChatMessage[]): Promise<void> => {
- const { internal_updateTopicTitleInSummary, internal_updateTopicLoading } = this.#get();
+ const { internal_updateTopicTitleInSummary } = this.#get();
const topic = topicSelectors.getTopicById(topicId)(this.#get());
if (!topic) return;
@@ -312,9 +306,6 @@ export class ChatTopicActionImpl {
onFinish: async (text) => {
await this.#get().internal_updateTopic(topicId, { title: text });
},
- onLoadingChange: (loading) => {
- internal_updateTopicLoading(topicId, loading);
- },
onMessageHandle: (chunk) => {
switch (chunk.type) {
case 'text': {
@@ -397,10 +388,8 @@ export class ChatTopicActionImpl {
value: { metadata: mergedMetadata },
});
- this.#get().internal_updateTopicLoading(id, true);
await topicService.updateTopicMetadata(id, metadata);
await this.#get().refreshTopic();
- this.#get().internal_updateTopicLoading(id, false);
};
updateTopicTitle = async (id: string, title: string): Promise<void> => {
@@ -779,13 +768,11 @@ export class ChatTopicActionImpl {
};
autoRenameTopicTitle = async (id: string): Promise<void> => {
- const { activeAgentId: agentId, summaryTopicTitle, internal_updateTopicLoading } = this.#get();
+ const { activeAgentId: agentId, summaryTopicTitle } = this.#get();
- internal_updateTopicLoading(id, true);
const messages = await messageService.getMessages({ agentId, topicId: id });
await summaryTopicTitle(id, messages);
- internal_updateTopicLoading(id, false);
};
useFetchTopics = (
@@ -1406,44 +1393,6 @@ export class ChatTopicActionImpl {
);
};
- internal_updateTopicLoading = (id: string, loading: boolean): void => {
- this.#set(
- (state) => {
- const currentCount =
- state.topicLoadingIdCounts[id] ?? (state.topicLoadingIds.includes(id) ? 1 : 0);
- const nextCounts = { ...state.topicLoadingIdCounts };
-
- if (loading) {
- nextCounts[id] = currentCount + 1;
- const nextIds = state.topicLoadingIds.includes(id)
- ? state.topicLoadingIds
- : [...state.topicLoadingIds, id];
-
- return {
- topicLoadingIdCounts: nextCounts,
- topicLoadingIds: nextIds,
- };
- }
-
- if (currentCount > 1) {
- nextCounts[id] = currentCount - 1;
-
- return { topicLoadingIdCounts: nextCounts, topicLoadingIds: state.topicLoadingIds };
- }
-
- delete nextCounts[id];
- const nextIds = state.topicLoadingIds.filter((i) => i !== id);
-
- return {
- topicLoadingIdCounts: nextCounts,
- topicLoadingIds: nextIds,
- };
- },
- false,
- n('updateTopicLoading'),
- );
- };
-
internal_replaceTopicId = (params: {
agentId?: string;
groupId?: string;
@@ -1453,9 +1402,9 @@ export class ChatTopicActionImpl {
}): void => {
const { agentId, groupId, nextId, previousId, value } = params;
- // The first-message optimistic topic starts as `tmp_topic_*`. Once the
- // server returns the real id, keep the same row alive so loading state and
- // title-summary updates continue targeting the visible topic.
+ // The first-message optimistic topic starts as a client-only row. Once the
+ // server returns the real id, keep the same row alive so title-summary
+ // updates continue targeting the visible topic.
this.#get().internal_dispatchTopic(
{
agentId,
@@ -1468,47 +1417,22 @@ export class ChatTopicActionImpl {
n('replaceTopicId'),
);
- // Client-minted ids (#17889) resolve with previousId === nextId — there is
- // no loading owner to migrate, and running the merge below would read the
- // same counter twice and double it, leaving the sidebar spinner stuck after
- // the single run-end release.
if (previousId === nextId) return;
this.#set(
- (state) => {
- const previousCount = state.topicLoadingIdCounts[previousId] ?? 0;
- const nextCount = state.topicLoadingIdCounts[nextId] ?? 0;
- const topicLoadingIdCounts = { ...state.topicLoadingIdCounts };
- delete topicLoadingIdCounts[previousId];
- if (previousCount > 0 || nextCount > 0) {
- topicLoadingIdCounts[nextId] = previousCount + nextCount;
- }
- const topicLoadingIds = Array.from(
- new Set(state.topicLoadingIds.map((id) => (id === previousId ? nextId : id))),
- );
-
- return {
- activeTopicId: state.activeTopicId === previousId ? nextId : state.activeTopicId,
- topicLoadingIdCounts,
- topicLoadingIds,
- };
- },
+ (state) => ({
+ activeTopicId: state.activeTopicId === previousId ? nextId : state.activeTopicId,
+ }),
false,
- n('replaceTopicId/loading'),
+ n('replaceTopicId/active'),
);
};
internal_updateTopic = async (id: string, data: Partial<ChatTopic>): Promise<void> => {
this.#get().internal_dispatchTopic({ type: 'updateTopic', id, value: data });
- this.#get().internal_updateTopicLoading(id, true);
- try {
- await topicService.updateTopic(id, data);
- await this.#get().refreshTopic();
- } finally {
- // Rename "Topic" -> "New" can fail after opening a loading owner; always release it.
- this.#get().internal_updateTopicLoading(id, false);
- }
+ await topicService.updateTopic(id, data);
+ await this.#get().refreshTopic();
};
internal_updateTopicLinkedPullRequest = async (
@@ -1582,13 +1506,8 @@ export class ChatTopicActionImpl {
'internal_createTopic',
);
- this.#get().internal_updateTopicLoading(tmpId, true);
const topicId = await topicService.createTopic(params);
- this.#get().internal_updateTopicLoading(tmpId, false);
-
- this.#get().internal_updateTopicLoading(topicId, true);
await this.#get().refreshTopic();
- this.#get().internal_updateTopicLoading(topicId, false);
return topicId;
};
diff --git a/src/store/chat/slices/topic/initialState.ts b/src/store/chat/slices/topic/initialState.ts
index 00cdc3c8038..a81e24c5a86 100644
--- a/src/store/chat/slices/topic/initialState.ts
+++ b/src/store/chat/slices/topic/initialState.ts
@@ -69,12 +69,6 @@ export interface ChatTopicState {
* Contains items, total count, pagination state, and loading states
*/
topicDataMap: Record<string, TopicData>;
- /**
- * Internal ref-count for topic loading owners. A topic can be loading because
- * the agent is running and because title-summary is streaming at the same time.
- */
- topicLoadingIdCounts: Record<string, number>;
- topicLoadingIds: string[];
topicRenamingId?: string;
topicSearchKeywords: string;
}
@@ -88,7 +82,5 @@ export const initialTopicState: ChatTopicState = {
isSearchingTopic: false,
searchTopics: [],
topicDataMap: {},
- topicLoadingIdCounts: {},
- topicLoadingIds: [],
topicSearchKeywords: '',
};
diff --git a/src/store/chat/slices/topic/selectors.ts b/src/store/chat/slices/topic/selectors.ts
index e415171ae52..49930369854 100644
--- a/src/store/chat/slices/topic/selectors.ts
+++ b/src/store/chat/slices/topic/selectors.ts
@@ -265,7 +265,8 @@ const groupedTopicsForSidebar =
// though their persisted status says otherwise — that's the one client-only
// overlay (see resolveStatusBucket). Unread is now a persisted status, so it
// buckets straight from `topic.status`.
- const loadingTopicIds = groupMode === 'byStatus' ? new Set(s.topicLoadingIds) : undefined;
+ const loadingTopicIds =
+ groupMode === 'byStatus' ? operationSelectors.visiblyRunningTopicIds(s) : undefined;
return buildGroupedTopics(limitedTopics, getGroupFn(groupMode, sortBy, loadingTopicIds));
};