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): attribute self-iteration run trace to reviewed agent & isolate memory runs (#15479)

Arvin Xu5dc769d135b3
diff --git a/src/server/services/agentSignal/policies/analyzeIntent/actions/__tests__/userMemory.test.ts b/src/server/services/agentSignal/policies/analyzeIntent/actions/__tests__/userMemory.test.ts
index 67324c6b861..b68e03beeda 100644
--- a/src/server/services/agentSignal/policies/analyzeIntent/actions/__tests__/userMemory.test.ts
+++ b/src/server/services/agentSignal/policies/analyzeIntent/actions/__tests__/userMemory.test.ts
@@ -74,6 +74,42 @@ describe('defineUserMemoryActionHandler', () => {
expect(context.runtimeState.touchGuardState).toHaveBeenCalledTimes(1);
});
+ it('anchors the memory-agent thread on the user message id when no assistant boundary exists', async () => {
+ // Non-clientRuntimeComplete source: sourceId has no `:completion:` segment,
+ // so assistantMessageId is absent. The run must still anchor a child thread
+ // under the triggering user message instead of leaking into the main topic.
+ memoryActionRunner.mockResolvedValue({ status: 'applied' });
+
+ const handler = defineUserMemoryActionHandler({
+ db: {} as never,
+ memoryActionRunner,
+ userId: 'user_1',
+ });
+
+ await handler.handle(
+ {
+ actionId: 'act_memory_fallback_anchor',
+ actionType: 'action.user-memory.handle',
+ chain: { chainId: 'chain_1', rootSourceId: 'source_1' },
+ payload: {
+ agentId: 'agent_1',
+ idempotencyKey: 'source_1:memory:msg_user_1',
+ message: 'Remember that I prefer concise answers.',
+ messageId: 'msg_user_1',
+ topicId: 'topic_1',
+ },
+ signal: { signalId: 'sig_1', signalType: 'signal.feedback.domain.memory' },
+ source: { sourceId: 'source_1', sourceType: 'agent.user.message' },
+ timestamp: 1,
+ },
+ context,
+ );
+
+ expect(memoryActionRunner).toHaveBeenCalledWith(
+ expect.objectContaining({ sourceMessageId: 'msg_user_1', topicId: 'topic_1' }),
+ );
+ });
+
it('returns the applied memory target from the memory agent runner', async () => {
memoryActionRunner.mockResolvedValue({
detail: 'Arvin Xu 希望助手在输出时每个段落/模块都写得更长、更展开。',
diff --git a/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts b/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts
index 0b117ee2f50..2510238751a 100644
--- a/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts
+++ b/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts
@@ -392,14 +392,21 @@ 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.
+ // The message to anchor the memory-agent child thread under, so its
+ // messages stay isolated from the main topic instead of being flattened
+ // into it. Prefer the assistant message that completed the turn (set by
+ // planUserMemory via extractAssistantMessageIdFromSourceId — only present
+ // for clientRuntimeComplete sources whose id is
+ // `${assistantMessageId}:completion:${parentMessageId}`). Other sources
+ // carry no assistant boundary, so fall back to the triggering user
+ // message id; without this fallback no thread is created and the run
+ // leaks into the active conversation.
sourceMessageId:
typeof action.payload.assistantMessageId === 'string'
? action.payload.assistantMessageId
- : undefined,
+ : typeof action.payload.messageId === 'string'
+ ? action.payload.messageId
+ : undefined,
topicId: typeof action.payload.topicId === 'string' ? action.payload.topicId : undefined,
};
// Stamp the run so the completion path can project the memory receipt (the
diff --git a/src/server/services/aiAgent/__tests__/execAgent.threadId.test.ts b/src/server/services/aiAgent/__tests__/execAgent.threadId.test.ts
index 8c02f4d6aaa..9a9dbf80369 100644
--- a/src/server/services/aiAgent/__tests__/execAgent.threadId.test.ts
+++ b/src/server/services/aiAgent/__tests__/execAgent.threadId.test.ts
@@ -293,4 +293,45 @@ describe('AiAgentService.execAgent - threadId handling', () => {
// This is handled by the createOperation call
}, 10_000);
});
+
+ describe('Agent Signal marker attribution', () => {
+ it('persists trace messages under the reviewed user agent carried on the marker', async () => {
+ // Background self-iteration runs execute under a builtin slug, so the
+ // resolved agent ('agent-1') is the builtin agent — but their persisted
+ // messages must attribute to the reviewed user agent on `marker.agentId`,
+ // matching the operation row + receipts (not the builtin slug).
+ await service.execAgent({
+ agentId: 'agent-1',
+ appContext: {
+ agentSignal: { agentId: 'user-agent-9', kind: 'skill', sourceId: 'src-1' },
+ topicId: 'topic-1',
+ },
+ prompt: 'Skill feedback evidence',
+ });
+
+ const userMessageCall = mockMessageCreate.mock.calls.find((call) => call[0].role === 'user');
+ const assistantMessageCall = mockMessageCreate.mock.calls.find(
+ (call) => call[0].role === 'assistant',
+ );
+
+ expect(userMessageCall![0].agentId).toBe('user-agent-9');
+ expect(assistantMessageCall![0].agentId).toBe('user-agent-9');
+ }, 10_000);
+
+ it('falls back to the executing agent id for ordinary runs without a marker', async () => {
+ await service.execAgent({
+ agentId: 'agent-1',
+ appContext: { topicId: 'topic-1' },
+ prompt: 'Test prompt',
+ });
+
+ const userMessageCall = mockMessageCreate.mock.calls.find((call) => call[0].role === 'user');
+ const assistantMessageCall = mockMessageCreate.mock.calls.find(
+ (call) => call[0].role === 'assistant',
+ );
+
+ expect(userMessageCall![0].agentId).toBe('agent-1');
+ expect(assistantMessageCall![0].agentId).toBe('agent-1');
+ }, 10_000);
+ });
});
diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.ts
index f5792544021..e3a86660f0d 100644
--- a/src/server/services/aiAgent/index.ts
+++ b/src/server/services/aiAgent/index.ts
@@ -403,6 +403,15 @@ export class AiAgentService {
// Use actual agent ID from config for subsequent operations
const resolvedAgentId = agentConfig.id;
+ // Persistence-attribution agent id. Background Agent Signal runs (memory /
+ // skill / self-reflection) execute under a builtin slug, so `resolvedAgentId`
+ // is the builtin agent — but the run's persisted messages, like its operation
+ // row (createOperation appContext.agentId) and receipts, must attribute to the
+ // reviewed *user* agent carried on `marker.agentId`. Ordinary runs (no marker)
+ // fall back to the executing agent. Tools / systemRole / skills / agent
+ // documents stay keyed on `resolvedAgentId`.
+ const persistAgentId = appContext?.agentSignal?.agentId ?? resolvedAgentId;
+
// Apply per-call model/provider overrides (e.g. from task.config)
if (modelOverride) agentConfig.model = modelOverride;
if (providerOverride) agentConfig.provider = providerOverride;
@@ -1852,7 +1861,7 @@ export class AiAgentService {
const userMessageRecord = effectiveResume
? undefined
: await this.messageModel.create({
- agentId: resolvedAgentId,
+ agentId: persistAgentId,
content: prompt,
files: fileIds,
metadata: requestTriggerMetadata,
@@ -1898,7 +1907,7 @@ export class AiAgentService {
// 14. Create assistant message placeholder in database
// Include threadId if provided (for SubAgent task execution in isolated Thread)
const assistantMessageRecord = await this.messageModel.create({
- agentId: resolvedAgentId,
+ agentId: persistAgentId,
content: LOADING_FLAT,
model,
parentId: parentMessageId ?? userMessageRecord?.id,