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: use main scope messages for subtopic re-fork (#13606)

Arvin Xu18001107482b
diff --git a/src/store/chat/slices/thread/action.test.ts b/src/store/chat/slices/thread/action.test.ts
index a36c9150d47..c80974f1a63 100644
--- a/src/store/chat/slices/thread/action.test.ts
+++ b/src/store/chat/slices/thread/action.test.ts
@@ -159,6 +159,146 @@ describe('thread action', () => {
startMessageId: 'message-id',
});
});
+
+ it('should initialize optimistic parent messages from main scope messages', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ const mainMessages: UIChatMessage[] = [
+ {
+ id: 'msg-1',
+ role: 'user',
+ content: 'first',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ agentId: 'test-session-id',
+ },
+ {
+ id: 'msg-2',
+ role: 'assistant',
+ content: 'reply',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ agentId: 'test-session-id',
+ },
+ {
+ id: 'msg-3',
+ role: 'user',
+ content: 'second',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ agentId: 'test-session-id',
+ },
+ ];
+
+ act(() => {
+ useChatStore.setState({
+ messagesMap: {
+ 'main_test-session-id_test-topic-id': mainMessages,
+ },
+ });
+ });
+
+ const replaceMessagesSpy = vi.spyOn(result.current, 'replaceMessages');
+
+ act(() => {
+ result.current.openThreadCreator('msg-3');
+ });
+
+ // Should call replaceMessages with all 3 parent messages (continuation mode)
+ expect(replaceMessagesSpy).toHaveBeenCalledWith(
+ mainMessages,
+ expect.objectContaining({ action: 'initThreadMessages' }),
+ );
+ });
+
+ it('should use main scope messages even when activeThreadId is set (LOBE-5023)', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ const mainMessages: UIChatMessage[] = [
+ {
+ id: 'msg-1',
+ role: 'user',
+ content: 'first',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ agentId: 'test-session-id',
+ },
+ {
+ id: 'msg-2',
+ role: 'assistant',
+ content: 'reply',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ agentId: 'test-session-id',
+ },
+ {
+ id: 'msg-3',
+ role: 'user',
+ content: 'second',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ agentId: 'test-session-id',
+ },
+ ];
+
+ const threadMessages: UIChatMessage[] = [
+ {
+ id: 'msg-1',
+ role: 'user',
+ content: 'first',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ agentId: 'test-session-id',
+ },
+ {
+ id: 'thread-msg-1',
+ role: 'user',
+ content: 'thread msg',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ agentId: 'test-session-id',
+ threadId: 'existing-thread',
+ },
+ {
+ id: 'thread-msg-2',
+ role: 'assistant',
+ content: 'thread reply',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ agentId: 'test-session-id',
+ threadId: 'existing-thread',
+ },
+ ];
+
+ act(() => {
+ useChatStore.setState({
+ activeThreadId: 'existing-thread',
+ messagesMap: {
+ // Main scope has all messages including msg-3
+ 'main_test-session-id_test-topic-id': mainMessages,
+ // Thread scope does NOT have msg-3
+ 'thread_test-session-id_test-topic-id_existing-thread': threadMessages,
+ },
+ });
+ });
+
+ const replaceMessagesSpy = vi.spyOn(result.current, 'replaceMessages');
+
+ act(() => {
+ // Fork from msg-3 which only exists in main scope
+ result.current.openThreadCreator('msg-3');
+ });
+
+ // BUG: if openThreadCreator uses activeDisplayMessages (which includes activeThreadId),
+ // it gets thread-scoped messages that don't contain msg-3,
+ // genParentMessages returns [], and replaceMessages is never called.
+ //
+ // FIX: openThreadCreator should always use main scope key to get messages.
+ expect(replaceMessagesSpy).toHaveBeenCalledWith(
+ mainMessages,
+ expect.objectContaining({ action: 'initThreadMessages' }),
+ );
+ });
});
describe('openThreadInPortal', () => {
diff --git a/src/store/chat/slices/thread/action.ts b/src/store/chat/slices/thread/action.ts
index 13b0412df7c..a2928acb84e 100644
--- a/src/store/chat/slices/thread/action.ts
+++ b/src/store/chat/slices/thread/action.ts
@@ -15,13 +15,13 @@ import { chatService } from '@/services/chat';
import { threadService } from '@/services/thread';
import { threadSelectors } from '@/store/chat/selectors';
import { type ChatStore } from '@/store/chat/store';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { type StoreSetter } from '@/store/types';
import { useUserStore } from '@/store/user';
import { systemAgentSelectors, userGeneralSettingsSelectors } from '@/store/user/selectors';
import { merge } from '@/utils/merge';
import { setNamespace } from '@/utils/storeDebug';
-import { displayMessageSelectors } from '../message/selectors';
import { PortalViewType } from '../portal/initialState';
import { type ThreadDispatch } from './reducer';
import { threadReducer } from './reducer';
@@ -51,10 +51,19 @@ export class ChatThreadActionImpl {
};
openThreadCreator = (messageId: string): void => {
- const { activeAgentId, activeTopicId, newThreadMode, replaceMessages } = this.#get();
-
- // Get parent messages up to and including the source message
- const displayMessages = displayMessageSelectors.activeDisplayMessages(this.#get());
+ const { activeAgentId, activeGroupId, activeTopicId, newThreadMode, replaceMessages } =
+ this.#get();
+
+ // Always use main scope key to get messages, not activeDisplayMessages,
+ // because activeDisplayMessages includes activeThreadId in the key.
+ // When inside a subtopic, that would return thread-scoped messages
+ // instead of main conversation messages, causing the fork to fail (LOBE-5023).
+ const mainKey = messageMapKey({
+ agentId: activeAgentId,
+ groupId: activeGroupId,
+ topicId: activeTopicId,
+ });
+ const displayMessages = this.#get().messagesMap[mainKey] || [];
// Filter out messages that have threadId (they belong to other threads)
const mainMessages = displayMessages.filter((m) => !m.threadId);
const parentMessages = genParentMessages(mainMessages, messageId, newThreadMode);
diff --git a/src/store/chat/slices/thread/selectors/index.ts b/src/store/chat/slices/thread/selectors/index.ts
index ecdbd533de6..a5378d0e494 100644
--- a/src/store/chat/slices/thread/selectors/index.ts
+++ b/src/store/chat/slices/thread/selectors/index.ts
@@ -4,8 +4,8 @@ import { useAgentStore } from '@/store/agent';
import { agentChatConfigSelectors } from '@/store/agent/selectors';
import { type ChatStoreState } from '@/store/chat';
import { chatHelpers } from '@/store/chat/helpers';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
-import { displayMessageSelectors } from '../../message/selectors';
import { genParentMessages } from './util';
// ============= Thread List Selectors ============= //
@@ -46,6 +46,21 @@ const hasThreadBySourceMsgId = (id: string) => (s: ChatStoreState) => {
// These are kept for Token calculation and AI title summarization
// Thread Chat component now uses dbMessagesMap directly
+/**
+ * Get main scope messages (without activeThreadId influence).
+ * Always uses main scope key so that thread selectors work correctly
+ * even when activeThreadId is set (i.e., viewing inside a subtopic).
+ */
+const getMainScopeMessages = (s: ChatStoreState): UIChatMessage[] => {
+ if (!s.activeAgentId) return [];
+ const mainKey = messageMapKey({
+ agentId: s.activeAgentId,
+ groupId: s.activeGroupId,
+ topicId: s.activeTopicId,
+ });
+ return s.messagesMap[mainKey] || [];
+};
+
/**
* Internal helper to get parent messages for a thread
*/
@@ -68,7 +83,7 @@ const getThreadParentMessages = (s: ChatStoreState, data: UIChatMessage[]) => {
const getThreadChildMessages =
(id?: string) =>
(s: ChatStoreState): UIChatMessage[] => {
- const data = displayMessageSelectors.activeDisplayMessages(s);
+ const data = getMainScopeMessages(s);
return data.filter((m) => !!id && m.threadId === id);
};
@@ -76,7 +91,7 @@ const getThreadChildMessages =
* Portal AI chats - used for AI title summarization
*/
const portalAIChats = (s: ChatStoreState) => {
- const data = displayMessageSelectors.activeDisplayMessages(s);
+ const data = getMainScopeMessages(s);
const parentMessages = getThreadParentMessages(s, data);
const childMessages = getThreadChildMessages(s.portalThreadId)(s);