🤯 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(agent-signal): preserve receipt anchor semantics (#16815)
AmAzing-354a87400722
diff --git a/apps/server/src/services/agentSignal/operationMarker.ts b/apps/server/src/services/agentSignal/operationMarker.tsindex 20a02f97ac3..aa48ed28797 100644--- a/apps/server/src/services/agentSignal/operationMarker.ts+++ b/apps/server/src/services/agentSignal/operationMarker.ts@@ -5,9 +5,10 @@* The `agent.execution.completed` source payload only carries* `agentId / operationId / topicId`. Async self-iteration & memory tools need* more: the originating source id, the review window / local date (for evidence- * re-derivation and brief/receipt writes), and the message anchors used to- * attach receipts back to the right assistant message. Rather than a side- * channel, this travels on the operation row itself.+ * re-derivation and brief/receipt writes), and optional message ids for receipt+ * projection. `triggerMessageId` is the causal source. `anchorMessageId` is an+ * explicit display anchor and should only point at a known assistant message.+ * Rather than a side channel, this travels on the operation row itself.*/import type { AgentSignalOperationKind, AgentSignalOperationMarker } from '@lobechat/types';diff --git a/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/__tests__/skillManagement.test.ts b/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/__tests__/skillManagement.test.tsindex 167130fc9a8..2d730d662f7 100644--- a/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/__tests__/skillManagement.test.ts+++ b/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/__tests__/skillManagement.test.ts@@ -59,11 +59,12 @@ describe('defineSkillManagementActionHandler', () => {expect(dispatched.slug).toBe('skill-management');expect(dispatched.agentId).toBe('agent_1');expect(dispatched.topicId).toBe('topic_1');- expect(dispatched.marker).toMatchObject({+ expect(dispatched.marker).toEqual({agentId: 'agent_1',kind: 'skill',sourceId: 'source_1:skill:msg_1',topicId: 'topic_1',+ triggerMessageId: 'msg_1',});expect(typeof dispatched.prompt).toBe('string');expect(dispatched.prompt).toContain(skillAction.payload.message);@@ -88,6 +89,38 @@ describe('defineSkillManagementActionHandler', () => {expect(dispatch.mock.calls[0][0].workspaceId).toBe('ws_1');});+ it('anchors the skill receipt to the completed assistant message when known', async () => {+ dispatch.mockResolvedValue({ operationId: 'op_1', topicId: 'topic_1' });++ const handler = defineSkillManagementActionHandler({+ db: {} as never,+ dispatch,+ selfIterationEnabled: true,+ userId: 'user_1',+ });++ await handler.handle(+ {+ ...skillAction,+ payload: {+ ...skillAction.payload,+ assistantMessageId: 'msg_assistant_1',+ },+ },+ createContext(),+ );++ expect(dispatch).toHaveBeenCalledTimes(1);+ expect(dispatch.mock.calls[0][0].marker).toEqual({+ agentId: 'agent_1',+ anchorMessageId: 'msg_assistant_1',+ kind: 'skill',+ sourceId: 'source_1:skill:msg_1',+ topicId: 'topic_1',+ triggerMessageId: 'msg_1',+ });+ });+it('skips when self-iteration is disabled (no dispatch)', async () => {const handler = defineSkillManagementActionHandler({db: {} as never,diff --git a/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/__tests__/userMemory.test.ts b/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/__tests__/userMemory.test.tsindex b68e03beeda..ab745e9d17a 100644--- a/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/__tests__/userMemory.test.ts+++ b/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/__tests__/userMemory.test.ts@@ -3,7 +3,11 @@ import { LayersEnum } from '@lobechat/types';import { beforeEach, describe, expect, it, vi } from 'vitest';import type { RuntimeProcessorContext } from '../../../../runtime/context';-import { defineUserMemoryActionHandler, resolveMemoryActionTargetFromState } from '../userMemory';+import {+ buildUserMemoryActionAgentSignalMarker,+ defineUserMemoryActionHandler,+ resolveMemoryActionTargetFromState,+} from '../userMemory';const memoryActionRunner = vi.fn();@@ -74,9 +78,9 @@ 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 () => {+ it('isolates 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+ // so assistantMessageId is absent. The run must still create a child thread// under the triggering user message instead of leaking into the main topic.memoryActionRunner.mockResolvedValue({ status: 'applied' });@@ -88,7 +92,7 @@ describe('defineUserMemoryActionHandler', () => {await handler.handle({- actionId: 'act_memory_fallback_anchor',+ actionId: 'act_memory_fallback_thread',actionType: 'action.user-memory.handle',chain: { chainId: 'chain_1', rootSourceId: 'source_1' },payload: {@@ -337,6 +341,40 @@ describe('defineUserMemoryActionHandler', () => {});});+describe('buildUserMemoryActionAgentSignalMarker', () => {+ it('keeps the user message as trigger without using it as the receipt anchor', () => {+ const marker = buildUserMemoryActionAgentSignalMarker({+ messageId: 'msg_user_1',+ sourceId: 'source_1:memory:msg_user_1',+ topicId: 'topic_1',+ });++ expect(marker).toEqual({+ kind: 'memory',+ sourceId: 'source_1:memory:msg_user_1',+ topicId: 'topic_1',+ triggerMessageId: 'msg_user_1',+ });+ });++ it('uses the assistant message as anchor while preserving the user trigger', () => {+ const marker = buildUserMemoryActionAgentSignalMarker({+ assistantMessageId: 'msg_assistant_1',+ messageId: 'msg_user_1',+ sourceId: 'source_1:memory:msg_user_1',+ topicId: 'topic_1',+ });++ expect(marker).toEqual({+ anchorMessageId: 'msg_assistant_1',+ kind: 'memory',+ sourceId: 'source_1:memory:msg_user_1',+ topicId: 'topic_1',+ triggerMessageId: 'msg_user_1',+ });+ });+});+describe('resolveMemoryActionTargetFromState', () => {it('extracts the successful memory title from runtime tool calls', () => {const target = resolveMemoryActionTargetFromState({diff --git a/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts b/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/skillManagement.tsindex 8674b73433e..c27ead323f6 100644--- a/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts+++ b/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts@@ -65,6 +65,31 @@ const toSkippedResult = (actionId: string, detail: string, startedAt: number): Econst isSkillManagementAction = (action: BaseAction): action is ActionSkillManagementHandle =>action.actionType === AGENT_SIGNAL_POLICY_ACTION_TYPES.skillManagementHandle;+interface BuildSkillManagementAgentSignalMarkerInput {+ agentId: string;+ assistantMessageId?: string;+ messageId?: string;+ sourceId: string;+ topicId?: string;+}++export const buildSkillManagementAgentSignalMarker = ({+ agentId,+ assistantMessageId,+ messageId,+ sourceId,+ topicId,+}: BuildSkillManagementAgentSignalMarkerInput): AgentSignalOperationMarker => ({+ agentId,+ // Preserve the split: user feedback is the trigger; only a known assistant+ // reply is a durable receipt anchor. UI fallback happens in the chat list.+ ...(assistantMessageId ? { anchorMessageId: assistantMessageId } : {}),+ kind: 'skill',+ sourceId,+ ...(messageId ? { triggerMessageId: messageId } : {}),+ ...(topicId ? { topicId } : {}),+});+/*** Renders the same-turn skill feedback into the agent prompt. The builtin* skill-management agent's systemRole carries the behavioural instructions; this@@ -155,13 +180,11 @@ export const executeSkillManagementAction = async (const sourceId = idempotencyKey ?? action.actionId;const { assistantMessageId, messageId, topicId } = action.payload;- // Anchor the skill seed under the completed assistant turn when the synthesis- // ran deferred at `agent.execution.completed` (skill delayed to turn- // completion so evidence carries the full trajectory); fall back to the user- // message for the legacy inbound dispatch. Anchoring to the assistant message- // keeps the seed inside the assistant group instead of surfacing as a- // floating `parent_id=null` mainline root.- const anchorMessageId = assistantMessageId ?? messageId;+ // Keep child-thread isolation separate from receipt anchoring. The receipt+ // marker only anchors to an assistant message; the fallback here prevents+ // async skill-management messages from flattening into the main topic when a+ // legacy inbound dispatch has no completed assistant boundary yet.+ const sourceMessageId = assistantMessageId ?? messageId;const prompt = buildSkillFeedbackPrompt({agentId,@@ -176,14 +199,13 @@ export const executeSkillManagementAction = async (// The run executes under the builtin skill-management slug, so attribute the// receipt to the reviewed user agent via `marker.agentId` (the operation's// own agentId is the builtin agent).- const marker: AgentSignalOperationMarker = {+ const marker = buildSkillManagementAgentSignalMarker({agentId,- kind: 'skill',+ ...(assistantMessageId ? { assistantMessageId } : {}),+ ...(messageId ? { messageId } : {}),sourceId,- ...(anchorMessageId ? { anchorMessageId } : {}),- ...(messageId ? { triggerMessageId: messageId } : {}),...(topicId ? { topicId } : {}),- };+ });const dispatch = options.dispatch ?? enqueueSelfIterationRun;await dispatch({@@ -192,7 +214,7 @@ export const executeSkillManagementAction = async (marker,prompt,slug: BUILTIN_AGENT_SLUGS.skillManagement,- ...(anchorMessageId ? { sourceMessageId: anchorMessageId } : {}),+ ...(sourceMessageId ? { sourceMessageId } : {}),threadTitle: 'Agent Signal Skill',...(topicId ? { topicId } : {}),userId: options.userId,diff --git a/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts b/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/userMemory.tsindex 71d1f846b9b..4f045503596 100644--- a/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts+++ b/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts@@ -105,6 +105,28 @@ const isUserMemoryAction = (action: BaseAction): action is ActionUserMemoryHandlreturn action.actionType === AGENT_SIGNAL_POLICY_ACTION_TYPES.userMemoryHandle;};+interface BuildUserMemoryActionAgentSignalMarkerInput {+ assistantMessageId?: string;+ messageId?: string;+ sourceId: string;+ topicId?: string;+}++export const buildUserMemoryActionAgentSignalMarker = ({+ assistantMessageId,+ messageId,+ sourceId,+ topicId,+}: BuildUserMemoryActionAgentSignalMarkerInput): AgentSignalOperationMarker => ({+ // Preserve the split: user feedback is the trigger; only a known assistant+ // reply is a durable receipt anchor. UI fallback happens in the chat list.+ ...(assistantMessageId ? { anchorMessageId: assistantMessageId } : {}),+ kind: 'memory',+ sourceId,+ ...(topicId ? { topicId } : {}),+ ...(messageId ? { triggerMessageId: messageId } : {}),+});+const createInitialContext = (operationId: string): AgentRuntimeContext => {return {payload: { message: [] },@@ -384,6 +406,12 @@ export const handleUserMemoryAction = async (action.payload.feedbackHint === 'satisfied' || action.payload.feedbackHint === 'not_satisfied'? action.payload.feedbackHint: undefined;+ const assistantMessageId =+ typeof action.payload.assistantMessageId === 'string'+ ? action.payload.assistantMessageId+ : undefined;+ const messageId =+ typeof action.payload.messageId === 'string' ? action.payload.messageId : undefined;const runnerInput = {agentId: typeof action.payload.agentId === 'string' ? action.payload.agentId : undefined,conflictPolicy:@@ -402,7 +430,7 @@ export const handleUserMemoryAction = async (typeof action.payload.sourceHints === 'object' && action.payload.sourceHints? action.payload.sourceHints: undefined,- // The message to anchor the memory-agent child thread under, so its+ // The message to attach the memory-agent child thread to, 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@@ -411,22 +439,17 @@ export const handleUserMemoryAction = async (// 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- : typeof action.payload.messageId === 'string'- ? action.payload.messageId- : undefined,+ sourceMessageId: assistantMessageId ?? messageId,topicId: typeof action.payload.topicId === 'string' ? action.payload.topicId : undefined,};// Stamp the run so the completion path can project the memory receipt (the// memory write is now enqueued async, not resolved synchronously here).- const marker: AgentSignalOperationMarker = {- kind: 'memory',- ...(runnerInput.sourceMessageId ? { anchorMessageId: runnerInput.sourceMessageId } : {}),+ const marker = buildUserMemoryActionAgentSignalMarker({+ ...(assistantMessageId ? { assistantMessageId } : {}),+ ...(messageId ? { messageId } : {}),sourceId: idempotencyKey ?? action.actionId,...(runnerInput.topicId ? { topicId: runnerInput.topicId } : {}),- };+ });const runner =options.memoryActionRunner ?? ((input) => runMemoryActionAgent(input, options, { marker }));let memoryActionResult: MemoryAgentActionResult | undefined;diff --git a/apps/server/src/services/agentSignal/policies/types.ts b/apps/server/src/services/agentSignal/policies/types.tsindex 4d9dbd0045a..355feab4241 100644--- a/apps/server/src/services/agentSignal/policies/types.ts+++ b/apps/server/src/services/agentSignal/policies/types.ts@@ -56,17 +56,10 @@ export type AgentSignalFeedbackDomainTarget = 'memory' | 'none' | 'prompt' | 'skexport type AgentSignalFeedbackPhase1DomainTarget = 'memory' | 'prompt' | 'skill';export type AgentSignalSkillIntentExplicitness =- | 'explicit_action'- | 'implicit_strong_learning'- | 'non_skill_preference'- | 'weak_positive';+ 'explicit_action' | 'implicit_strong_learning' | 'non_skill_preference' | 'weak_positive';export type AgentSignalSkillActionIntent =- | 'consolidate'- | 'create'- | 'maintain'- | 'noop'- | 'refine';+ 'consolidate' | 'create' | 'maintain' | 'noop' | 'refine';export type AgentSignalSkillIntentRoute = 'accumulate' | 'direct_decision' | 'non_skill';@@ -262,10 +255,7 @@ export interface AgentSignalPolicySignalPayloadMap {operationId: string;outcome: 'failed' | 'resolved' | 'succeeded';reason:- | 'execution-failed'- | 'repeated-repair'- | 'successful-resolution'- | 'unexpected-tool-result';+ 'execution-failed' | 'repeated-repair' | 'successful-resolution' | 'unexpected-tool-result';serializedContext?: string;topicId?: string;};@@ -317,11 +307,7 @@ export interface AgentSignalPolicyActionPayloadMap {};[AGENT_SIGNAL_POLICY_ACTION_TYPES.skillManagementHandle]: {agentId?: string;- /**- * Assistant message that completed the turn. When present (deferred- * completion-stage synthesis) the skill seed anchors here instead of under- * the user message, so it is not a floating mainline root.- */+ /** Assistant message that completed the turn, used as the receipt anchor when known. */assistantMessageId?: string;conflictPolicy?: AgentSignalFeedbackDomainConflictPolicy;evidence?: AgentSignalFeedbackEvidence[];@@ -336,6 +322,8 @@ export interface AgentSignalPolicyActionPayloadMap {};[AGENT_SIGNAL_POLICY_ACTION_TYPES.userMemoryHandle]: {agentId?: string;+ /** Assistant message that completed the turn, used as the receipt anchor when known. */+ assistantMessageId?: string;conflictPolicy?: AgentSignalFeedbackDomainConflictPolicy;evidence?: AgentSignalFeedbackEvidence[];feedbackHint?: Exclude<AgentSignalFeedbackSatisfactionResult, 'neutral'>;@@ -421,9 +409,7 @@ export type ActionNudgeHandle = AgentSignalPolicyActionVariant<'action.nudge.han/** Sources that can trigger the memory-nudge policy. */export type MemoryNudgePolicySource =- | SourceAgentExecutionCompleted- | SourceRuntimeAfterStep- | SourceRuntimeBeforeStep;+ SourceAgentExecutionCompleted | SourceRuntimeAfterStep | SourceRuntimeBeforeStep;/** Sources that can trigger self-reflection analysis. */export type SelfReflectionPolicySource = SourceAgentExecutionCompleted | SourceAgentExecutionFailed;diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.tsindex 25107d54d1e..052b2b70eca 100644--- a/packages/types/src/agentExecution/index.ts+++ b/packages/types/src/agentExecution/index.ts@@ -21,7 +21,14 @@ export interface AgentSignalOperationMarker {* completion projector prefers this over the run's agentId.*/agentId?: string;- /** Assistant message a resulting receipt should anchor to. */+ /**+ * Explicit display anchor for receipts. Write this only when the producer+ * already knows the exact assistant message that should own the receipt.+ *+ * Do not fall back to the triggering user message here. If the backend only+ * knows the causal source, write `triggerMessageId` and let the conversation+ * UI resolve the best display anchor from the current message graph.+ */anchorMessageId?: string;/** Discriminator the completion handler dispatches on. */kind: AgentSignalOperationKind;@@ -35,7 +42,11 @@ export interface AgentSignalOperationMarker {sourceId?: string;/** Topic the run is scoped to. */topicId?: string;- /** User message that initiated the originating feedback. */+ /**+ * Causal message source for the signal. For user-feedback flows this is the+ * user message that triggered the receipt; it is not necessarily the message+ * where the receipt should render.+ */triggerMessageId?: string;}diff --git a/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.ts b/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.tsindex f6c31d7509b..59f0c2b5619 100644--- a/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.ts+++ b/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.ts@@ -163,13 +163,10 @@ const resolveEffectiveAnchorMessageId = ();if (assistantReplyId) return assistantReplyId;- // WORKAROUND:- // Start-triggered Agent Signal receipts can arrive before the assistant row is available, so- // falling back to the trigger keeps them visible and prevents latest-message drift.- //- // TODO:- // Remove or simplify this fallback when all user-triggered paths provide anchorMessageId or- // stable assistant child resolution.+ // Display fallback belongs here, not in the persisted receipt. A trigger-only+ // receipt tells us why the signal fired; the UI can attach it to the assistant+ // reply when that row exists, or keep it visible on the triggering user message+ // while the assistant row is still unavailable.return receipt.triggerMessageId;};