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(agent-signal): isolate memory-agent messages into a child thread (#14921)

Arvin Xu652005ed21ef
diff --git a/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts b/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts
index 8aa23ca6b1e..e7b7995fac9 100644
--- a/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts
+++ b/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts
@@ -11,10 +11,11 @@ import {
createAgentSignalMemoryWriterPrompt,
createAgentSignalMemoryWriterSystemRole,
} from '@lobechat/prompts';
-import { LayersEnum, RequestTrigger } from '@lobechat/types';
+import { LayersEnum, RequestTrigger, ThreadType } from '@lobechat/types';
import { nanoid } from '@lobechat/utils';
import { PluginModel } from '@/database/models/plugin';
+import { ThreadModel } from '@/database/models/thread';
import type { LobeChatDatabase } from '@/database/type';
import {
InMemoryAgentStateManager,
@@ -98,6 +99,7 @@ export interface UserMemoryActionHandlerOptions {
reason?: string;
serializedContext?: string;
sourceHints?: AgentSignalFeedbackSourceHints;
+ sourceMessageId?: string;
topicId?: string;
}) => Promise<MemoryAgentActionResult>;
pluginModel?: Pick<PluginModel, 'query'>;
@@ -378,6 +380,13 @@ export const runMemoryActionAgent = async (
reason?: string;
serializedContext?: string;
sourceHints?: AgentSignalFeedbackSourceHints;
+ /**
+ * The assistant message id that triggered this memory action.
+ * When provided together with topicId, a child thread is created
+ * under this message so that memory-agent messages are isolated
+ * from the main topic conversation.
+ */
+ sourceMessageId?: string;
topicId?: string;
},
options: UserMemoryActionHandlerOptions,
@@ -458,11 +467,34 @@ export const runMemoryActionAgent = async (
streamEventManager,
});
+ // Create a child thread under the triggering assistant message so that
+ // memory-agent messages are isolated from the main topic conversation
+ // instead of being flattened into it.
+ let threadId: string | undefined;
+ if (input.topicId && input.sourceMessageId) {
+ try {
+ const threadModel = new ThreadModel(options.db, options.userId);
+ const thread = await threadModel.create({
+ agentId: input.agentId,
+ metadata: { operationId },
+ sourceMessageId: input.sourceMessageId,
+ title: 'Agent Signal Memory',
+ topicId: input.topicId,
+ type: ThreadType.Isolation,
+ });
+ threadId = thread?.id;
+ } catch {
+ // Non-fatal: fall back to writing into the main topic if thread creation fails.
+ }
+ }
+
await runtimeService.createOperation({
agentConfig: memoryRuntimeAgentConfig,
appContext: {
agentId: input.agentId,
scope: 'chat',
+ sourceMessageId: input.sourceMessageId,
+ threadId: threadId ?? null,
topicId: input.topicId ?? null,
trigger: RequestTrigger.AgentSignal,
},
@@ -589,6 +621,14 @@ export const handleUserMemoryAction = async (
typeof action.payload.sourceHints === 'object' && action.payload.sourceHints
? action.payload.sourceHints
: undefined,
+ // The assistant message that completed the turn — used to anchor the
+ // memory-agent child thread under that message instead of the main topic.
+ // Populated by planUserMemory via extractAssistantMessageIdFromSourceId;
+ // absent for non-clientRuntimeComplete sources where no assistant boundary exists.
+ sourceMessageId:
+ typeof action.payload.assistantMessageId === 'string'
+ ? action.payload.assistantMessageId
+ : undefined,
topicId: typeof action.payload.topicId === 'string' ? action.payload.topicId : undefined,
};
const runner = options.memoryActionRunner ?? ((input) => runMemoryActionAgent(input, options));
diff --git a/src/server/services/agentSignal/processors/actions.ts b/src/server/services/agentSignal/processors/actions.ts
index 07b2dbd32b9..783e2065da1 100644
--- a/src/server/services/agentSignal/processors/actions.ts
+++ b/src/server/services/agentSignal/processors/actions.ts
@@ -14,6 +14,25 @@ interface SourcePayloadCarrier {
payload?: SerializedContextPayload;
}
+/**
+ * Extracts the assistant message id embedded in a hydrated `clientRuntimeComplete` source id.
+ *
+ * Hydration produces source ids with the format:
+ * `${assistantMessageId}:completion:${parentMessageId}`
+ *
+ * For all other source types the source id does not follow this pattern, so undefined is returned.
+ */
+const extractAssistantMessageIdFromSourceId = (
+ sourceId: string | undefined,
+): string | undefined => {
+ if (!sourceId) return undefined;
+ const completionMarker = ':completion:';
+ const idx = sourceId.indexOf(completionMarker);
+ if (idx === -1) return undefined;
+ const candidate = sourceId.slice(0, idx);
+ return candidate.length > 0 ? candidate : undefined;
+};
+
/**
* Skill-domain feedback signal that is eligible for direct skill-management action planning.
*/
@@ -64,6 +83,10 @@ export const planUserMemory = (signal: SignalFeedbackDomainMemory): ActionUserMe
},
payload: {
agentId: payload.agentId,
+ // Propagate the assistant message id so that the memory-agent thread
+ // can be anchored under the assistant message that completed the turn,
+ // rather than under the user message (messageId).
+ assistantMessageId: extractAssistantMessageIdFromSourceId(signal.source?.sourceId),
conflictPolicy: payload.conflictPolicy,
evidence: payload.evidence,
feedbackHint: payload.satisfactionResult === 'satisfied' ? 'satisfied' : 'not_satisfied',