π€― 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: sidebar topic spinner, ordering and optimistic-row glitches around new-topic sends (#16801)
YuTengjing5212aceb9dbc
diff --git a/.agents/skills/skills-audit/SKILL.md b/.agents/skills/skills-audit/SKILL.mdindex d2a3b8404e5..bc1d337179d 100644--- a/.agents/skills/skills-audit/SKILL.md+++ b/.agents/skills/skills-audit/SKILL.md@@ -1,7 +1,6 @@---name: skills-auditdescription: 'Audit .agents/skills SKILL.md files. Use for recurring checks of duplicate, overlapping, stale, inconsistent, or broken skills and merge/delete candidates.'-disable-model-invocation: trueargument-hint: '[--verbose | --apply]'---diff --git a/src/features/ChatInput/ActionBar/SaveTopic/index.tsx b/src/features/ChatInput/ActionBar/SaveTopic/index.tsxdeleted file mode 100644index fabe633a678..00000000000--- a/src/features/ChatInput/ActionBar/SaveTopic/index.tsx+++ /dev/null@@ -1,104 +0,0 @@-import { HotkeyEnum } from '@lobechat/const/hotkeys';-import { ActionIcon, Flexbox, Hotkey, Tooltip } from '@lobehub/ui';-import { Popconfirm } from 'antd';-import { LucideGalleryVerticalEnd, LucideMessageSquarePlus } from 'lucide-react';-import { memo, useCallback, useState } from 'react';-import { useTranslation } from 'react-i18next';--import { useIsMobile } from '@/hooks/useIsMobile';-import { usePermission } from '@/hooks/usePermission';-import { useActionSWR } from '@/libs/swr';-import { topicActionKeys } from '@/libs/swr/keys';-import { useChatStore } from '@/store/chat';-import { useUserStore } from '@/store/user';-import { settingsSelectors } from '@/store/user/selectors';--const SaveTopic = memo(() => {- const { t } = useTranslation('chat');- const hotkey = useUserStore(settingsSelectors.getHotkeyById(HotkeyEnum.SaveTopic));- const { allowed: canCreateContent, reason } = usePermission('create_content');- const [hasTopic, openNewTopicOrSaveTopic] = useChatStore((s) => [- !!s.activeTopicId,- s.openNewTopicOrSaveTopic,- ]);-- const mobile = useIsMobile();-- const { mutate, isValidating } = useActionSWR(- topicActionKeys.openNewOrSave(),- openNewTopicOrSaveTopic,- );-- const [confirmOpened, setConfirmOpened] = useState(false);-- const icon = hasTopic ? LucideMessageSquarePlus : LucideGalleryVerticalEnd;- const desc = t(hasTopic ? 'topic.openNewTopic' : 'topic.saveCurrentMessages');-- const handleMutate = useCallback(() => {- if (!canCreateContent) return;-- mutate();- }, [canCreateContent, mutate]);-- const handleConfirmOpenChange = useCallback(- (nextOpen: boolean) => {- if (!canCreateContent) return;-- setConfirmOpened(nextOpen);- },- [canCreateContent],- );-- if (mobile) {- return (- <Popconfirm- arrow={false}- okButtonProps={{ danger: false, type: 'primary' }}- open={canCreateContent && confirmOpened}- placement={'top'}- title={- <Flexbox horizontal align={'center'} style={{ marginBottom: 8 }}>- <div style={{ marginRight: '16px', whiteSpace: 'pre-line', wordBreak: 'break-word' }}>- {t(hasTopic ? 'topic.checkOpenNewTopic' : 'topic.checkSaveCurrentMessages')}- </div>- <Hotkey keys={hotkey} />- </Flexbox>- }- onConfirm={handleMutate}- onOpenChange={handleConfirmOpenChange}- >- <Tooltip title={canCreateContent ? desc : reason}>- <div>- <ActionIcon- aria-label={desc}- disabled={!canCreateContent}- icon={icon}- loading={isValidating}- onClick={() => handleConfirmOpenChange(true)}- />- </div>- </Tooltip>- </Popconfirm>- );- } else {- return (- <ActionIcon- aria-label={desc}- disabled={!canCreateContent}- icon={icon}- loading={isValidating}- size={{ blockSize: 32, size: 16, strokeWidth: 2.3 }}- title={canCreateContent ? desc : reason}- variant={'outlined'}- tooltipProps={{- hotkey,- }}- onClick={handleMutate}- />- );- }-});--SaveTopic.displayName = 'SaveTopic';--export default SaveTopic;diff --git a/src/features/ChatInput/ActionBar/config.ts b/src/features/ChatInput/ActionBar/config.tsindex b5b082dcd06..ac95b39dd8d 100644--- a/src/features/ChatInput/ActionBar/config.ts+++ b/src/features/ChatInput/ActionBar/config.ts@@ -8,7 +8,6 @@ import ModelLabel from './ModelLabel';import Params from './Params';import Plus from './Plus';import PromptTransform from './PromptTransform';-import SaveTopic from './SaveTopic';import Search from './Search';import ContextWindow from './Token';import Tools from './Tools';@@ -28,7 +27,6 @@ export const actionMap = {modelLabel: ModelLabel,params: Params,promptTransform: PromptTransform,- saveTopic: SaveTopic,search: Search,temperature: Params,tools: Tools,diff --git a/src/features/CommandMenu/MainMenu.tsx b/src/features/CommandMenu/MainMenu.tsxindex d7ad31ffd86..255c0df4b04 100644--- a/src/features/CommandMenu/MainMenu.tsx+++ b/src/features/CommandMenu/MainMenu.tsx@@ -17,6 +17,8 @@ import { openFeedbackModal } from '@/components/FeedbackModal';import { getNavigableRoutes, getRouteById } from '@/config/routes';import { FEEDBACK } from '@/const/url';import { usePermission } from '@/hooks/usePermission';+import { useChatStore } from '@/store/chat';+import { topicSelectors } from '@/store/chat/selectors';import { useCommandMenuContext } from './CommandMenuContext';import { CommandItem } from './components';@@ -27,6 +29,10 @@ const MainMenu = memo(() => {const { pathname, menuContext, setPages, pages, onClose } = useCommandMenuContext();const { t } = useTranslation('common');const { allowed: canCreate } = usePermission('create_content');+ // While the first send from the new-topic view is still creating the real+ // topic, openNewTopicOrSaveTopic is a no-op β disable the command instead of+ // letting it close the palette as a false success (same as the sidebar entry).+ const isNewTopicSendInFlight = useChatStore(topicSelectors.isNewTopicSendInFlight);const {handleCreateSession,@@ -65,7 +71,7 @@ const MainMenu = memo(() => {{menuContext === 'agent' && (<CommandItem- disabled={!canCreate}+ disabled={!canCreate || isNewTopicSendInFlight}icon={<MessageSquarePlusIcon />}unpinned={menuContext !== 'agent'}value="create new topic"diff --git a/src/features/CommandMenu/useCommandMenu.ts b/src/features/CommandMenu/useCommandMenu.tsindex 41f1f7d92ed..f815639606d 100644--- a/src/features/CommandMenu/useCommandMenu.ts+++ b/src/features/CommandMenu/useCommandMenu.ts@@ -15,6 +15,7 @@ import { electronSystemService } from '@/services/electron/system';import { useAgentStore } from '@/store/agent';import { builtinAgentSelectors } from '@/store/agent/selectors/builtinAgentSelectors';import { useChatStore } from '@/store/chat';+import { topicSelectors } from '@/store/chat/selectors';import { useGlobalStore } from '@/store/global';import { globalHelpers } from '@/store/global/helpers';import { useHomeStore } from '@/store/home';@@ -171,6 +172,10 @@ export const useCommandMenu = () => {const handleCreateTopic = useCallback(() => {if (!canCreate) return;+ // The command item is disabled while a new-topic send is in flight, but a+ // selection can still race the window opening β don't close the palette on+ // what would be a silent no-op in openNewTopicOrSaveTopic.+ if (topicSelectors.isNewTopicSendInFlight(useChatStore.getState())) return;openNewTopicOrSaveTopic();onClose();diff --git a/src/features/NavPanel/components/NavItem.tsx b/src/features/NavPanel/components/NavItem.tsxindex 27c08d50346..73e022f7a3c 100644--- a/src/features/NavPanel/components/NavItem.tsx+++ b/src/features/NavPanel/components/NavItem.tsx@@ -89,6 +89,7 @@ const NavItem = memo<NavItemProps>(loading,extra,slots,+ style,...rest}) => {const iconColor = active ? cssVar.colorText : cssVar.colorTextDescription;@@ -101,10 +102,20 @@ const NavItem = memo<NavItemProps>(? {as: 'a' as const,href,- style: { color: 'inherit', textDecoration: 'none' },}: {};+ const mergedStyle =+ href || disabled || style+ ? {+ ...(href ? { color: 'inherit', textDecoration: 'none' } : undefined),+ // `disabled` only blocks the click by itself β dim the row so the+ // blocked state is visible instead of a silently dead button.+ ...(disabled ? { cursor: 'not-allowed', opacity: 0.5 } : undefined),+ ...style,+ }+ : undefined;+const Content = (<Blockhorizontal@@ -115,6 +126,7 @@ const NavItem = memo<NavItemProps>(height={description ? undefined : 36}paddingBlock={description ? 4 : undefined}paddingInline={4}+ style={mergedStyle}variant={variant}onClick={(e) => {// Always prevent default <a> navigation for normal clicks to avoid full page reload.diff --git a/src/routes/(main)/agent/_layout/Sidebar/Header/Nav.tsx b/src/routes/(main)/agent/_layout/Sidebar/Header/Nav.tsxindex fdc3c73c4c0..de9695bedbb 100644--- a/src/routes/(main)/agent/_layout/Sidebar/Header/Nav.tsx+++ b/src/routes/(main)/agent/_layout/Sidebar/Header/Nav.tsx@@ -22,6 +22,7 @@ import { topicActionKeys } from '@/libs/swr/keys';import { useAgentStore } from '@/store/agent';import { agentSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';+import { topicSelectors } from '@/store/chat/selectors';import { useGlobalStore } from '@/store/global';import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';@@ -49,10 +50,11 @@ const Nav = memo(() => {hideProfile || (!!heterogeneousProviderType && heterogeneousProviderType !== 'claude-code');const switchTopic = useChatStore((s) => s.switchTopic);const [openNewTopicOrSaveTopic] = useChatStore((s) => [s.openNewTopicOrSaveTopic]);+ const isNewTopicSendInFlight = useChatStore(topicSelectors.isNewTopicSendInFlight);const { mutate } = useActionSWR(topicActionKeys.openNewOrSave(), openNewTopicOrSaveTopic);const handleNewTopic = () => {- if (!canCreateTopic) return;+ if (!canCreateTopic || isNewTopicSendInFlight) return;// Always navigate to the bare agent chat URL β drops any sub-route// (/profile, /channel, /page, /cron/:cronId, β¦) and any `:topicId`// segment so the new topic isn't conflated with the previous URL.@@ -65,7 +67,7 @@ const Nav = memo(() => {return (<Flexbox gap={1} paddingInline={4}><NavItem- disabled={!canCreateTopic}+ disabled={!canCreateTopic || isNewTopicSendInFlight}icon={MessageSquarePlusIcon}title={tTopic('actions.addNewTopic')}onClick={handleNewTopic}diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsxindex 3c2918f07f0..bdfdaceeb31 100644--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx@@ -275,8 +275,11 @@ const TopicItem = memo<TopicItemProps>(const isFailed = status === 'failed';const isRunning = status === 'running';const isWaitingForHuman = status === 'waitingForHuman';- const shouldShowRunningIcon =- isLoading || (isRunning && (!hasLocalRunningRuntime || isRuntimeVisiblyRunning));+ // Post-visible-output tail: the user-visible answer is complete but the run+ // is still doing terminal bookkeeping (unread persist, title summary) β+ // #16518 intentionally masks the running icon during this window.+ const isMaskedRunningTail = isRunning && hasLocalRunningRuntime && !isRuntimeVisiblyRunning;+ const shouldShowRunningIcon = isLoading || (isRunning && !isMaskedRunningTail);// By-status grouping mixes topics from different projects, so surface each// topic's working directory as a muted second line. Data is already on the@@ -293,7 +296,12 @@ const TopicItem = memo<TopicItemProps>(</Flexbox>) : undefined;- const hasUnread = id && isUnreadCompleted;+ // Surface the unread dot right away during the masked tail instead of a+ // blank icon gap until markTopicUnread's persisted 'unread' lands. Skipped+ // while the user is viewing the topic, like markTopicUnread's own guard.+ const isRunningTailUnread = isMaskedRunningTail && !isTopicActive;++ const hasUnread = id && (isUnreadCompleted || isRunningTailUnread);const unreadIcon = (<span className={styles.unreadWrapper}><span className={styles.unreadRipple} />diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.tsindex f7cbb653d80..8faecf5d71a 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts@@ -567,6 +567,177 @@ describe('ConversationLifecycle actions', () => {expect(useChatStore.getState().topicLoadingIds).not.toContain(newTopicId);});+ it('should release the migrated topicLoadingIds owner after a gateway send creates the topic', async () => {+ const { result } = renderHook(() => useChatStore());+ const agentId = TEST_IDS.SESSION_ID;+ const topicKey = topicMapKey({ agentId });+ const newTopicId = TEST_IDS.NEW_TOPIC_ID;+ let resolveGateway!: () => void;+ const executeGatewayAgentSpy = vi.fn().mockImplementation(+ (params: any) =>+ 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+ // 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`).+ useChatStore.getState().internal_replaceTopicId({+ nextId: newTopicId,+ previousId: params.optimisticTopic.id,+ });+ useChatStore.getState().completeOperation(params.parentOperationId);+ resolve({+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ operationId: 'gateway-op-release',+ topicId: newTopicId,+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ });+ };+ }),+ );++ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ activeTopicId: undefined,+ executeGatewayAgent: executeGatewayAgentSpy,+ isGatewayModeEnabled: () => true,+ summaryTopicTitle: vi.fn().mockResolvedValue(undefined),+ topicDataMap: {+ [topicKey]: {+ currentPage: 0,+ hasMore: false,+ isExpandingPageSize: false,+ isLoadingMore: false,+ items: [],+ pageSize: 20,+ total: 0,+ },+ },+ });+ });++ let sendPromise!: ReturnType<typeof result.current.sendMessage>;+ act(() => {+ sendPromise = result.current.sendMessage({+ context: { agentId, threadId: null, topicId: null },+ message: 'hello',+ });+ });++ await waitFor(() => expect(executeGatewayAgentSpy).toHaveBeenCalled());++ const optimisticTopicId = useChatStore.getState().topicDataMap[topicKey]?.items[0]?.id;+ expect(optimisticTopicId).toMatch(/^tmp_topic_/);+ expect(useChatStore.getState().topicLoadingIds).toContain(optimisticTopicId);++ await act(async () => {+ resolveGateway();+ await sendPromise;+ // Let the fire-and-forget afterUserMessagePersisted title task settle+ // inside this test instead of leaking into the next one.+ await Promise.resolve();+ await Promise.resolve();+ });++ // 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);+ });++ it('should hold the migrated topicLoadingIds owner through a hetero new-topic run and release it at the end', async () => {+ mockConstEnv.isDesktop = true;+ setupMockSelectors({+ agentConfig: {+ agencyConfig: {+ heterogeneousProvider: { command: 'codex', type: 'codex' },+ },+ },+ });++ const { result } = renderHook(() => useChatStore());+ const agentId = TEST_IDS.SESSION_ID;+ const topicKey = topicMapKey({ agentId });+ const newTopicId = TEST_IDS.NEW_TOPIC_ID;++ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ activeTopicId: undefined,+ summaryTopicTitle: vi.fn().mockResolvedValue(undefined),+ topicDataMap: {+ [topicKey]: {+ currentPage: 0,+ hasMore: false,+ isExpandingPageSize: false,+ isLoadingMore: false,+ items: [],+ pageSize: 20,+ total: 0,+ },+ },+ });+ });++ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ isCreateNewTopic: true,+ messages: [+ createMockMessage({+ id: TEST_IDS.USER_MESSAGE_ID,+ role: 'user',+ topicId: newTopicId,+ }),+ createMockMessage({+ id: TEST_IDS.ASSISTANT_MESSAGE_ID,+ role: 'assistant',+ topicId: newTopicId,+ }),+ ],+ topicId: newTopicId,+ topics: { items: [{ id: newTopicId, title: 'Server Topic' }], total: 1 },+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ } as any);++ let resolveExecutor!: () => void;+ executeHeterogeneousAgentMock.mockReturnValue(+ new Promise<void>((resolve) => {+ resolveExecutor = resolve;+ }),+ );++ let sendPromise!: ReturnType<typeof result.current.sendMessage>;+ act(() => {+ sendPromise = result.current.sendMessage({+ context: { agentId, threadId: null, topicId: null },+ message: 'hello',+ });+ });++ 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);++ await act(async () => {+ resolveExecutor();+ await sendPromise;+ // Let the fire-and-forget afterUserMessagePersisted title task settle+ // inside this test instead of leaking into the next one.+ await Promise.resolve();+ await Promise.resolve();+ });++ expect(useChatStore.getState().topicLoadingIds).not.toContain(newTopicId);+ });+it('should keep a gateway optimistic topic in its pending repo project group', async () => {const { result } = renderHook(() => useChatStore());const agentId = TEST_IDS.SESSION_ID;diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.tsindex 20d2890a58d..cea91157b2a 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts@@ -845,6 +845,12 @@ 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.}// Clean up temp messages@@ -946,6 +952,16 @@ 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 {@@ -1001,6 +1017,19 @@ export class ConversationLifecycleActionImpl {// the new topic, so the shared hook reads the persisted conversation from// 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.+ if (optimisticTopic && optimisticTopicActive) {+ this.#get().internal_updateTopicLoading(result.topicId, false);+ optimisticTopicActive = false;+ }void sendRunLifecycle.afterUserMessagePersisted({assistantMessageId: result.assistantMessageId,diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.tsindex 5d8d3fd23f3..cafb445f716 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts@@ -584,11 +584,11 @@ export const createGatewayEventHandler = (// means visible output is done; the operation still waits for// agent_runtime_end to preserve terminal side-effect ordering.get().updateOperationMetadata(operationId, { visibleLoadingDone: true });- // The sidebar "running" spinner is driven off `topic.status === 'running'`- // (persisted, reset at the terminal) for gateway/hetero runs β no- // client-only `topicLoadingIds` early-clear here, so the topic keeps- // spinning through the post-visible-output terminal side-effects until- // the run actually completes.+ // From here the sidebar item stops showing the running spinner (the+ // answer is visibly complete) and β when the user isn't viewing the+ // topic β shows the unread dot instead, ahead of markTopicUnread's+ // persisted 'unread' at the terminal. See `isRunningTailUnread` in+ // the sidebar topic Item.});break;}diff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.tsindex db0d10aaf0f..70f7c127eb3 100644--- a/src/store/chat/slices/topic/action.test.ts+++ b/src/store/chat/slices/topic/action.test.ts@@ -132,6 +132,26 @@ describe('topic action', () => {expect(saveToTopicSpy).toHaveBeenCalled();});++ it('should skip saveToTopic when a send is still in flight in the new-topic context', async () => {+ const { result } = renderHook(() => useChatStore());+ act(() => {+ useChatStore.setState({ activeAgentId: 'session', activeTopicId: undefined });+ // Simulate an in-flight send from the new-topic view (topic not created yet)+ result.current.startOperation({+ type: 'sendMessage',+ context: { agentId: 'session', topicId: null },+ });+ });++ const saveToTopicSpy = vi.spyOn(result.current, 'saveToTopic');++ await act(async () => {+ await result.current.openNewTopicOrSaveTopic();+ });++ expect(saveToTopicSpy).not.toHaveBeenCalled();+ });});describe('saveToTopic', () => {it('should not create a topic if there are no messages', async () => {diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.tsindex 3ade42f3f9c..655d34da6f7 100644--- a/src/store/chat/slices/topic/action.ts+++ b/src/store/chat/slices/topic/action.ts@@ -101,6 +101,15 @@ export class ChatTopicActionImpl {if (hasTopic) switchTopic(null);else {+ // A send from the new-topic view may still be in flight (the `_new`+ // context holds only optimistic tmp_* messages while the run itself+ // creates the real topic). Saving here would archive those tmp ids into+ // a spurious "Default Topic" and race the in-flight topic creation,+ // leaving the real topic's loading state stuck until reload. Skip:+ // the running send owns topic creation. Entry buttons are disabled via+ // the same selector, so this guard only backstops hotkey/command paths.+ if (topicSelectors.isNewTopicSendInFlight(this.#get())) return;+await saveToTopic();refreshMessages();}@@ -325,6 +334,52 @@ export class ChatTopicActionImpl {await this.#get().internal_updateTopic(id, { title });};+ /**+ * Optimistic `updateTopicStatus` writes that a topic-list refetch must not+ * clobber. A refetch whose server query ran BEFORE a status write can land+ * AFTER the optimistic dispatch and revert the row β e.g. a run-end 'unread'+ * reverting to 'running', leaving the sidebar spinning forever on a finished+ * topic. Fetched rows are reconciled against this map: a row still carrying+ * the pre-write status gets the pending status re-applied; a row already+ * reflecting it confirms propagation and drops the pin. TTL-bounded so a+ * failed persist or a legit cross-device status change can't be suppressed+ * indefinitely.+ */+ #pendingTopicStatusWrites = new Map<string, { expiresAt: number; status: ChatTopicStatus }>();++ #reconcileFetchedTopics = (items: ChatTopic[], currentItems?: ChatTopic[]): ChatTopic[] => {+ let next = items;++ if (this.#pendingTopicStatusWrites.size > 0) {+ next = next.map((item) => {+ const pending = this.#pendingTopicStatusWrites.get(item.id);+ if (!pending) return item;+ if (pending.expiresAt <= Date.now() || item.status === pending.status) {+ this.#pendingTopicStatusWrites.delete(item.id);+ return item;+ }+ return { ...item, status: pending.status };+ });+ }++ // In-flight first-send optimistic rows (`tmp_topic_*`) are client-only, so+ // any refetch landing mid-send (e.g. the fire-and-forget refreshTopic after+ // a previous run's topic creation or terminal) would wipe them from the+ // sidebar until the server returns the real topicId. Re-prepend the ones+ // still in the bucket β they only ever leave it via replaceTopicId (send+ // resolved) or deleteTopic (rollback), never via a fetch.+ if (currentItems && currentItems.length > 0) {+ const optimisticRows = currentItems.filter((item) => item.id.startsWith('tmp_topic_'));+ if (optimisticRows.length > 0) {+ const fetchedIds = new Set(next.map((item) => item.id));+ const surviving = optimisticRows.filter((item) => !fetchedIds.has(item.id));+ if (surviving.length > 0) next = [...surviving, ...next];+ }+ }++ return next;+ };+/*** Persist the topic's status. Optimistically patches the in-memory map so* the sidebar reflects the change immediately; persistence runs@@ -355,6 +410,8 @@ export class ChatTopicActionImpl {// Already at the target status β both the in-memory and DB writes are no-ops.if (topic?.status === status) return;+ this.#pendingTopicStatusWrites.set(topicId, { expiresAt: Date.now() + 15_000, status });+// Scope on the payload routes the write to the owning bucket inside// `internal_dispatchTopic`. A no-op if the bucket isn't loaded; the DB// write below still ensures the status sticks across the next refetch.@@ -368,6 +425,8 @@ export class ChatTopicActionImpl {await topicService.updateTopic(topicId, { status }).catch((err) => {console.error('[updateTopicStatus] persist failed:', err);+ // The DB never got the write β stop pinning it over fetched rows.+ this.#pendingTopicStatusWrites.delete(topicId);});};@@ -463,9 +522,10 @@ export class ChatTopicActionImpl {onData: (result) => {if (!hasValidContainer) return;- const { items: topics, total: totalCount } = result;+ const { total: totalCount } = result;const currentData = this.#get().topicDataMap[containerKey];+ const topics = this.#reconcileFetchedTopics(result.items, currentData?.items);const isRefreshingExpandedList =!!currentData &&@@ -570,9 +630,10 @@ export class ChatTopicActionImpl {{onData: (result) => {if (!hasValidAgent) return;- const { items: topics, total: totalCount } = result;+ const { total: totalCount } = result;const currentData = this.#get().agentTopicsViewMap[containerKey];+ const topics = this.#reconcileFetchedTopics(result.items, currentData?.items);// Preserve appended pages on refresh β same convention as// `useFetchTopics` so the user keeps their scroll position after@@ -804,8 +865,11 @@ export class ChatTopicActionImpl {topicService.searchTopics(keywords, agentId, groupId),{onSuccess: (data) => {+ // Search rows render the same status icon as the sidebar β pin+ // pending status writes here too (no tmp-row re-prepend: optimistic+ // rows don't belong in search results).this.#set(- { searchTopics: data, isSearchingTopic: false },+ { searchTopics: this.#reconcileFetchedTopics(data), isSearchingTopic: false },false,n('useSearchTopics(success)', { keywords }),);@@ -1192,9 +1256,15 @@ export class ChatTopicActionImpl {total: number;},): void => {- const { items, total, pageSize, currentPage = 0, append = false, groupId } = params;+ const { total, pageSize, currentPage = 0, append = false, groupId } = params;const key = topicMapKey({ agentId, groupId });const currentData = this.#get().topicDataMap[key];+ // Append mode keeps the existing items (optimistic rows included) in front,+ // so only pass them for reconciliation on full replacement.+ const items = this.#reconcileFetchedTopics(+ params.items,+ append ? undefined : currentData?.items,+ );const nextItems = append ? [...(currentData?.items || []), ...items] : items;diff --git a/src/store/chat/slices/topic/reducer.ts b/src/store/chat/slices/topic/reducer.tsindex eb41f148840..0093ab0e6ad 100644--- a/src/store/chat/slices/topic/reducer.ts+++ b/src/store/chat/slices/topic/reducer.ts@@ -70,9 +70,19 @@ export const topicReducer = (state: ChatTopic[] = [], payload: ChatTopicDispatch// Only update if the merged value is different from current (excluding updatedAt).// Compare against a plain snapshot, not the raw draft proxy β see message/reducer.ts.if (!isEqual(current(currentTopic), mergedTopic)) {- // TODO: updatedAt type needs to be changed to Date later- // @ts-ignore- draftState[topicIndex] = { ...mergedTopic, updatedAt: new Date() };+ // Status flips (running/unread/read bookkeeping) are not user activity β+ // bumping updatedAt here reorders the updatedAt-sorted sidebar on every+ // run end / topic read, and the bump reverts on the next refetch (the+ // server orders by latest-message time), so rows visibly jump around.+ const isStatusOnlyWrite = Object.keys(value).every((key) => key === 'status');++ if (isStatusOnlyWrite) {+ draftState[topicIndex] = mergedTopic;+ } else {+ // TODO: updatedAt type needs to be changed to Date later+ // @ts-ignore+ draftState[topicIndex] = { ...mergedTopic, updatedAt: new Date() };+ }}}});diff --git a/src/store/chat/slices/topic/selectors.ts b/src/store/chat/slices/topic/selectors.tsindex a85914978a4..61f3ae8209d 100644--- a/src/store/chat/slices/topic/selectors.ts+++ b/src/store/chat/slices/topic/selectors.ts@@ -18,6 +18,7 @@ import {import { type ChatStoreState } from '../../initialState';import { topicMapKey } from '../../utils/topicMapKey';+import { operationSelectors } from '../operation/selectors';import { type TopicData } from './initialState';// Helper selector: get current topic data based on session context@@ -106,6 +107,23 @@ const currentTopicWorkingDirectory = (s: ChatStoreState): string | undefined =>};const isCreatingTopic = (s: ChatStoreState) => s.creatingTopic;++/**+ * Whether a send from the new-topic view is still in flight β no active topic+ * yet, while the running send owns creation of the real topic (the `_new`+ * context only holds optimistic tmp_* messages until then). While true,+ * `openNewTopicOrSaveTopic` is a no-op, so its entry buttons should be+ * disabled to make the blocked window visible instead of silently ignoring+ * the click.+ */+const isNewTopicSendInFlight = (s: ChatStoreState): boolean =>+ !s.activeTopicId &&+ operationSelectors.isInputLoadingByContext({+ agentId: s.activeAgentId,+ groupId: s.activeGroupId,+ threadId: s.activeThreadId,+ topicId: s.activeTopicId,+ })(s);const isUndefinedTopics = (s: ChatStoreState) => !currentTopics(s);const isInSearchMode = (s: ChatStoreState) => s.inSearchingMode;const isSearchingTopic = (s: ChatStoreState) => s.isSearchingTopic;@@ -266,6 +284,7 @@ export const topicSelectors = {isExpandingPageSize,isInSearchMode,isLoadingMoreTopics,+ isNewTopicSendInFlight,isSearchingTopic,isUndefinedTopics,loadMoreTopicsError,