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): preserve receipt anchors in user sources (#16818)

AmAzing-a4661bf983aa
diff --git a/.agents/skills/agent-signal/SKILL.md b/.agents/skills/agent-signal/SKILL.md
index ac656ac8cf4..f09c8347e63 100644
--- a/.agents/skills/agent-signal/SKILL.md
+++ b/.agents/skills/agent-signal/SKILL.md
@@ -7,10 +7,14 @@ description: 'Build or extend LobeHub Agent Signal pipelines. Use for signal sou
Use this skill to implement event-driven background work for agents without coupling the work to the foreground chat request.
-Agent Signal has one consistent shape:
+Agent Signal has one consistent runtime shape:
`source event` -> `signal interpretation` -> `action execution` -> built-in result signals
+Durable self-iteration work has one extra completion branch:
+
+`memory/skill action` -> `execAgent` enqueue -> `agent.execution.completed` -> `selfIteration` receipt projection
+
## Start Here
1. Read `references/architecture.md` to map the package boundary, runtime queue, scope model, and async workflow handoff.
@@ -48,13 +52,15 @@ Keep the boundaries strict:
## Implementation Workflow
1. Decide whether the use case is synchronous or quiet background work.
-2. Define or reuse a source type in `apps/server/src/services/agentSignal/sourceTypes.ts`.
+2. Define or reuse a source type in `packages/agent-signal/src/source/sourceTypes.ts`.
3. Define or reuse signal and action types in `apps/server/src/services/agentSignal/policies/types.ts`.
4. Implement handlers with `defineSourceHandler`, `defineSignalHandler`, or `defineActionHandler`.
-5. Bundle handlers with `defineAgentSignalHandlers(...)`.
-6. Register the policy in `apps/server/src/services/agentSignal/policies/index.ts` and pass it into the runtime factory if needed.
-7. Add or update ingress code that emits or enqueues the source event.
-8. Add observability and tests before considering the flow complete.
+5. Add source normalization or hydration under `apps/server/src/services/agentSignal/sources/**` when the producer payload needs shaping.
+6. Bundle handlers with `defineAgentSignalHandlers(...)`.
+7. Register the policy in `apps/server/src/services/agentSignal/policies/index.ts` and pass it into the runtime factory if needed.
+8. Add or update ingress code that emits or enqueues the source event.
+9. For async self-iteration writes, stamp an Agent Signal operation marker and project user-visible receipts from the completion path.
+10. Add observability and tests before considering the flow complete.
## Default Reading Set
@@ -62,6 +68,8 @@ Keep the boundaries strict:
`packages/agent-signal/src/index.ts`
`packages/agent-signal/src/base/builders.ts`
`packages/agent-signal/src/base/types.ts`
+ `packages/agent-signal/src/source/sourceTypes.ts`
+ `packages/agent-signal/src/source/sourceEvent.ts`
- Server-owned runtime and middleware:
`apps/server/src/services/agentSignal/runtime/AgentSignalRuntime.ts`
`apps/server/src/services/agentSignal/runtime/AgentSignalScheduler.ts`
@@ -73,6 +81,11 @@ Keep the boundaries strict:
`apps/server/src/services/agentSignal/policies/analyzeIntent/feedbackDomain.ts`
`apps/server/src/services/agentSignal/policies/analyzeIntent/feedbackAction.ts`
`apps/server/src/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts`
+ `apps/server/src/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts`
+ `apps/server/src/services/agentSignal/policies/analyzeIntent/completionSkillSynthesis.ts`
+ `apps/server/src/services/agentSignal/policies/completionPolicy.ts`
+ `apps/server/src/services/agentSignal/services/selfIteration/completion/buildSelfIterationReceipts.ts`
+ `apps/server/src/services/agentSignal/services/selfIteration/completion/selfIterationCompletionHandler.ts`
- Observability:
`apps/server/src/services/agentSignal/observability/projector.ts`
`apps/server/src/services/agentSignal/observability/traceEvents.ts`
@@ -82,11 +95,12 @@ Keep the boundaries strict:
- Reuse existing source, signal, and action types before adding new ones.
- Keep source handlers focused on interpretation and fan-out, not heavy side effects.
-- Keep action handlers responsible for side effects, idempotency, and executor-style result reporting.
+- Keep action handlers responsible for side effects, idempotency, and executor-style result reporting. For memory/skill self-iteration actions, the side effect is enqueueing `execAgent`; the durable write and receipt projection happen after completion.
- Use stable ids and idempotency keys when the same source can arrive more than once.
- Preserve scope discipline. The runtime uses `scopeKey` to serialize related background work.
- Prefer the dedicated shared package types and builders from `@lobechat/agent-signal` for normalized nodes and result contracts.
-- Add focused tests near the touched runtime, policy, or store module. Existing tests under `apps/server/src/services/agentSignal/**/__tests__` are the reference pattern.
+- Do not project memory or skill receipts from the enqueue action. Use `agent.execution.completed` + `selfIteration` finalState via `createSelfIterationCompletionHandler(...)`.
+- Add focused tests near the touched runtime, policy, or store module. Existing tests under `apps/server/src/services/agentSignal/**/__test__` and `**/__tests__` are the reference pattern.
## References
diff --git a/.agents/skills/agent-signal/agents/openai.yaml b/.agents/skills/agent-signal/agents/openai.yaml
index 7d755ddc4fd..5ccee60bdcb 100644
--- a/.agents/skills/agent-signal/agents/openai.yaml
+++ b/.agents/skills/agent-signal/agents/openai.yaml
@@ -1,4 +1,4 @@
interface:
display_name: 'Agent Signal'
- short_description: 'Build AgentSignal sources, signals, actions, and policies.'
- default_prompt: 'Use $agent-signal to add a new Agent Signal source, policy, handler, or observability flow.'
+ short_description: 'Build AgentSignal sources, policies, completion receipts, and observability.'
+ default_prompt: 'Use $agent-signal to add or debug an Agent Signal source, policy, handler, completion receipt, or observability flow.'
diff --git a/.agents/skills/agent-signal/references/architecture.md b/.agents/skills/agent-signal/references/architecture.md
index f691e4fe436..27536d649d1 100644
--- a/.agents/skills/agent-signal/references/architecture.md
+++ b/.agents/skills/agent-signal/references/architecture.md
@@ -17,6 +17,23 @@ producer
-> observability projection + persistence
```
+For durable memory, skill, and self-review writes, the action handler can enqueue
+an async `execAgent` run instead of doing the write synchronously:
+
+```text
+action.user-memory.handle | action.skill-management.handle | self-iteration source
+ -> stamp AgentSignal operation marker
+ -> enqueue execAgent
+ -> agent.execution.completed with selfIteration finalState
+ -> completion policy
+ -> buildSelfIterationReceipts(...)
+ -> receipt store
+```
+
+The immediate runtime chain still emits `signal.action.applied | skipped | failed`
+for the enqueue result. User-visible memory and skill receipts are projected from
+the completion event, not from the enqueue action.
+
The scheduler is queue-driven, not hard-coded for one policy:
```text
@@ -46,6 +63,8 @@ It provides:
- base node types: source, signal, action
- builders: `createSource`, `createSignal`, `createAction`
+- shared source type and payload catalog
+- source-event envelopes and scope helpers
- built-in result signal types
- runtime result contracts such as `RuntimeProcessorResult` and `ExecutorResult`
@@ -53,6 +72,9 @@ Read:
- `packages/agent-signal/src/base/types.ts`
- `packages/agent-signal/src/base/builders.ts`
+- `packages/agent-signal/src/source/sourceTypes.ts`
+- `packages/agent-signal/src/source/sourceEvent.ts`
+- `packages/agent-signal/src/source/scopeKey.ts`
- `packages/agent-signal/src/types/events.ts`
- `packages/agent-signal/src/types/builtin.ts`
@@ -62,12 +84,13 @@ Treat this as the server-owned implementation layer.
It owns:
-- source catalogs and payload maps
+- source normalization, hydration, and renderers
- policy-specific signal and action catalogs
- middleware registration
- runtime scheduling and guard backends
- Redis-backed dedupe, waypoint, and policy state
- service entrypoints for synchronous and async execution
+- receipt projection and persistence for completed self-iteration runs
### `packages/observability-otel/src/modules/agent-signal`
@@ -89,11 +112,13 @@ Examples:
Define source payloads in:
-- `apps/server/src/services/agentSignal/sourceTypes.ts`
+- `packages/agent-signal/src/source/sourceTypes.ts`
Build normalized sources in:
+- `packages/agent-signal/src/source/sourceEvent.ts`
- `apps/server/src/services/agentSignal/sources/buildSource.ts`
+- `apps/server/src/services/agentSignal/sources/renderers/*`
- `packages/agent-signal/src/base/builders.ts`
### Signal
@@ -186,10 +211,27 @@ agent.user.message
-> feedback domain signal handler
-> signal.feedback.domain.*
-> feedback action planner
- -> action.user-memory.handle
+ -> action.user-memory.handle | action.skill-management.handle
-> signal.action.applied | skipped | failed
```
+The current policy also includes optional tool-outcome projection, skill
+management, deferred completion skill synthesis, nightly review, and completion
+fan-out:
+
+```text
+action.user-memory.handle | action.skill-management.handle
+ -> enqueue execAgent with AgentSignal marker
+ -> agent.execution.completed
+ -> completion policy
+ -> buildSelfIterationReceipts(...)
+ -> memory | skill | review receipts
+```
+
+For skill synthesis, an inbound user-message candidate can be parked during the
+foreground chain and resumed after `agent.execution.completed`, where the full
+trajectory and tool outcomes are available.
+
Read:
- `apps/server/src/services/agentSignal/policies/analyzeIntent/index.ts`
@@ -197,3 +239,8 @@ Read:
- `apps/server/src/services/agentSignal/policies/analyzeIntent/feedbackDomain.ts`
- `apps/server/src/services/agentSignal/policies/analyzeIntent/feedbackAction.ts`
- `apps/server/src/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts`
+- `apps/server/src/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts`
+- `apps/server/src/services/agentSignal/policies/analyzeIntent/completionSkillSynthesis.ts`
+- `apps/server/src/services/agentSignal/policies/completionPolicy.ts`
+- `apps/server/src/services/agentSignal/services/selfIteration/completion/buildSelfIterationReceipts.ts`
+- `apps/server/src/services/agentSignal/services/selfIteration/completion/selfIterationCompletionHandler.ts`
diff --git a/.agents/skills/agent-signal/references/handlers.md b/.agents/skills/agent-signal/references/handlers.md
index f938b954185..b88b15adb27 100644
--- a/.agents/skills/agent-signal/references/handlers.md
+++ b/.agents/skills/agent-signal/references/handlers.md
@@ -58,9 +58,12 @@ Example from `analyzeIntent`:
```ts
return defineAgentSignalHandlers([
+ ...(options.procedure ? [createToolOutcomeSourceHandler(options.procedure)] : []),
createFeedbackSatisfactionJudgeProcessor(...),
createFeedbackDomainJudgeSignalHandler(...),
createFeedbackActionPlannerSignalHandler(),
+ defineSkillManagementActionHandler(...),
+ createCompletionSkillSynthesisSourceHandler(...),
defineUserMemoryActionHandler(...),
]);
```
@@ -94,9 +97,7 @@ return defineSourceHandler(
// optionally use ctx.runtimeState
return {
- signals: [
- /* one or more semantic signals */
- ],
+ signals: [/* one or more semantic signals */],
status: 'dispatch',
};
},
@@ -125,9 +126,7 @@ return defineSignalHandler(
'signal.my-policy-router',
async (signal): Promise<RuntimeProcessorResult | void> => {
return {
- actions: [
- /* planned work */
- ],
+ actions: [/* planned work */],
status: 'dispatch',
};
},
@@ -144,11 +143,13 @@ Use signal handlers for:
## Action Handler Pattern
-Use an action handler when the runtime should do actual work.
+Use an action handler when the runtime should do actual work or enqueue the work
+that will run out-of-band.
-Reference:
+References:
- `apps/server/src/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts`
+- `apps/server/src/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts`
Pattern:
@@ -180,13 +181,25 @@ Keep these rules:
- return stable `actionId`
- include failure detail in `error`
- let the scheduler turn the `ExecutorResult` into built-in result signals
+- for async `execAgent` actions, report the enqueue result here and project durable receipts from `agent.execution.completed`
+
+For memory and skill self-iteration actions, the concrete side effect is
+`enqueueSelfIterationRun(...)`. The background run stamps an Agent Signal
+operation marker, writes durable resources in the agent runtime, then exposes
+mutation outcomes on the completion source's `selfIteration` payload. Do not add
+a second synchronous receipt projection to the action handler.
## Source, Signal, And Action Type Placement
Use this split:
- external event payloads:
- `apps/server/src/services/agentSignal/sourceTypes.ts`
+ `packages/agent-signal/src/source/sourceTypes.ts`
+- source-event envelopes and scope keys:
+ `packages/agent-signal/src/source/sourceEvent.ts`
+ `packages/agent-signal/src/source/scopeKey.ts`
+- server source normalization and hydration:
+ `apps/server/src/services/agentSignal/sources/**`
- policy-owned signal and action payloads:
`apps/server/src/services/agentSignal/policies/types.ts`
- normalized shared node contracts:
@@ -220,9 +233,11 @@ Useful references:
- `apps/server/src/services/agentSignal/__tests__/index.integration.test.ts`
- `apps/server/src/services/agentSignal/policies/analyzeIntent/__tests__/*`
- `apps/server/src/services/agentSignal/policies/analyzeIntent/actions/__tests__/*`
+- `apps/server/src/services/agentSignal/services/selfIteration/completion/__test__/*`
Test at the smallest level that proves the behavior:
- handler unit test for one routing rule
- runtime test for queue fan-out
+- completion projection test for async memory or skill receipts
- integration test for service ingress and observability persistence
diff --git a/.agents/skills/agent-signal/references/observability.md b/.agents/skills/agent-signal/references/observability.md
index c5d100b6d01..e61482b583e 100644
--- a/.agents/skills/agent-signal/references/observability.md
+++ b/.agents/skills/agent-signal/references/observability.md
@@ -15,6 +15,13 @@ Available instruments:
- `signalActionTransitionCounter`
- `chainDurationHistogram`
- `actionDurationHistogram`
+- `sourceEventCounter`
+- `sourceEventDurationHistogram`
+- `workflowRunCounter`
+- `workflowRunDurationHistogram`
+- `handlerCounter`
+- `handlerDurationHistogram`
+- `terminalResultCounter`
Use this module when you need shared telemetry ownership instead of creating feature-local meters or tracers.
@@ -40,6 +47,12 @@ This projection is built from:
- planned actions
- executor results
+Receipt projection is separate from observability projection. The orchestrator
+still calls `projectAgentSignalReceipts(...)` after an immediate runtime chain,
+but memory and skill self-iteration receipts are projected from
+`agent.execution.completed` via `buildSelfIterationReceipts(...)` and persisted
+through the receipt store.
+
## How To Inspect A Chain
Use this order:
@@ -109,10 +122,22 @@ Check:
- projected telemetry record contents
- OTEL counters and histograms in the shared module
+### Memory or skill receipts are missing after an action applied
+
+Check:
+
+- the action handler enqueued `execAgent` and stamped an Agent Signal operation marker
+- `agent.execution.completed` carried a `selfIteration` payload from the run's finalState
+- `createCompletionPolicy(...)` was wired with `onSelfIterationCompleted`
+- `buildSelfIterationReceipts(...)` recognized the durable mutation api name
+- the receipt store accepted the deterministic receipt id
+- the marker includes usable `anchorMessageId` or `triggerMessageId` when UI placement matters
+
## Minimal Completion Checklist
- source ingress is testable
- handler registration is discoverable from the policy factory
- action executor returns structured results
- projection includes the new path cleanly
+- async self-iteration receipts, when relevant, are covered on the completion path
- tests cover at least one happy path and one no-op or failure path
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.ts
index 2d730d662f7..03b7dc9d724 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
@@ -121,6 +121,32 @@ describe('defineSkillManagementActionHandler', () => {
});
});
+ it('stamps the explicit trigger id when it differs from the feedback message id', 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,
+ messageId: 'msg_feedback_1',
+ triggerMessageId: 'msg_trigger_1',
+ },
+ },
+ createContext(),
+ );
+
+ expect(dispatch).toHaveBeenCalledTimes(1);
+ expect(dispatch.mock.calls[0][0].marker.triggerMessageId).toBe('msg_trigger_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.ts
index ab745e9d17a..a291e4ff76e 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
@@ -344,9 +344,9 @@ 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',
+ triggerMessageId: 'msg_user_1',
});
expect(marker).toEqual({
@@ -360,9 +360,9 @@ describe('buildUserMemoryActionAgentSignalMarker', () => {
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',
+ triggerMessageId: 'msg_user_1',
});
expect(marker).toEqual({
@@ -373,6 +373,17 @@ describe('buildUserMemoryActionAgentSignalMarker', () => {
triggerMessageId: 'msg_user_1',
});
});
+
+ it('keeps an explicit trigger id separate from the feedback message id', () => {
+ const marker = buildUserMemoryActionAgentSignalMarker({
+ assistantMessageId: 'msg_assistant_1',
+ sourceId: 'source_1:memory:msg_feedback_1',
+ topicId: 'topic_1',
+ triggerMessageId: 'msg_trigger_1',
+ });
+
+ expect(marker.triggerMessageId).toBe('msg_trigger_1');
+ });
});
describe('resolveMemoryActionTargetFromState', () => {
diff --git a/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts b/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts
index c27ead323f6..66c17b2f882 100644
--- a/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts
+++ b/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts
@@ -68,17 +68,17 @@ const isSkillManagementAction = (action: BaseAction): action is ActionSkillManag
interface BuildSkillManagementAgentSignalMarkerInput {
agentId: string;
assistantMessageId?: string;
- messageId?: string;
sourceId: string;
topicId?: string;
+ triggerMessageId?: string;
}
export const buildSkillManagementAgentSignalMarker = ({
agentId,
assistantMessageId,
- messageId,
sourceId,
topicId,
+ triggerMessageId,
}: BuildSkillManagementAgentSignalMarkerInput): AgentSignalOperationMarker => ({
agentId,
// Preserve the split: user feedback is the trigger; only a known assistant
@@ -86,8 +86,8 @@ export const buildSkillManagementAgentSignalMarker = ({
...(assistantMessageId ? { anchorMessageId: assistantMessageId } : {}),
kind: 'skill',
sourceId,
- ...(messageId ? { triggerMessageId: messageId } : {}),
...(topicId ? { topicId } : {}),
+ ...(triggerMessageId ? { triggerMessageId } : {}),
});
/**
@@ -179,12 +179,13 @@ export const executeSkillManagementAction = async (
const sourceId = idempotencyKey ?? action.actionId;
const { assistantMessageId, messageId, topicId } = action.payload;
+ const triggerMessageId = action.payload.triggerMessageId ?? 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 sourceMessageId = assistantMessageId ?? triggerMessageId;
const prompt = buildSkillFeedbackPrompt({
agentId,
@@ -202,9 +203,9 @@ export const executeSkillManagementAction = async (
const marker = buildSkillManagementAgentSignalMarker({
agentId,
...(assistantMessageId ? { assistantMessageId } : {}),
- ...(messageId ? { messageId } : {}),
sourceId,
...(topicId ? { topicId } : {}),
+ ...(triggerMessageId ? { triggerMessageId } : {}),
});
const dispatch = options.dispatch ?? enqueueSelfIterationRun;
diff --git a/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts b/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts
index 4f045503596..c3ac7808eec 100644
--- a/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts
+++ b/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts
@@ -107,16 +107,16 @@ const isUserMemoryAction = (action: BaseAction): action is ActionUserMemoryHandl
interface BuildUserMemoryActionAgentSignalMarkerInput {
assistantMessageId?: string;
- messageId?: string;
sourceId: string;
topicId?: string;
+ triggerMessageId?: string;
}
export const buildUserMemoryActionAgentSignalMarker = ({
assistantMessageId,
- messageId,
sourceId,
topicId,
+ triggerMessageId,
}: 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.
@@ -124,7 +124,7 @@ export const buildUserMemoryActionAgentSignalMarker = ({
kind: 'memory',
sourceId,
...(topicId ? { topicId } : {}),
- ...(messageId ? { triggerMessageId: messageId } : {}),
+ ...(triggerMessageId ? { triggerMessageId } : {}),
});
const createInitialContext = (operationId: string): AgentRuntimeContext => {
@@ -412,6 +412,10 @@ export const handleUserMemoryAction = async (
: undefined;
const messageId =
typeof action.payload.messageId === 'string' ? action.payload.messageId : undefined;
+ const triggerMessageId =
+ typeof action.payload.triggerMessageId === 'string'
+ ? action.payload.triggerMessageId
+ : messageId;
const runnerInput = {
agentId: typeof action.payload.agentId === 'string' ? action.payload.agentId : undefined,
conflictPolicy:
@@ -430,25 +434,20 @@ export const handleUserMemoryAction = async (
typeof action.payload.sourceHints === 'object' && action.payload.sourceHints
? action.payload.sourceHints
: undefined,
- // 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
- // 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: assistantMessageId ?? messageId,
+ // Attach the memory-agent child thread to the completed assistant turn
+ // when the planner has one, either from the normalized payload anchor or
+ // the legacy `:completion:` source id. Fall back to the triggering
+ // message so the async run still stays out of the main topic.
+ sourceMessageId: assistantMessageId ?? triggerMessageId,
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 = buildUserMemoryActionAgentSignalMarker({
...(assistantMessageId ? { assistantMessageId } : {}),
- ...(messageId ? { messageId } : {}),
sourceId: idempotencyKey ?? action.actionId,
...(runnerInput.topicId ? { topicId: runnerInput.topicId } : {}),
+ ...(triggerMessageId ? { triggerMessageId } : {}),
});
const runner =
options.memoryActionRunner ?? ((input) => runMemoryActionAgent(input, options, { marker }));
diff --git a/apps/server/src/services/agentSignal/policies/types.ts b/apps/server/src/services/agentSignal/policies/types.ts
index 355feab4241..a2dc929b3dd 100644
--- a/apps/server/src/services/agentSignal/policies/types.ts
+++ b/apps/server/src/services/agentSignal/policies/types.ts
@@ -139,6 +139,8 @@ export interface AgentSignalFeedbackDomainConflictPolicy {
export interface AgentSignalPolicySignalPayloadMap {
[AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainMemory]: {
agentId?: string;
+ /** Assistant message that completed the turn, used as the receipt anchor when known. */
+ anchorMessageId?: string;
confidence: number;
conflictPolicy: AgentSignalFeedbackDomainConflictPolicy;
evidence: AgentSignalFeedbackEvidence[];
@@ -152,9 +154,13 @@ export interface AgentSignalPolicySignalPayloadMap {
topicId?: string;
/** Source event trigger copied from the original feedback input when available. */
trigger?: string;
+ /** Message that initiated the source or run, usually the user message. */
+ triggerMessageId?: string;
};
[AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainNone]: {
agentId?: string;
+ /** Assistant message that completed the turn, used as the receipt anchor when known. */
+ anchorMessageId?: string;
confidence: number;
conflictPolicy: AgentSignalFeedbackDomainConflictPolicy;
evidence: AgentSignalFeedbackEvidence[];
@@ -168,9 +174,13 @@ export interface AgentSignalPolicySignalPayloadMap {
topicId?: string;
/** Source event trigger copied from the original feedback input when available. */
trigger?: string;
+ /** Message that initiated the source or run, usually the user message. */
+ triggerMessageId?: string;
};
[AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainPrompt]: {
agentId?: string;
+ /** Assistant message that completed the turn, used as the receipt anchor when known. */
+ anchorMessageId?: string;
confidence: number;
conflictPolicy: AgentSignalFeedbackDomainConflictPolicy;
evidence: AgentSignalFeedbackEvidence[];
@@ -184,9 +194,13 @@ export interface AgentSignalPolicySignalPayloadMap {
topicId?: string;
/** Source event trigger copied from the original feedback input when available. */
trigger?: string;
+ /** Message that initiated the source or run, usually the user message. */
+ triggerMessageId?: string;
};
[AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainSkill]: {
agentId?: string;
+ /** Assistant message that completed the turn, used as the receipt anchor when known. */
+ anchorMessageId?: string;
confidence: number;
conflictPolicy: AgentSignalFeedbackDomainConflictPolicy;
evidence: AgentSignalFeedbackEvidence[];
@@ -206,9 +220,13 @@ export interface AgentSignalPolicySignalPayloadMap {
topicId?: string;
/** Source event trigger copied from the original feedback input when available. */
trigger?: string;
+ /** Message that initiated the source or run, usually the user message. */
+ triggerMessageId?: string;
};
[AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackSatisfaction]: {
agentId?: string;
+ /** Assistant message that completed the turn, used as the receipt anchor when known. */
+ anchorMessageId?: string;
confidence: number;
evidence: AgentSignalFeedbackEvidence[];
message: string;
@@ -220,6 +238,8 @@ export interface AgentSignalPolicySignalPayloadMap {
topicId?: string;
/** Source event trigger copied from the original feedback input when available. */
trigger?: string;
+ /** Message that initiated the source or run, usually the user message. */
+ triggerMessageId?: string;
};
[AGENT_SIGNAL_POLICY_SIGNAL_TYPES.nudgeMemoryConditionMatched]: {
agentId?: string;
@@ -319,6 +339,8 @@ export interface AgentSignalPolicyActionPayloadMap {
serializedContext?: string;
sourceHints?: AgentSignalFeedbackSourceHints;
topicId?: string;
+ /** Message that initiated the source or run, usually the user message. */
+ triggerMessageId?: string;
};
[AGENT_SIGNAL_POLICY_ACTION_TYPES.userMemoryHandle]: {
agentId?: string;
@@ -334,6 +356,8 @@ export interface AgentSignalPolicyActionPayloadMap {
serializedContext?: string;
sourceHints?: AgentSignalFeedbackSourceHints;
topicId?: string;
+ /** Message that initiated the source or run, usually the user message. */
+ triggerMessageId?: string;
};
}
diff --git a/apps/server/src/services/agentSignal/processors/__tests__/actions.test.ts b/apps/server/src/services/agentSignal/processors/__tests__/actions.test.ts
index 6931789041e..c1e8f05356f 100644
--- a/apps/server/src/services/agentSignal/processors/__tests__/actions.test.ts
+++ b/apps/server/src/services/agentSignal/processors/__tests__/actions.test.ts
@@ -16,6 +16,7 @@ const payloadSerializedContext =
const createMemorySignal = (
input: Partial<{
+ anchorMessageId: string;
message: string;
messageId: string;
payloadSerializedContext: string;
@@ -24,6 +25,7 @@ const createMemorySignal = (
signalId: string;
sourceSerializedContext: unknown;
sourceId: string;
+ triggerMessageId: string;
}> = {},
) => {
const base = {
@@ -47,6 +49,7 @@ const createMemorySignal = (
...base,
payload: {
agentId: 'agent_1',
+ anchorMessageId: input.anchorMessageId,
confidence: 0.9,
conflictPolicy: { forbiddenWith: ['none'], mode: 'fanout', priority: 100 },
evidence: [{ cue: 'test', excerpt: input.message ?? 'Remember this.' }],
@@ -58,6 +61,7 @@ const createMemorySignal = (
sourceHints: { intents: ['memory'] },
target: 'memory',
topicId: 'topic_1',
+ triggerMessageId: input.triggerMessageId,
},
signalId: input.signalId ?? 'sig_1',
signalType: 'signal.feedback.domain.memory',
@@ -66,6 +70,7 @@ const createMemorySignal = (
const createSkillSignal = (
input: Partial<{
+ anchorMessageId: string;
message: string;
messageId: string;
payloadSerializedContext: string;
@@ -74,6 +79,7 @@ const createSkillSignal = (
signalId: string;
sourceSerializedContext: unknown;
sourceId: string;
+ triggerMessageId: string;
}> = {},
) => {
const base = {
@@ -97,6 +103,7 @@ const createSkillSignal = (
...base,
payload: {
agentId: 'agent_1',
+ anchorMessageId: input.anchorMessageId,
confidence: 0.9,
conflictPolicy: { forbiddenWith: ['none'], mode: 'fanout', priority: 80 },
evidence: [{ cue: 'test', excerpt: input.message ?? 'Keep this workflow as a skill.' }],
@@ -108,6 +115,7 @@ const createSkillSignal = (
sourceHints: { intents: ['skill'] },
target: 'skill',
topicId: 'topic_1',
+ triggerMessageId: input.triggerMessageId,
},
signalId: input.signalId ?? 'sig_1',
signalType: 'signal.feedback.domain.skill',
@@ -190,6 +198,7 @@ describe('action planning processors', () => {
serializedContext: payloadSerializedContext,
sourceHints: signal.payload.sourceHints,
topicId: 'topic_1',
+ triggerMessageId: 'msg_memory_1',
});
expect(action.signal).toEqual({
signalId: 'sig_memory_1',
@@ -259,6 +268,28 @@ describe('action planning processors', () => {
expect(action.payload.serializedContext).toBeUndefined();
});
+ it('uses the propagated assistant anchor for user memory actions when source id is opaque', () => {
+ const signal = createMemorySignal({
+ anchorMessageId: 'msg_assistant_1',
+ sourceId: 'opaque_source_1',
+ });
+
+ const action = planUserMemory(signal);
+
+ expect(action.payload.assistantMessageId).toBe('msg_assistant_1');
+ });
+
+ it('uses the explicit trigger anchor for user memory actions when it differs from message id', () => {
+ const signal = createMemorySignal({
+ messageId: 'msg_feedback_1',
+ triggerMessageId: 'msg_trigger_1',
+ });
+
+ const action = planUserMemory(signal);
+
+ expect(action.payload.triggerMessageId).toBe('msg_trigger_1');
+ });
+
/**
* @example
* Skill action planning accepts skill-domain signals after handler-level route narrowing.
@@ -311,6 +342,7 @@ describe('action planning processors', () => {
serializedContext: payloadSerializedContext,
sourceHints: signal.payload.sourceHints,
topicId: 'topic_1',
+ triggerMessageId: 'msg_skill_1',
});
expect(action.signal).toEqual({
signalId: 'sig_skill_1',
@@ -319,4 +351,26 @@ describe('action planning processors', () => {
expect(action.source).toBe(signal.source);
expect(action.timestamp).toBe(1);
});
+
+ it('uses the propagated assistant anchor for skill management actions when source id is opaque', () => {
+ const signal = createNonSatisfiedSkillSignal({
+ anchorMessageId: 'msg_assistant_2',
+ sourceId: 'opaque_source_2',
+ });
+
+ const action = planSkillManagement(signal);
+
+ expect(action.payload.assistantMessageId).toBe('msg_assistant_2');
+ });
+
+ it('uses the explicit trigger anchor for skill management actions when it differs from message id', () => {
+ const signal = createNonSatisfiedSkillSignal({
+ messageId: 'msg_feedback_2',
+ triggerMessageId: 'msg_trigger_2',
+ });
+
+ const action = planSkillManagement(signal);
+
+ expect(action.payload.triggerMessageId).toBe('msg_trigger_2');
+ });
});
diff --git a/apps/server/src/services/agentSignal/processors/__tests__/classifiers.test.ts b/apps/server/src/services/agentSignal/processors/__tests__/classifiers.test.ts
index bb1cc934ad8..8ded18f077e 100644
--- a/apps/server/src/services/agentSignal/processors/__tests__/classifiers.test.ts
+++ b/apps/server/src/services/agentSignal/processors/__tests__/classifiers.test.ts
@@ -22,8 +22,10 @@ const context = createRuntimeProcessorContext({
const createUserMessageSource = (
input: Partial<{
+ anchorMessageId: string;
message: string;
sourceId: string;
+ triggerMessageId: string;
}> = {},
): SourceAgentUserMessage => ({
chain: {
@@ -32,6 +34,7 @@ const createUserMessageSource = (
},
payload: {
agentId: 'agent_1',
+ anchorMessageId: input.anchorMessageId,
documentPayload: { section: 'style' },
intents: ['document', 'memory'],
memoryPayload: { shouldRemember: true },
@@ -39,6 +42,7 @@ const createUserMessageSource = (
messageId: `msg:${input.sourceId ?? 'source_1'}`,
serializedContext: 'topic=repo-review',
topicId: 'topic_1',
+ triggerMessageId: input.triggerMessageId,
},
scopeKey: 'topic:thread_1',
sourceId: input.sourceId ?? 'source_1',
@@ -97,7 +101,10 @@ describe('classifier processors', () => {
reason: 'explicit style feedback',
result: 'not_satisfied',
});
- const source = createUserMessageSource();
+ const source = createUserMessageSource({
+ anchorMessageId: 'msg_assistant_1',
+ triggerMessageId: 'msg_trigger_1',
+ });
const result = await classifySatisfaction(source, context, {
satisfactionClassifier: { classify },
@@ -118,6 +125,7 @@ describe('classifier processors', () => {
},
payload: expect.objectContaining({
agentId: 'agent_1',
+ anchorMessageId: 'msg_assistant_1',
message: 'Please keep replies tighter.',
messageId: 'msg:source_1',
serializedContext: 'topic=repo-review',
@@ -127,6 +135,7 @@ describe('classifier processors', () => {
memoryPayload: { shouldRemember: true },
},
topicId: 'topic_1',
+ triggerMessageId: 'msg_trigger_1',
}),
signalId: 'source_1:signal:feedback-satisfaction',
signalType: 'signal.feedback.satisfaction',
@@ -158,7 +167,10 @@ describe('classifier processors', () => {
target: 'skill',
},
]);
- const signal = createSatisfactionSignal();
+ const signal = createSatisfactionSignal({
+ anchorMessageId: 'msg_assistant_1',
+ triggerMessageId: 'msg_trigger_1',
+ });
const result = await classifyDomain(signal, context, {
domainClassifier: { classify },
@@ -171,10 +183,12 @@ describe('classifier processors', () => {
value: [
expect.objectContaining({
payload: expect.objectContaining({
+ anchorMessageId: 'msg_assistant_1',
conflictPolicy: { forbiddenWith: ['none'], mode: 'fanout', priority: 100 },
evidence: signal.payload.evidence,
satisfactionResult: 'not_satisfied',
target: 'memory',
+ triggerMessageId: 'msg_trigger_1',
}),
signalId: 'source_1:signal:feedback-satisfaction:domain:memory',
signalType: 'signal.feedback.domain.memory',
@@ -182,10 +196,12 @@ describe('classifier processors', () => {
}),
expect.objectContaining({
payload: expect.objectContaining({
+ anchorMessageId: 'msg_assistant_1',
conflictPolicy: { forbiddenWith: ['none'], mode: 'fanout', priority: 80 },
evidence: [{ cue: 'template', excerpt: 'reusable template' }],
satisfactionResult: 'not_satisfied',
target: 'skill',
+ triggerMessageId: 'msg_trigger_1',
}),
signalId: 'source_1:signal:feedback-satisfaction:domain:skill',
signalType: 'signal.feedback.domain.skill',
diff --git a/apps/server/src/services/agentSignal/processors/actions.ts b/apps/server/src/services/agentSignal/processors/actions.ts
index 783e2065da1..801eaea8455 100644
--- a/apps/server/src/services/agentSignal/processors/actions.ts
+++ b/apps/server/src/services/agentSignal/processors/actions.ts
@@ -54,6 +54,12 @@ const getSerializedContext = (signal: SignalFeedbackDomainMemory | SignalFeedbac
: undefined;
};
+const getAssistantMessageId = (signal: SignalFeedbackDomainMemory | SignalFeedbackDomainSkill) =>
+ signal.payload.anchorMessageId ?? extractAssistantMessageIdFromSourceId(signal.source?.sourceId);
+
+const getTriggerMessageId = (signal: SignalFeedbackDomainMemory | SignalFeedbackDomainSkill) =>
+ signal.payload.triggerMessageId ?? signal.payload.messageId;
+
/**
* Plans a user-memory action from one memory feedback-domain signal.
*
@@ -86,7 +92,7 @@ export const planUserMemory = (signal: SignalFeedbackDomainMemory): ActionUserMe
// 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),
+ assistantMessageId: getAssistantMessageId(signal),
conflictPolicy: payload.conflictPolicy,
evidence: payload.evidence,
feedbackHint: payload.satisfactionResult === 'satisfied' ? 'satisfied' : 'not_satisfied',
@@ -97,6 +103,7 @@ export const planUserMemory = (signal: SignalFeedbackDomainMemory): ActionUserMe
serializedContext: getSerializedContext(signal),
sourceHints: payload.sourceHints,
topicId: payload.topicId,
+ triggerMessageId: getTriggerMessageId(signal),
},
signal: {
signalId: signal.signalId,
@@ -139,6 +146,7 @@ export const planSkillManagement = (
},
payload: {
agentId: payload.agentId,
+ assistantMessageId: getAssistantMessageId(signal),
conflictPolicy: payload.conflictPolicy,
evidence: payload.evidence,
feedbackHint: payload.satisfactionResult === 'satisfied' ? 'satisfied' : 'not_satisfied',
@@ -149,6 +157,7 @@ export const planSkillManagement = (
serializedContext: getSerializedContext(signal),
sourceHints: payload.sourceHints,
topicId: payload.topicId,
+ triggerMessageId: getTriggerMessageId(signal),
},
signal: {
signalId: signal.signalId,
diff --git a/apps/server/src/services/agentSignal/processors/classifiers.ts b/apps/server/src/services/agentSignal/processors/classifiers.ts
index f6c8fdeffdf..137a3c5f78f 100644
--- a/apps/server/src/services/agentSignal/processors/classifiers.ts
+++ b/apps/server/src/services/agentSignal/processors/classifiers.ts
@@ -143,6 +143,7 @@ const buildDomainSignal = (
},
payload: {
agentId: signal.payload.agentId,
+ anchorMessageId: signal.payload.anchorMessageId,
confidence: target.confidence,
conflictPolicy: toConflictPolicy('memory'),
evidence: resolveDomainEvidence(target, signal),
@@ -154,6 +155,7 @@ const buildDomainSignal = (
target: 'memory',
topicId: signal.payload.topicId,
trigger: signal.payload.trigger,
+ triggerMessageId: signal.payload.triggerMessageId,
},
signalId: `${signal.signalId}:domain:memory`,
signalType: AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainMemory,
@@ -170,6 +172,7 @@ const buildDomainSignal = (
},
payload: {
agentId: signal.payload.agentId,
+ anchorMessageId: signal.payload.anchorMessageId,
confidence: target.confidence,
conflictPolicy: toConflictPolicy('none'),
evidence: resolveDomainEvidence(target, signal),
@@ -181,6 +184,7 @@ const buildDomainSignal = (
target: 'none',
topicId: signal.payload.topicId,
trigger: signal.payload.trigger,
+ triggerMessageId: signal.payload.triggerMessageId,
},
signalId: `${signal.signalId}:domain:none`,
signalType: AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainNone,
@@ -197,6 +201,7 @@ const buildDomainSignal = (
},
payload: {
agentId: signal.payload.agentId,
+ anchorMessageId: signal.payload.anchorMessageId,
confidence: target.confidence,
conflictPolicy: toConflictPolicy('prompt'),
evidence: resolveDomainEvidence(target, signal),
@@ -208,6 +213,7 @@ const buildDomainSignal = (
target: 'prompt',
topicId: signal.payload.topicId,
trigger: signal.payload.trigger,
+ triggerMessageId: signal.payload.triggerMessageId,
},
signalId: `${signal.signalId}:domain:prompt`,
signalType: AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainPrompt,
@@ -224,6 +230,7 @@ const buildDomainSignal = (
},
payload: {
agentId: signal.payload.agentId,
+ anchorMessageId: signal.payload.anchorMessageId,
confidence: target.confidence,
conflictPolicy: toConflictPolicy('skill'),
evidence: resolveDomainEvidence(target, signal),
@@ -241,6 +248,7 @@ const buildDomainSignal = (
target: 'skill',
topicId: signal.payload.topicId,
trigger: signal.payload.trigger,
+ triggerMessageId: signal.payload.triggerMessageId,
},
signalId: `${signal.signalId}:domain:skill`,
signalType: AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainSkill,
@@ -321,6 +329,7 @@ export const classifySatisfaction = async (
},
payload: {
agentId: source.payload.agentId,
+ anchorMessageId: source.payload.anchorMessageId,
confidence: payload.confidence,
evidence: normalizeEvidence(payload.evidence),
message,
@@ -335,6 +344,7 @@ export const classifySatisfaction = async (
},
topicId: source.payload.topicId,
trigger: source.payload.trigger,
+ triggerMessageId: source.payload.triggerMessageId,
},
signalId: `${source.sourceId}:signal:feedback-satisfaction`,
signalType: AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackSatisfaction,
diff --git a/apps/server/src/services/agentSignal/sources/__tests__/index.test.ts b/apps/server/src/services/agentSignal/sources/__tests__/index.test.ts
index c5d4bd762ce..4382e475c1a 100644
--- a/apps/server/src/services/agentSignal/sources/__tests__/index.test.ts
+++ b/apps/server/src/services/agentSignal/sources/__tests__/index.test.ts
@@ -86,4 +86,27 @@ describe('agent signal sources', () => {
expect(built.sourceType).toBe('agent.execution.completed');
expect(built.payload.selfIteration).toEqual(selfIteration);
});
+
+ it('preserves agent user message display and trigger anchors through normalization', async () => {
+ const { buildSource } = await import('..');
+
+ const built = buildSource({
+ payload: {
+ agentId: 'agent_1',
+ anchorMessageId: 'assistant_1',
+ message: 'Remember this preference.',
+ messageId: 'user_1',
+ topicId: 'topic_1',
+ triggerMessageId: 'user_1',
+ },
+ scopeKey: 'topic:topic_1',
+ sourceId: 'assistant_1:completion:user_1',
+ sourceType: 'agent.user.message',
+ timestamp: 1_710_000_000_000,
+ });
+
+ expect(built.sourceType).toBe('agent.user.message');
+ expect(built.payload.anchorMessageId).toBe('assistant_1');
+ expect(built.payload.triggerMessageId).toBe('user_1');
+ });
});
diff --git a/apps/server/src/services/agentSignal/sources/renderers/agentUserMessage.ts b/apps/server/src/services/agentSignal/sources/renderers/agentUserMessage.ts
index aa26f50a3f5..6920b347965 100644
--- a/apps/server/src/services/agentSignal/sources/renderers/agentUserMessage.ts
+++ b/apps/server/src/services/agentSignal/sources/renderers/agentUserMessage.ts
@@ -9,6 +9,10 @@ export const agentUserMessageRenderer = {
...createBaseSource(input),
payload: {
agentId: typeof input.payload.agentId === 'string' ? input.payload.agentId : undefined,
+ anchorMessageId:
+ typeof input.payload.anchorMessageId === 'string'
+ ? input.payload.anchorMessageId
+ : undefined,
documentPayload:
input.payload.documentPayload && typeof input.payload.documentPayload === 'object'
? (input.payload.documentPayload as Record<string, unknown>)
@@ -46,6 +50,10 @@ export const agentUserMessageRenderer = {
threadId: typeof input.payload.threadId === 'string' ? input.payload.threadId : undefined,
topicId: typeof input.payload.topicId === 'string' ? input.payload.topicId : undefined,
trigger: typeof input.payload.trigger === 'string' ? input.payload.trigger : undefined,
+ triggerMessageId:
+ typeof input.payload.triggerMessageId === 'string'
+ ? input.payload.triggerMessageId
+ : undefined,
},
sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage,
};
diff --git a/src/routes/(main)/home/_layout/Header/components/AddButton.tsx b/src/routes/(main)/home/_layout/Header/components/AddButton.tsx
deleted file mode 100644
index 16efe11a252..00000000000
--- a/src/routes/(main)/home/_layout/Header/components/AddButton.tsx
+++ /dev/null
@@ -1,67 +0,0 @@
-import { ActionIcon, DropdownMenu, Flexbox, Tooltip } from '@lobehub/ui';
-import { CreateBotIcon } from '@lobehub/ui/icons';
-import { cssVar } from 'antd-style';
-import { ChevronDownIcon } from 'lucide-react';
-import React, { memo, useCallback, useMemo } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import { DESKTOP_HEADER_ICON_SIZE } from '@/const/layoutTokens';
-import { usePermission } from '@/hooks/usePermission';
-
-import { useCreateMenuItems } from '../../hooks';
-
-const AddButton = memo(() => {
- const { t: tChat } = useTranslation('chat');
- const { allowed: canCreate, reason } = usePermission('create_content');
-
- // Create menu items
- const { createTopLevelMenuItems, openCreateModal, isMutatingAgent, isCreatingGroup } =
- useCreateMenuItems();
-
- const handleMainIconClick = useCallback(
- (e: React.MouseEvent) => {
- e.stopPropagation();
- e.preventDefault();
- if (!canCreate) return;
- openCreateModal?.('agent');
- },
- [canCreate, openCreateModal],
- );
-
- const dropdownItems = useMemo(() => createTopLevelMenuItems(), [createTopLevelMenuItems]);
-
- // When viewer (no create_content): keep the icons visible per UX rule
- // (disabled-not-hidden), but the click handler short-circuits and the
- // dropdown is hidden (it would let users bypass the gate). Tooltip
- // surfaces the missing-permission reason.
- const mainIcon = (
- <ActionIcon
- disabled={!canCreate}
- icon={CreateBotIcon}
- loading={isMutatingAgent || isCreatingGroup}
- size={DESKTOP_HEADER_ICON_SIZE}
- title={canCreate ? tChat('newAgent') : undefined}
- onClick={handleMainIconClick}
- />
- );
-
- return (
- <Flexbox horizontal>
- {canCreate ? mainIcon : <Tooltip title={reason}>{mainIcon}</Tooltip>}
- {canCreate && (
- <DropdownMenu items={dropdownItems}>
- <ActionIcon
- color={cssVar.colorTextQuaternary}
- icon={ChevronDownIcon}
- size={{ blockSize: 32, size: 14 }}
- style={{
- width: 16,
- }}
- />
- </DropdownMenu>
- )}
- </Flexbox>
- );
-});
-
-export default AddButton;
diff --git a/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.tsx b/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.tsx
index c2e88483a7f..26febc0e4a3 100644
--- a/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.tsx
+++ b/src/routes/(main)/home/_layout/hooks/useCreateMenuItems.tsx
@@ -47,7 +47,7 @@ interface CreateAgentOptions {
/**
* Hook for generating menu items for top-level create actions
- * Used in Body/Agent/Actions.tsx and Header/AddButton.tsx
+ * Used by the home sidebar create menus.
*/
export const useCreateMenuItems = () => {
const { t } = useTranslation('chat');