🤯 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(conversation-flow): keep background threads out of the main transcript (#19011)
Arvin Xu1cb485fa4c48
diff --git a/apps/cli/src/runtime/LocalMessageStore.ts b/apps/cli/src/runtime/LocalMessageStore.tsindex aac31dd67a8..49c61d30c0f 100644--- a/apps/cli/src/runtime/LocalMessageStore.ts+++ b/apps/cli/src/runtime/LocalMessageStore.ts@@ -234,7 +234,7 @@ export class LocalMessageStore {if (!options.flatten) return matches;- const { flatList } = parse(matches as never);+ const { flatList } = parse(matches as never, undefined, { threadId });return flatList as unknown as UIChatMessage[];}diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.tsindex 7fd888d493c..40108cfe6db 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts@@ -131,7 +131,7 @@ export class ServerMessageTransport implements MessageTransport {if (!options?.flatten) return messages;- const { flatList } = parse(messages);+ const { flatList } = parse(messages, undefined, { threadId: params?.threadId });return flatList;}diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.tsindex bf544432f28..f5cc27537c3 100644--- a/apps/server/src/routers/lambda/aiAgent.ts+++ b/apps/server/src/routers/lambda/aiAgent.ts@@ -3027,7 +3027,7 @@ export const aiAgentRouter = router({);// 6.1 Parse messages using conversation-flow for UI display- const { flatList: parsedMessages } = parse(threadMessages);+ const { flatList: parsedMessages } = parse(threadMessages, undefined, { threadId });// 7. Get result content when task is completed or failedlet resultContent: string | undefined;diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.tsindex 794b3f6f7ca..6c47dd52361 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts@@ -4114,7 +4114,7 @@ export class AgentRuntimeService {private async refreshMessagesFromDB(state: AgentState): Promise<AgentState['messages']> {const dbMessages = await this.queryMessagesFromDB(state);- const { flatList } = parse(dbMessages);+ const { flatList } = parse(dbMessages, undefined, { threadId: state.origin?.threadId });return flatList as AgentState['messages'];}@@ -4126,7 +4126,7 @@ export class AgentRuntimeService {*/private async resolveLastAssistantMessageFromDB(state: AgentState): Promise<unknown> {const dbMessages = await this.queryMessagesFromDB(state);- const { flatList } = parse(dbMessages);+ const { flatList } = parse(dbMessages, undefined, { threadId: state.origin?.threadId });const lastAssistant = findLastAssistantMessage(normalizeCompletionMessages(flatList));const lastAssistantId = typeof lastAssistant?.id === 'string' ? lastAssistant.id : undefined;@@ -4234,7 +4234,7 @@ export class AgentRuntimeService {fileService!.getFullFileUrl(file.url),): messages;- const { flatList } = parse(resolved);+ const { flatList } = parse(resolved, undefined, { threadId: state.origin?.threadId });if (flatList.length > 0) state.messages = flatList as AgentState['messages'];} catch (error) {console.error('[queryStepEntryMessages] Failed to hydrate runtime messages: %O', error);diff --git a/packages/conversation-flow/src/__tests__/parse.test.ts b/packages/conversation-flow/src/__tests__/parse.test.tsindex ddb94fc20b5..3bc73e3ec5a 100644--- a/packages/conversation-flow/src/__tests__/parse.test.ts+++ b/packages/conversation-flow/src/__tests__/parse.test.ts@@ -1712,4 +1712,43 @@ describe('parse', () => {});});});++ describe('thread scope', () => {+ const base = { createdAt: 1, role: 'assistant', updatedAt: 1 } as const;+ // Shape of `MessageModel.query({ threadId })`: the unthreaded ancestors the thread hangs+ // off, followed by the thread's own replies.+ const threadQuery: Message[] = [+ { ...base, content: 'Question', id: 'user-1', role: 'user' },+ { ...base, content: 'Answer', createdAt: 2, id: 'asst-1', parentId: 'user-1' },+ {+ ...base,+ content: 'Thread question',+ createdAt: 3,+ id: 'thr-1',+ parentId: 'asst-1',+ role: 'user',+ threadId: 'thd-1',+ },+ {+ ...base,+ content: 'Thread answer',+ createdAt: 4,+ id: 'thr-2',+ parentId: 'thr-1',+ threadId: 'thd-1',+ },+ ];++ it('should keep thread replies when parsing a thread view', () => {+ const { flatList } = parse(threadQuery, undefined, { threadId: 'thd-1' });++ expect(flatList.map((m) => m.id)).toEqual(['user-1', 'asst-1', 'thr-1', 'thr-2']);+ });++ it('should leave threads out of the main flow by default', () => {+ const { flatList } = parse(threadQuery);++ expect(flatList.map((m) => m.id)).toEqual(['user-1', 'asst-1']);+ });+ });});diff --git a/packages/conversation-flow/src/index.ts b/packages/conversation-flow/src/index.tsindex d7ae4e298b1..e2948d25176 100644--- a/packages/conversation-flow/src/index.ts+++ b/packages/conversation-flow/src/index.ts@@ -37,4 +37,12 @@ export type {export type { FlatMessage, FlatMessageExtra, FlatMessageRole } from './types';// Shared Types-export type { HelperMaps, IdNode, Message, MessageGroupMetadata, ParseResult } from './types';+export type {+ HelperMaps,+ IdNode,+ Message,+ MessageGroupMetadata,+ ParseOptions,+ ParseResult,+ ThreadScope,+} from './types';diff --git a/packages/conversation-flow/src/indexing.ts b/packages/conversation-flow/src/indexing.tsindex b9752184cf1..1f948368840 100644--- a/packages/conversation-flow/src/indexing.ts+++ b/packages/conversation-flow/src/indexing.ts@@ -1,4 +1,4 @@-import type { HelperMaps, Message, MessageGroupMetadata } from './types';+import type { HelperMaps, Message, MessageGroupMetadata, ThreadScope } from './types';interface CompressedDisplayNode {children?: CompressedDisplayNode[];@@ -31,6 +31,24 @@ const getLastMessageIdFromCompressedDisplay = (return message.id;};+/**+ * Resolve the flat-list thread scope. An explicit `threadId` (including `null`) wins; without+ * one, mixed input is scoped to the main flow and thread-only input keeps every message.+ */+export const resolveThreadScope = (messages: Message[], threadId?: string | null): ThreadScope => {+ if (threadId !== undefined) return threadId || null;++ return messages.some((message) => !message.threadId) ? null : undefined;+};++/** Whether `message` belongs to the flat list under `scope`. */+export const isInThreadScope = (message: Message | undefined, scope: ThreadScope): boolean => {+ if (!message) return false;+ if (scope === undefined || !message.threadId) return true;++ return message.threadId === scope;+};+/*** Phase 1: Indexing* Builds helper maps for efficient querying during parsing@@ -42,6 +60,7 @@ const getLastMessageIdFromCompressedDisplay = (export function buildHelperMaps(messages: Message[],messageGroups?: MessageGroupMetadata[],+ threadId?: string | null,): HelperMaps {const messageMap = new Map<string, Message>();const childrenMap = new Map<string | null, string[]>();@@ -115,5 +134,6 @@ export function buildHelperMaps(messageGroupMap,messageMap,threadMap,+ threadScope: resolveThreadScope(messages, threadId),};}diff --git a/packages/conversation-flow/src/parse.ts b/packages/conversation-flow/src/parse.tsindex 8af1c00f8d2..70cf575553a 100644--- a/packages/conversation-flow/src/parse.ts+++ b/packages/conversation-flow/src/parse.ts@@ -1,7 +1,7 @@import { buildHelperMaps } from './indexing';import { buildIdTree } from './structuring';import { Transformer } from './transformation';-import type { Message, MessageGroupMetadata, ParseResult } from './types';+import type { Message, MessageGroupMetadata, ParseOptions, ParseResult } from './types';/*** Main parse function - the brain of the conversation flow engine@@ -18,9 +18,14 @@ import type { Message, MessageGroupMetadata, ParseResult } from './types';** @param messages - Flat array of messages from backend* @param messageGroups - Optional array of message group metadata for compare/manual grouping+ * @param options - `threadId` scopes the flat list to the main flow (`null`) or to one thread* @returns ParseResult containing messageMap, displayTree, and flatList*/-export function parse(messages: Message[], messageGroups?: MessageGroupMetadata[]): ParseResult {+export function parse(+ messages: Message[],+ messageGroups?: MessageGroupMetadata[],+ options?: ParseOptions,+): ParseResult {// Pre-processing: Transform sub_agent messages before building helper maps// This ensures FlatListBuilder and MessageCollector see the correct agentId// and won't merge messages from different agents into the same group@@ -34,7 +39,7 @@ export function parse(messages: Message[], messageGroups?: MessageGroupMetadata[// Phase 1: Indexing// Build helper maps for O(1) access patterns- const helperMaps = buildHelperMaps(processedMessages, messageGroups);+ const helperMaps = buildHelperMaps(processedMessages, messageGroups, options?.threadId);// Phase 2: Structuring// Convert flat parent-child relationships to tree structurediff --git a/packages/conversation-flow/src/transformation/FlatListBuilder.ts b/packages/conversation-flow/src/transformation/FlatListBuilder.tsindex 6ddd074c499..35269c4bdeb 100644--- a/packages/conversation-flow/src/transformation/FlatListBuilder.ts+++ b/packages/conversation-flow/src/transformation/FlatListBuilder.ts@@ -1,6 +1,7 @@import type { AssistantContentBlock, ChatToolPayloadWithResult } from '@lobechat/types';-import type { Message, MessageGroupMetadata } from '../types';+import { isInThreadScope } from '../indexing';+import type { Message, MessageGroupMetadata, ThreadScope } from '../types';import type { BranchResolver } from './BranchResolver';import type { MessageCollector } from './MessageCollector';import type { MessageTransformer } from './MessageTransformer';@@ -30,8 +31,29 @@ export class FlatListBuilder {private branchResolver: BranchResolver,private messageCollector: MessageCollector,private messageTransformer: MessageTransformer,+ /** See `ThreadScope`. Defaults to every message in scope. */+ private threadScope: ThreadScope = undefined,) {}+ /**+ * Children of `parentId` that belong to the flat list's thread scope.+ *+ * Threaded messages live outside the main chain, and `buildIdTree` already drops them from+ * the context tree. The flat list has to apply the same rule: a thread head is parented to+ * nothing (`parentId: null`) or to the main-chain assistant/tool that spawned it, so an+ * unfiltered walk reaches it and renders a background run — an isolated memory or sub-agent+ * turn — as an ordinary bubble in the middle of the user's transcript. A thread view keeps+ * its own thread in scope, since its input is the ancestors plus that thread's replies.+ */+ private childIdsInScope(parentId: string | null): string[] {+ const childIds = this.childrenMap.get(parentId) ?? [];+ if (this.threadScope === undefined) return childIds;++ return childIds.filter((childId) =>+ isInThreadScope(this.messageMap.get(childId), this.threadScope),+ );+ }+/*** Generate flatList from messages array* Only includes messages in the active path@@ -40,20 +62,25 @@ export class FlatListBuilder {const flatList: Message[] = [];const processedIds = new Set<string>();+ const scopedMessages =+ this.threadScope === undefined+ ? messages+ : messages.filter((message) => isInThreadScope(message, this.threadScope));+// Determine the root parentId// Normal case: start from null (messages with no parentId)// Orphan case: if all messages have parentId (thread mode), use first message as rootlet rootParentId: string | null = null;- const hasRootMessages = this.childrenMap.has(null) && this.childrenMap.get(null)!.length > 0;- if (!hasRootMessages && messages.length > 0) {+ const hasRootMessages = this.childIdsInScope(null).length > 0;+ if (!hasRootMessages && scopedMessages.length > 0) {// All messages have parentId - this is orphan/thread mode// Use the first message's parentId as the virtual root- rootParentId = messages[0].parentId ?? null;+ rootParentId = scopedMessages[0].parentId ?? null;}// Build the active path by traversing from root- this.buildFlatListRecursive(rootParentId, flatList, processedIds, messages);+ this.buildFlatListRecursive(rootParentId, flatList, processedIds, scopedMessages);// Assistant groups must be assembled before ordering because their members// are discovered through recursive tool-result chains. That traversal is@@ -76,7 +103,7 @@ export class FlatListBuilder {processedIds: Set<string>,allMessages: Message[],): void {- const children = this.childrenMap.get(parentId) ?? [];+ const children = this.childIdsInScope(parentId);// Broadcast councils now render in-bubble (a `council` block inside the// supervisor's assistant group), so there is no separate agentCouncil message@@ -319,7 +346,7 @@ export class FlatListBuilder {}// Priority 3a: Compare mode from user message metadata- const childMessages = this.childrenMap.get(message.id) ?? [];+ const childMessages = this.childIdsInScope(message.id);// Non-tool children only are branch candidates (dual-form reader invariant: tool children are inline, not branches):// a tool child is inline data of its assistant, never a sibling branch.const nonToolChildMessages = this.branchResolver.getMetadataBranchIds(childMessages);@@ -744,7 +771,7 @@ export class FlatListBuilder {): { child: Message; parentId: string } | undefined {return parentIds.flatMap((parentId) =>- (this.childrenMap.get(parentId) ?? [])+ this.childIdsInScope(parentId).map((childId) => this.messageMap.get(childId)).filter((child): child is Message => !!child && !processedIds.has(child.id)).map((child) => ({ child, parentId })),@@ -754,9 +781,7 @@ export class FlatListBuilder {private shouldDrainParentContinuations(parentId: string, processedIds: Set<string>): boolean {const parentMessage = this.messageMap.get(parentId);- const children = (this.childrenMap.get(parentId) ?? []).filter(- (childId) => !processedIds.has(childId),- );+ const children = this.childIdsInScope(parentId).filter((childId) => !processedIds.has(childId));if (!parentMessage || children.length <= 1) return false;if (this.isAgentCouncilMode(parentMessage)) return true;diff --git a/packages/conversation-flow/src/transformation/MessageCollector.ts b/packages/conversation-flow/src/transformation/MessageCollector.tsindex 550c935dc26..9c0171034bc 100644--- a/packages/conversation-flow/src/transformation/MessageCollector.ts+++ b/packages/conversation-flow/src/transformation/MessageCollector.ts@@ -1,4 +1,12 @@-import type { ContextNode, IdNode, Message, MessageNode, SignalCallbacksNode } from '../types';+import { isInThreadScope } from '../indexing';+import type {+ ContextNode,+ IdNode,+ Message,+ MessageNode,+ SignalCallbacksNode,+ ThreadScope,+} from '../types';import { BranchResolver } from './BranchResolver';/**@@ -57,8 +65,25 @@ export class MessageCollector {private messageMap: Map<string, Message>,private childrenMap: Map<string | null, string[]>,private branchResolver: BranchResolver = new BranchResolver(messageMap),+ /** See `ThreadScope`. Defaults to every message in scope. */+ private threadScope: ThreadScope = undefined,) {}+ /**+ * Every message the current scope may walk.+ *+ * Chain classification has to see exactly what chain collection will be given: if a+ * threaded reply counts as the continuation that makes an assistant a tool-chain head,+ * but collection then cannot reach it, the assistant renders as an empty one-message+ * group instead of its own bubble.+ */+ private scopedMessages(): Message[] {+ const messages = [...this.messageMap.values()];+ if (this.threadScope === undefined) return messages;++ return messages.filter((message) => isInThreadScope(message, this.threadScope));+ }+/*** Collect all messages belonging to a message group*/@@ -135,7 +160,7 @@ export class MessageCollector {if (parent?.role !== 'user') return false;const groupAgentId = assistant.agentId;- const allMessages = [...this.messageMap.values()];+ const allMessages = this.scopedMessages();const visited = new Set<string>([assistant.id]);let current: Message = assistant;diff --git a/packages/conversation-flow/src/transformation/__tests__/FlatListBuilder.test.ts b/packages/conversation-flow/src/transformation/__tests__/FlatListBuilder.test.tsindex da1c87e2347..c3e03704fcf 100644--- a/packages/conversation-flow/src/transformation/__tests__/FlatListBuilder.test.ts+++ b/packages/conversation-flow/src/transformation/__tests__/FlatListBuilder.test.ts@@ -1,5 +1,6 @@import { describe, expect, it } from 'vitest';+import { resolveThreadScope } from '../../indexing';import type { Message, MessageGroupMetadata } from '../../types';import { BranchResolver } from '../BranchResolver';import { FlatListBuilder } from '../FlatListBuilder';@@ -10,6 +11,7 @@ describe('FlatListBuilder', () => {const createBuilder = (messages: Message[],messageGroupMap: Map<string, MessageGroupMetadata> = new Map(),+ threadId?: string | null,) => {const messageMap = new Map<string, Message>();const childrenMap = new Map<string | null, string[]>();@@ -24,8 +26,16 @@ describe('FlatListBuilder', () => {childrenMap.get(parentId)!.push(msg.id);});+ // Mirrors `buildHelperMaps`, so the builder is scoped the way production scopes it.+ const threadScope = resolveThreadScope(messages, threadId);+const branchResolver = new BranchResolver();- const messageCollector = new MessageCollector(messageMap, childrenMap);+ const messageCollector = new MessageCollector(+ messageMap,+ childrenMap,+ branchResolver,+ threadScope,+ );const messageTransformer = new MessageTransformer();return new FlatListBuilder(@@ -35,6 +45,7 @@ describe('FlatListBuilder', () => {branchResolver,messageCollector,messageTransformer,+ threadScope,);};@@ -1180,4 +1191,157 @@ describe('FlatListBuilder', () => {expect(block.callbacks[0].content).toBe('等 list 完。');});});++ describe('threads', () => {+ const base = { createdAt: 1, role: 'assistant', updatedAt: 1 } as const;++ // A background run (memory signal, sub-agent) lives in its own thread. Whether its head+ // hangs off nothing or off the main-chain step that spawned it, the transcript must not+ // walk into it — otherwise the run renders as a stray bubble mid-conversation.+ const mainChain: Message[] = [+ { ...base, content: 'Question', id: 'user-1', role: 'user' },+ { ...base, content: 'Answer', createdAt: 2, id: 'asst-1', parentId: 'user-1' },+ ];++ it('should exclude a thread whose head is a root', () => {+ const messages: Message[] = [+ ...mainChain,+ { ...base, content: 'Background run', createdAt: 3, id: 'thr-1', threadId: 'thd-1' },+ ];++ expect(+ createBuilder(messages)+ .flatten(messages)+ .map((m) => m.id),+ ).toEqual(['user-1', 'asst-1']);+ });++ it('should exclude a thread whose head hangs off the main chain', () => {+ const messages: Message[] = [+ ...mainChain,+ {+ ...base,+ content: 'Background run',+ createdAt: 3,+ id: 'thr-1',+ parentId: 'asst-1',+ threadId: 'thd-1',+ },+ ];++ expect(+ createBuilder(messages)+ .flatten(messages)+ .map((m) => m.id),+ ).toEqual(['user-1', 'asst-1']);+ });++ it('should not classify an assistant as a tool-chain head via a threaded reply', () => {+ // The only continuation carrying tools is threaded, so it is out of scope. Classifying+ // on it would open an AssistantGroup that collection cannot fill, replacing the+ // assistant's own bubble with an empty group.+ const messages: Message[] = [+ { ...base, content: 'Question', id: 'user-1', role: 'user' },+ {+ ...base,+ agentId: 'a1',+ content: 'Answer',+ createdAt: 2,+ id: 'asst-1',+ parentId: 'user-1',+ },+ {+ ...base,+ agentId: 'a1',+ content: 'Background run',+ createdAt: 3,+ id: 'thr-1',+ parentId: 'asst-1',+ threadId: 'thd-1',+ tools: [+ {+ apiName: 'search',+ arguments: '{}',+ id: 'call-1',+ identifier: 'search',+ type: 'default',+ },+ ],+ },+ ];++ const result = createBuilder(messages).flatten(messages);++ expect(result.map((m) => m.id)).toEqual(['user-1', 'asst-1']);+ expect(result[1].role).toBe('assistant');+ });++ // The thread view's query returns the unthreaded ancestors together with the thread's+ // replies, so the input mixes both. Scoped to that thread, the replies must survive while+ // other threads stay out.+ const threadQuery: Message[] = [+ ...mainChain,+ {+ ...base,+ content: 'Reply',+ createdAt: 3,+ id: 'thr-1',+ parentId: 'asst-1',+ threadId: 'thd-1',+ },+ {+ ...base,+ content: 'Follow-up',+ createdAt: 4,+ id: 'thr-2',+ parentId: 'thr-1',+ role: 'user',+ threadId: 'thd-1',+ },+ {+ ...base,+ content: 'Other thread',+ createdAt: 5,+ id: 'other-1',+ parentId: 'asst-1',+ threadId: 'thd-2',+ },+ ];++ it('should keep the replies of the requested thread alongside its ancestors', () => {+ expect(+ createBuilder(threadQuery, new Map(), 'thd-1')+ .flatten(threadQuery)+ .map((m) => m.id),+ ).toEqual(['user-1', 'asst-1', 'thr-1', 'thr-2']);+ });++ it('should drop every thread when scoped to the main flow', () => {+ expect(+ createBuilder(threadQuery, new Map(), null)+ .flatten(threadQuery)+ .map((m) => m.id),+ ).toEqual(['user-1', 'asst-1']);+ });++ it('should still render a thread when it is all the caller passed', () => {+ const messages: Message[] = [+ { ...base, content: 'Background run', id: 'thr-1', threadId: 'thd-1' },+ {+ ...base,+ content: 'More',+ createdAt: 2,+ id: 'thr-2',+ parentId: 'thr-1',+ threadId: 'thd-1',+ },+ ];++ expect(+ createBuilder(messages)+ .flatten(messages)+ .map((m) => m.id),+ ).toEqual(['thr-1', 'thr-2']);+ });+ });});diff --git a/packages/conversation-flow/src/transformation/index.ts b/packages/conversation-flow/src/transformation/index.tsindex 26aede9e1a7..9df33a4646a 100644--- a/packages/conversation-flow/src/transformation/index.ts+++ b/packages/conversation-flow/src/transformation/index.ts@@ -35,6 +35,7 @@ export class Transformer {this.messageMap,helperMaps.childrenMap,this.branchResolver,+ helperMaps.threadScope,);this.messageTransformer = new MessageTransformer();@@ -54,6 +55,7 @@ export class Transformer {this.branchResolver,this.messageCollector,this.messageTransformer,+ helperMaps.threadScope,);}diff --git a/packages/conversation-flow/src/types/index.ts b/packages/conversation-flow/src/types/index.tsindex 976ee3c6f64..6b48e22dd2f 100644--- a/packages/conversation-flow/src/types/index.ts+++ b/packages/conversation-flow/src/types/index.ts@@ -29,4 +29,12 @@ export type {export type { FlatMessage, FlatMessageExtra, FlatMessageRole } from './flatMessageList';// Shared Types-export type { HelperMaps, IdNode, Message, MessageGroupMetadata, ParseResult } from './shared';+export type {+ HelperMaps,+ IdNode,+ Message,+ MessageGroupMetadata,+ ParseOptions,+ ParseResult,+ ThreadScope,+} from './shared';diff --git a/packages/conversation-flow/src/types/shared.ts b/packages/conversation-flow/src/types/shared.tsindex 96845a5cbc5..dafcf129e99 100644--- a/packages/conversation-flow/src/types/shared.ts+++ b/packages/conversation-flow/src/types/shared.ts@@ -48,6 +48,27 @@ export interface ParseResult {messageMap: Record<string, Message>;}+/**+ * Which threaded messages belong to the rendered flat list.+ *+ * - `undefined`: every message is in scope. Used when the input holds only threaded rows (a+ * thread passed on its own), where there is no main flow to separate.+ * - `null`: the main flow only. Threaded rows are side conversations (background runs,+ * sub-agent turns) and must not be walked into the transcript.+ * - a thread id: the main flow plus that thread. This is the thread view, whose query+ * intentionally returns the unthreaded ancestors together with the thread's replies.+ */+export type ThreadScope = string | null | undefined;++export interface ParseOptions {+ /**+ * The thread the caller is rendering, or `null` for the main flow. Omit it to derive the+ * scope from the input: mixed input is treated as the main flow, thread-only input as the+ * thread itself. Thread views must pass it, because their input mixes ancestors and replies.+ */+ threadId?: string | null;+}+/*** Internal helper maps used during parsing*/@@ -60,4 +81,6 @@ export interface HelperMaps {messageMap: Map<string, Message>;/** Maps thread ID to all messages in that thread */threadMap: Map<string, Message[]>;+ /** Which threaded messages the flat list may walk. See `ThreadScope`. */+ threadScope: ThreadScope;}diff --git a/src/features/Conversation/store/action.ts b/src/features/Conversation/store/action.tsindex ebe8bab3b91..1ce6a63cbb5 100644--- a/src/features/Conversation/store/action.ts+++ b/src/features/Conversation/store/action.ts@@ -84,7 +84,8 @@ export const createStoreAction: CreateStore =...(initialMessages? {dbMessages: initialMessages,- displayMessages: parse(initialMessages).flatList,+ displayMessages: parse(initialMessages, undefined, { threadId: context.threadId })+ .flatList,messagesInit: true,}: {}),diff --git a/src/features/Conversation/store/slices/data/action.ts b/src/features/Conversation/store/slices/data/action.tsindex 23594fac8df..58e1539bed5 100644--- a/src/features/Conversation/store/slices/data/action.ts+++ b/src/features/Conversation/store/slices/data/action.ts@@ -181,7 +181,7 @@ export const dataSlice: StateCreator<}// Re-parse for display order and grouping- const { flatList } = parse(newDbMessages);+ const { flatList } = parse(newDbMessages, undefined, { threadId: get().context.threadId });// parse() rebuilds every message/block/tool reference, so pin unchanged// subtrees back to their previous identity to preserve memo bailouts.const stableFlatList = stabilizeReferences(get().displayMessages, flatList);@@ -281,7 +281,7 @@ export const dataSlice: StateCreator<const prevDbMessages = get().dbMessages;// Parse messages using conversation-flow- const { flatList } = parse(messages);+ const { flatList } = parse(messages, undefined, { threadId: get().context.threadId });const stableFlatList = stabilizeReferences(get().displayMessages, flatList);log(@@ -402,7 +402,7 @@ export const dataSlice: StateCreator<);// Parse messages using conversation-flow- const { flatList } = parse(mergedMessages);+ const { flatList } = parse(mergedMessages, undefined, { threadId: context.threadId });const stableFlatList = stabilizeReferences(get().displayMessages, flatList);log(diff --git a/src/store/chat/slices/message/actions/internals.ts b/src/store/chat/slices/message/actions/internals.tsindex b11d28bf779..2a0b9463c6c 100644--- a/src/store/chat/slices/message/actions/internals.ts+++ b/src/store/chat/slices/message/actions/internals.ts@@ -69,7 +69,8 @@ export class MessageInternalsActionImpl {if (isEqual(nextDbMap, this.#get().dbMessagesMap)) return;// parse to get display messages- const { flatList } = parse(reconciled);+ // The key's thread decides which threaded rows render (see conversation-flow `ThreadScope`).+ const { flatList } = parse(reconciled, undefined, { threadId: ctx.threadId });const nextDisplayMap = { ...this.#get().messagesMap, [messagesKey]: flatList };this.#set({ dbMessagesMap: nextDbMap, messagesMap: nextDisplayMap }, false, {diff --git a/src/store/chat/slices/message/actions/query.ts b/src/store/chat/slices/message/actions/query.tsindex 63204a9f011..e35a2cc362e 100644--- a/src/store/chat/slices/message/actions/query.ts+++ b/src/store/chat/slices/message/actions/query.ts@@ -254,7 +254,9 @@ export class MessageQueryActionImpl {if (isEqual(nextDbMap, this.#get().dbMessagesMap)) return;// Parse messages using conversation-flow- const { flatList } = parse(reconciled);+ // A thread view's rows are its ancestors plus its replies; scope the parse to that thread+ // so the replies are not dropped as a side conversation.+ const { flatList } = parse(reconciled, undefined, { threadId: ctx.threadId });this.#set({diff --git a/src/store/chat/slices/message/replaceMessages.threadScope.regression.test.ts b/src/store/chat/slices/message/replaceMessages.threadScope.regression.test.tsnew file mode 100644index 00000000000..be0fdf3c0c0--- /dev/null+++ b/src/store/chat/slices/message/replaceMessages.threadScope.regression.test.ts@@ -0,0 +1,78 @@+import { type UIChatMessage } from '@lobechat/types';+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { messageMapKey } from '@/store/chat/utils/messageMapKey';++import { useChatStore } from '../../store';++vi.mock('@/libs/swr', async () => {+ const actual = await vi.importActual('@/libs/swr');+ return { ...actual, mutate: vi.fn() };+});+vi.stubGlobal(+ 'fetch',+ vi.fn(() => Promise.resolve(new Response('mock'))),+);+vi.mock('@/services/message', () => ({+ messageService: {+ createMessage: vi.fn(),+ getMessages: vi.fn(),+ updateMessage: vi.fn(),+ updateMessageError: vi.fn(),+ },+}));+vi.mock('@/services/topic', () => ({ topicService: {} }));++const THREAD_CTX = { agentId: 'agent-1', threadId: 'thread-1', topicId: 'topic-1' };++/**+ * Shape of `MessageModel.query({ threadId })`: the unthreaded ancestors the thread hangs off,+ * followed by the thread's own replies.+ */+const threadQuery = [+ { content: 'Question', createdAt: 1, id: 'user-1', role: 'user', updatedAt: 1 },+ {+ content: 'Answer',+ createdAt: 2,+ id: 'asst-1',+ parentId: 'user-1',+ role: 'assistant',+ updatedAt: 2,+ },+ {+ content: 'Thread question',+ createdAt: 3,+ id: 'thr-1',+ parentId: 'asst-1',+ role: 'user',+ threadId: 'thread-1',+ updatedAt: 3,+ },+ {+ content: 'Thread answer',+ createdAt: 4,+ id: 'thr-2',+ parentId: 'thr-1',+ role: 'assistant',+ threadId: 'thread-1',+ updatedAt: 4,+ },+] as UIChatMessage[];++describe('replaceMessages — thread-scoped parse', () => {+ beforeEach(() => {+ useChatStore.setState({ dbMessagesMap: {}, messagesMap: {} });+ });++ it('keeps the thread replies next to their ancestors in the thread view', () => {+ const { result } = renderHook(() => useChatStore());++ act(() => {+ result.current.replaceMessages(threadQuery, { context: THREAD_CTX });+ });++ const display = result.current.messagesMap[messageMapKey(THREAD_CTX)] ?? [];+ expect(display.map((m) => m.id)).toEqual(['user-1', 'asst-1', 'thr-1', 'thr-2']);+ });+});diff --git a/src/store/chat/slices/thread/selectors/index.test.ts b/src/store/chat/slices/thread/selectors/index.test.tsindex 9c14976edcd..dda569aeb8e 100644--- a/src/store/chat/slices/thread/selectors/index.test.ts+++ b/src/store/chat/slices/thread/selectors/index.test.ts@@ -2,6 +2,7 @@ import { ThreadStatus, ThreadType } from '@lobechat/types';import { describe, expect, it } from 'vitest';import type { ChatStoreState } from '@/store/chat';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { threadSelectors } from '.';@@ -116,4 +117,27 @@ describe('threadSelectors', () => {expect(threadSelectors.isActiveThreadSubagent(state)).toBe(true);});+ it('reads thread replies from the raw rows, not the rendered transcript', () => {+ const mainKey = messageMapKey({ agentId: 'agent-1', topicId: 'topic-1' });+ const state = {+ activeAgentId: 'agent-1',+ activeTopicId: 'topic-1',+ // The rendered transcript deliberately leaves threads out, so the replies only exist+ // in the raw rows. Reading `messagesMap` here would return nothing.+ dbMessagesMap: {+ [mainKey]: [+ { content: 'Question', id: 'message-1' },+ { content: 'Reply', id: 'message-2', threadId: 'thread-1' },+ { content: 'Other thread', id: 'message-3', threadId: 'thread-2' },+ ],+ },+ messagesMap: { [mainKey]: [{ content: 'Question', id: 'message-1' }] },+ } as unknown as ChatStoreState;++ expect(+ threadSelectors+ .getThreadChildMessages('thread-1')(state)+ .map((m) => m.id),+ ).toEqual(['message-2']);+ });});diff --git a/src/store/chat/slices/thread/selectors/index.ts b/src/store/chat/slices/thread/selectors/index.tsindex e27ed930782..dc9a76159b4 100644--- a/src/store/chat/slices/thread/selectors/index.ts+++ b/src/store/chat/slices/thread/selectors/index.ts@@ -85,6 +85,20 @@ const getMainScopeMessages = (s: ChatStoreState): UIChatMessage[] => {return s.messagesMap[mainKey] || [];};+/**+ * Raw main-scope rows, the same key as `getMainScopeMessages` but before conversation-flow+ * grouped them for display.+ */+const getMainScopeDbMessages = (s: ChatStoreState): UIChatMessage[] => {+ if (!s.activeAgentId) return [];+ const mainKey = messageMapKey({+ agentId: s.activeAgentId,+ groupId: s.activeGroupId,+ topicId: s.activeTopicId,+ });+ return (s.dbMessagesMap?.[mainKey] || []) as UIChatMessage[];+};+/*** Internal helper to get parent messages for a thread*/@@ -103,11 +117,15 @@ const getThreadParentMessages = (s: ChatStoreState, data: UIChatMessage[]) => {/*** Get thread child messages by thread ID+ *+ * Reads the raw main-scope rows rather than `messagesMap`: the rendered shape is the main+ * transcript, which deliberately leaves threads out, so a thread's replies only exist here+ * in `dbMessagesMap`.*/const getThreadChildMessages =(id?: string) =>(s: ChatStoreState): UIChatMessage[] => {- const data = getMainScopeMessages(s);+ const data = getMainScopeDbMessages(s);return data.filter((m) => !!id && m.threadId === id);};