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(project): keep the conversation workspace mounted when switching topics (#21533)

LiJianae4566a296d2
diff --git a/src/features/Conversation/hooks/useTopicDetailSendGuard.test.ts b/src/features/Conversation/hooks/useTopicDetailSendGuard.test.ts
new file mode 100644
index 00000000000..2951a055fe9
--- /dev/null
+++ b/src/features/Conversation/hooks/useTopicDetailSendGuard.test.ts
@@ -0,0 +1,93 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useChatStore } from '@/store/chat';
+
+import { ensureTopicBeforeRun, useTopicDetailSendGuard } from './useTopicDetailSendGuard';
+
+const refreshTopicDetail = vi.fn();
+
+describe('ensureTopicBeforeRun', () => {
+ beforeEach(() => {
+ refreshTopicDetail.mockReset();
+ act(() =>
+ useChatStore.setState({
+ activeAgentId: 'agt_cook',
+ refreshTopicDetail,
+ topicDataMap: {},
+ topicDetailMap: {},
+ } as any),
+ );
+ });
+
+ /**
+ * @example Codex review: a send on a first visit to a project topic ran with
+ * the agent's default model and routing, because the topic row had not
+ * reached the store yet.
+ */
+ it('reads the detail of a topic the store does not hold before the run starts', async () => {
+ const order: string[] = [];
+ refreshTopicDetail.mockImplementation(async () => {
+ await Promise.resolve();
+ order.push('detail');
+ });
+
+ await ensureTopicBeforeRun('tpc_new').then(() => order.push('run'));
+
+ expect(refreshTopicDetail).toHaveBeenCalledWith('tpc_new', true);
+ expect(order).toEqual(['detail', 'run']);
+ });
+
+ it('does not refetch a topic the store already holds', async () => {
+ act(() => useChatStore.setState({ topicDetailMap: { tpc_known: { id: 'tpc_known' } } } as any));
+
+ await ensureTopicBeforeRun('tpc_known');
+ await ensureTopicBeforeRun(undefined);
+
+ expect(refreshTopicDetail).not.toHaveBeenCalled();
+ });
+
+ it('lets the run through when the detail cannot be read', async () => {
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ refreshTopicDetail.mockRejectedValue(new Error('offline'));
+
+ await expect(ensureTopicBeforeRun('tpc_new')).resolves.toBeUndefined();
+
+ consoleError.mockRestore();
+ });
+});
+
+describe('useTopicDetailSendGuard', () => {
+ beforeEach(() => {
+ refreshTopicDetail.mockReset();
+ act(() =>
+ useChatStore.setState({
+ refreshTopicDetail,
+ topicDataMap: {},
+ topicDetailMap: {},
+ } as any),
+ );
+ });
+
+ it('guards every generation on the current topic and never blocks it', async () => {
+ const { result, rerender } = renderHook(({ topicId }) => useTopicDetailSendGuard(topicId), {
+ initialProps: { topicId: 'tpc_a' as string | undefined },
+ });
+ const hooks = result.current;
+ rerender({ topicId: 'tpc_b' });
+
+ await expect(hooks.onBeforeSendMessage!({} as any)).resolves.toBeUndefined();
+ await hooks.onBeforeRegenerate!('msg_1');
+ await hooks.onBeforeContinue!('msg_1');
+
+ expect(result.current).toBe(hooks);
+ expect(refreshTopicDetail.mock.calls).toEqual([
+ ['tpc_b', true],
+ ['tpc_b', true],
+ ['tpc_b', true],
+ ]);
+ });
+});
diff --git a/src/features/Conversation/hooks/useTopicDetailSendGuard.ts b/src/features/Conversation/hooks/useTopicDetailSendGuard.ts
new file mode 100644
index 00000000000..f5c81dd492c
--- /dev/null
+++ b/src/features/Conversation/hooks/useTopicDetailSendGuard.ts
@@ -0,0 +1,46 @@
+import { useMemo, useRef } from 'react';
+
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+
+import { type ConversationHooks } from '../types';
+
+/**
+ * Make sure the chat store holds the topic row before a run starts in it.
+ *
+ * A run reads the topic's saved configuration from the store: its pinned
+ * model, working directory and device. A topic opened before any list or
+ * detail read reached the store (a first visit to a project topic, a deep link
+ * past the loaded pages) would otherwise run on the agent's defaults. On a miss
+ * this reads the detail first. A failed read lets the run through as before.
+ */
+export const ensureTopicBeforeRun = async (topicId: string | null | undefined): Promise<void> => {
+ if (!topicId) return;
+
+ const state = useChatStore.getState();
+ if (topicSelectors.getTopicById(topicId)(state)) return;
+
+ try {
+ await state.refreshTopicDetail(topicId, true);
+ } catch (error) {
+ console.error('[ensureTopicBeforeRun] Failed to fetch topic detail:', error);
+ }
+};
+
+/** Conversation hooks that hold a send, regenerate or continue on `ensureTopicBeforeRun`. */
+export const useTopicDetailSendGuard = (topicId: string | null | undefined): ConversationHooks => {
+ const topicIdRef = useRef(topicId);
+ topicIdRef.current = topicId;
+
+ return useMemo(() => {
+ const guard = async (): Promise<void> => {
+ await ensureTopicBeforeRun(topicIdRef.current);
+ };
+
+ return {
+ onBeforeContinue: guard,
+ onBeforeRegenerate: guard,
+ onBeforeSendMessage: guard,
+ };
+ }, []);
+};
diff --git a/src/features/Projects/Conversation/index.tsx b/src/features/Projects/Conversation/index.tsx
index 98758af615a..f2a87512ace 100644
--- a/src/features/Projects/Conversation/index.tsx
+++ b/src/features/Projects/Conversation/index.tsx
@@ -6,6 +6,7 @@ import { useTranslation } from 'react-i18next';
import { Navigate, useParams, useSearchParams } from 'react-router';
import AsyncError from '@/components/AsyncError';
+import ConversationSegmentSkeleton from '@/components/Skeleton/Conversation/Segment';
import TopicActions from '@/features/AgentSidebar/Topic/List/Item/Actions';
import ConversationWorkspace from '@/features/Conversation/Workspace';
import NavHeader from '@/features/NavHeader';
@@ -26,6 +27,7 @@ import {
import { getProjectConversationPath } from '../Layout/navigation';
import { freshProjectTopicAgentId } from './freshProjectTopicAgentId';
+import { projectConversationStage } from './projectConversationStage';
import { useMarkProjectTopicRead } from './useMarkProjectTopicRead';
import { useProjectDraftStaging } from './useProjectDraftStaging';
import { useRevalidateWhileUnlisted } from './useRevalidateWhileUnlisted';
@@ -142,13 +144,13 @@ const ProjectConversation = memo(() => {
if (detailSWR.error && !detail) {
return <AsyncError error={detailSWR.error} variant="page" onRetry={detailSWR.revalidate} />;
}
- if (
- !detail ||
- !conversationAgentId ||
- agent.isLoading ||
- (!storedTopic && topicDetail.isValidating) ||
- chatAgentId !== conversationAgentId
- ) {
+ const stage = projectConversationStage({
+ agentConfigLoading: !!agent.isLoading,
+ chatAgentId,
+ conversationAgentId,
+ hasProject: !!detail,
+ });
+ if (stage === 'loading') {
return (
<Center height="100%" width="100%">
<Spin size="small" />
@@ -184,15 +186,23 @@ const ProjectConversation = memo(() => {
/>
}
>
- <ChatHydration getConversationPath={getConversationPath} getTopicPath={getTopicPath} />
- <Flexbox
- flex={1}
- style={{ minHeight: 0, minWidth: 0 }}
- onFocusCapture={restageDraft}
- onPointerDownCapture={restageDraft}
- >
- <ChatConversation />
- </Flexbox>
+ {stage === 'ready' ? (
+ <>
+ <ChatHydration getConversationPath={getConversationPath} getTopicPath={getTopicPath} />
+ <Flexbox
+ flex={1}
+ style={{ minHeight: 0, minWidth: 0 }}
+ onFocusCapture={restageDraft}
+ onPointerDownCapture={restageDraft}
+ >
+ <ChatConversation />
+ </Flexbox>
+ </>
+ ) : (
+ // Not delayed: the header is already on screen, and a blank column
+ // reads as the composer blinking out.
+ <ConversationSegmentSkeleton />
+ )}
</ConversationWorkspace>
);
});
diff --git a/src/features/Projects/Conversation/projectConversationStage.test.ts b/src/features/Projects/Conversation/projectConversationStage.test.ts
new file mode 100644
index 00000000000..370c2ce1729
--- /dev/null
+++ b/src/features/Projects/Conversation/projectConversationStage.test.ts
@@ -0,0 +1,40 @@
+import { describe, expect, it } from 'vitest';
+
+import { projectConversationStage } from './projectConversationStage';
+
+const ready = {
+ agentConfigLoading: false,
+ chatAgentId: 'agt_cook',
+ conversationAgentId: 'agt_cook',
+ hasProject: true,
+};
+
+describe('projectConversationStage', () => {
+ it('waits with the whole pane until the project and its agent are known', () => {
+ expect(projectConversationStage({ ...ready, hasProject: false })).toBe('loading');
+ expect(projectConversationStage({ ...ready, conversationAgentId: undefined })).toBe('loading');
+ });
+
+ it('renders the conversation once its agent is loaded and synced', () => {
+ expect(projectConversationStage(ready)).toBe('ready');
+ });
+
+ /**
+ * @example Switching to a topic of another agent swapped the whole workspace
+ * for a spinner, so the header and composer blinked out before the
+ * conversation mounted again.
+ */
+ it('keeps the workspace while a newly selected agent loads or syncs', () => {
+ expect(
+ projectConversationStage({
+ ...ready,
+ agentConfigLoading: true,
+ chatAgentId: 'agt_sam',
+ conversationAgentId: 'agt_sam',
+ }),
+ ).toBe('agentPending');
+ expect(projectConversationStage({ ...ready, conversationAgentId: 'agt_sam' })).toBe(
+ 'agentPending',
+ );
+ });
+});
diff --git a/src/features/Projects/Conversation/projectConversationStage.ts b/src/features/Projects/Conversation/projectConversationStage.ts
new file mode 100644
index 00000000000..c767e03f8d7
--- /dev/null
+++ b/src/features/Projects/Conversation/projectConversationStage.ts
@@ -0,0 +1,28 @@
+/**
+ * How much of the project conversation pane can render.
+ *
+ * - `loading`: the project or the conversation's agent is not known yet, so
+ * there is no workspace to frame. The whole pane waits.
+ * - `agentPending`: the workspace stays mounted while a newly selected agent
+ * loads its config or reaches the chat store. Only the conversation waits.
+ * - `ready`: the conversation renders.
+ *
+ * A topic switch must not drop back to `loading`: that unmounts the workspace,
+ * so the header and composer blink out and the message list starts over. A
+ * topic whose detail is still being fetched is `ready` too. Its readers update
+ * when the row lands, and a send waits for the row (`useTopicDetailSendGuard`).
+ */
+export type ProjectConversationStage = 'agentPending' | 'loading' | 'ready';
+
+export const projectConversationStage = (params: {
+ agentConfigLoading: boolean;
+ chatAgentId: string | undefined;
+ conversationAgentId: string | undefined;
+ hasProject: boolean;
+}): ProjectConversationStage => {
+ const { agentConfigLoading, chatAgentId, conversationAgentId, hasProject } = params;
+ if (!hasProject || !conversationAgentId) return 'loading';
+ if (agentConfigLoading || chatAgentId !== conversationAgentId) return 'agentPending';
+
+ return 'ready';
+};
diff --git a/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx b/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx
index 2e6fc36e4ec..94247f89a94 100644
--- a/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx
+++ b/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx
@@ -16,6 +16,7 @@ import { ChatList, ConversationProvider } from '@/features/Conversation';
import { useMessageDeepLink } from '@/features/Conversation/ChatList/hooks/useMessageDeepLink';
import ComposerDraftReceiver from '@/features/Conversation/ComposerDraftReceiver';
import { useChatFollowUp } from '@/features/Conversation/hooks/useChatFollowUp';
+import { useTopicDetailSendGuard } from '@/features/Conversation/hooks/useTopicDetailSendGuard';
import {
ForwardMessageDispatcher,
MessageForwardFooter,
@@ -114,6 +115,9 @@ const Conversation = memo(() => {
// First in the chain: a send on an unconfirmed `/agent/<slug>` must not reach
// the agent painted from the local copy before the server confirms it.
const slugRouteSendGuard = useSlugRouteSendGuard();
+ // A run reads the topic's pinned model and routing from the store, so a send
+ // into a topic the store has not loaded yet waits for its detail.
+ const topicDetailSendGuard = useTopicDetailSendGuard(context.topicId);
// A topic still awaiting its transfer backfill shows a placeholder instead
// of an empty (not-yet-migrated) history, and blocks sending — the server
@@ -125,8 +129,14 @@ const Conversation = memo(() => {
);
const hooks = useMemo(
- () => mergeConversationHooks(slugRouteSendGuard, businessAnalyticsHooks, chatFollowUpHooks),
- [slugRouteSendGuard, businessAnalyticsHooks, chatFollowUpHooks],
+ () =>
+ mergeConversationHooks(
+ slugRouteSendGuard,
+ topicDetailSendGuard,
+ businessAnalyticsHooks,
+ chatFollowUpHooks,
+ ),
+ [slugRouteSendGuard, topicDetailSendGuard, businessAnalyticsHooks, chatFollowUpHooks],
);
return (