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,app): anchor agent signal receipts to messages (#14969)

Nekof9b611bc6966
diff --git a/packages/agent-signal/src/source/sourceTypes.ts b/packages/agent-signal/src/source/sourceTypes.ts
index e3967212fd2..cd6329ac0aa 100644
--- a/packages/agent-signal/src/source/sourceTypes.ts
+++ b/packages/agent-signal/src/source/sourceTypes.ts
@@ -84,15 +84,20 @@ export interface AgentSignalSourcePayloadMap {
};
[AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage]: {
agentId?: string;
+ /** Message the receipt or UI should attach to, usually the assistant response. */
+ anchorMessageId?: string;
documentPayload?: Record<string, unknown>;
intents?: Array<'document' | 'memory' | 'persona' | 'prompt' | 'skill'>;
memoryPayload?: Record<string, unknown>;
message: string;
+ /** Legacy source message identifier kept for compatibility. */
messageId: string;
serializedContext?: string;
threadId?: string;
topicId?: string;
trigger?: string;
+ /** Message that initiated the source or run, usually the user message. */
+ triggerMessageId?: string;
};
[AGENT_SIGNAL_SOURCE_TYPES.botMessageMerged]: {
agentId?: string;
@@ -105,52 +110,81 @@ export interface AgentSignalSourcePayloadMap {
};
[AGENT_SIGNAL_SOURCE_TYPES.clientGatewayError]: {
agentId?: string;
+ /** Message the receipt or UI should attach to, usually the assistant response. */
+ anchorMessageId?: string;
+ /** Legacy assistant response identifier kept for compatibility. */
assistantMessageId?: string;
errorMessage?: string;
operationId: string;
serializedContext?: string;
topicId?: string;
+ /** Message that initiated the source or run, usually the user message. */
+ triggerMessageId?: string;
};
[AGENT_SIGNAL_SOURCE_TYPES.clientGatewayRuntimeEnd]: {
agentId?: string;
+ /** Message the receipt or UI should attach to, usually the assistant response. */
+ anchorMessageId?: string;
+ /** Legacy assistant response identifier kept for compatibility. */
assistantMessageId?: string;
operationId: string;
serializedContext?: string;
topicId?: string;
+ /** Message that initiated the source or run, usually the user message. */
+ triggerMessageId?: string;
};
[AGENT_SIGNAL_SOURCE_TYPES.clientGatewayStepComplete]: {
agentId?: string;
+ /** Message the receipt or UI should attach to, usually the assistant response. */
+ anchorMessageId?: string;
+ /** Legacy assistant response identifier kept for compatibility. */
assistantMessageId?: string;
operationId: string;
serializedContext?: string;
stepIndex: number;
topicId?: string;
+ /** Message that initiated the source or run, usually the user message. */
+ triggerMessageId?: string;
};
[AGENT_SIGNAL_SOURCE_TYPES.clientGatewayStreamStart]: {
agentId?: string;
+ /** Message the receipt or UI should attach to, usually the assistant response. */
+ anchorMessageId?: string;
+ /** Legacy assistant response identifier kept for compatibility. */
assistantMessageId?: string;
operationId: string;
serializedContext?: string;
stepIndex: number;
topicId?: string;
+ /** Message that initiated the source or run, usually the user message. */
+ triggerMessageId?: string;
};
[AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete]: {
agentId?: string;
+ /** Message the receipt or UI should attach to, usually the assistant response. */
+ anchorMessageId?: string;
+ /** Legacy assistant response identifier kept for compatibility. */
assistantMessageId?: string;
operationId: string;
serializedContext?: string;
status?: 'cancelled' | 'completed' | 'failed';
threadId?: string;
topicId?: string;
+ /** Message that initiated the source or run, usually the user message. */
+ triggerMessageId?: string;
};
[AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeStart]: {
agentId?: string;
+ /** Message the receipt or UI should attach to, usually the assistant response. */
+ anchorMessageId?: string;
operationId: string;
parentMessageId?: string;
parentMessageType?: string;
serializedContext?: string;
threadId?: string;
topicId?: string;
+ /** Message that initiated the source or run, usually the user message. */
+ triggerMessageId?: string;
};
[AGENT_SIGNAL_SOURCE_TYPES.runtimeAfterStep]: {
agentId?: string;
diff --git a/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.test.ts b/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.test.ts
index 1db448ce715..1d3631e3f95 100644
--- a/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.test.ts
+++ b/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.test.ts
@@ -1,3 +1,4 @@
+import type { UIChatMessage } from '@lobechat/types';
import { act, renderHook, waitFor } from '@testing-library/react';
import type { PropsWithChildren } from 'react';
import { createElement } from 'react';
@@ -34,6 +35,14 @@ vi.mock('@/services/agentSignal', () => ({
},
}));
+const message = (input: Partial<UIChatMessage> & { id: string; role: UIChatMessage['role'] }) =>
+ ({
+ content: '',
+ createdAt: 1,
+ updatedAt: 1,
+ ...input,
+ }) as UIChatMessage;
+
describe('useAgentSignalReceipts', () => {
const wrapper = ({ children }: PropsWithChildren) =>
createElement(SWRConfig, { value: { provider: () => new Map() } }, children);
@@ -43,11 +52,19 @@ describe('useAgentSignalReceipts', () => {
vi.useRealTimers();
});
- it('groups receipts by anchor and keeps unanchored receipts separate', async () => {
- const { result } = renderHook(
- () => useAgentSignalReceipts({ agentId: 'agent-1', enabled: true, topicId: 'topic-1' }),
- { wrapper },
- );
+ const renderReceiptsHook = (input: Parameters<typeof useAgentSignalReceipts>[0]) =>
+ renderHook(() => useAgentSignalReceipts(input), { wrapper });
+
+ it('groups anchored receipts by anchorMessageId', async () => {
+ const { result } = renderReceiptsHook({
+ agentId: 'agent-1',
+ displayMessages: [
+ message({ id: 'user-1', role: 'user' }),
+ message({ id: 'assistant-1', parentId: 'user-1', role: 'assistant' }),
+ ],
+ enabled: true,
+ topicId: 'topic-1',
+ });
await waitFor(() => {
expect(result.current.receiptsByAnchor.get('assistant-1')).toEqual([
@@ -61,11 +78,154 @@ describe('useAgentSignalReceipts', () => {
});
});
+ it('groups anchored receipts under the assistant group when the anchor is a child block', async () => {
+ vi.mocked(agentSignalService.listReceipts).mockResolvedValueOnce({
+ cursor: undefined,
+ receipts: [{ ...receipt, anchorMessageId: 'assistant-child-2', id: 'receipt-child-anchor' }],
+ });
+
+ const { result } = renderReceiptsHook({
+ agentId: 'agent-1',
+ displayMessages: [
+ message({ id: 'user-1', role: 'user' }),
+ message({
+ children: [
+ { content: 'First assistant step', id: 'assistant-child-1' },
+ { content: 'Final assistant step', id: 'assistant-child-2' },
+ ],
+ id: 'assistant-group-1',
+ parentId: 'user-1',
+ role: 'assistantGroup',
+ }),
+ ],
+ enabled: true,
+ topicId: 'topic-1',
+ });
+
+ await waitFor(() => {
+ expect(result.current.receiptsByAnchor.get('assistant-group-1')).toEqual([
+ expect.objectContaining({ id: 'receipt-child-anchor' }),
+ ]);
+ });
+ expect(result.current.receiptsByAnchor.get('assistant-child-2')).toBeUndefined();
+ });
+
+ it('groups trigger-only receipts under the assistant child message when present', async () => {
+ vi.mocked(agentSignalService.listReceipts).mockResolvedValueOnce({
+ cursor: undefined,
+ receipts: [
+ {
+ ...receipt,
+ anchorMessageId: undefined,
+ id: 'receipt-trigger',
+ triggerMessageId: 'user-1',
+ },
+ ],
+ });
+
+ const { result } = renderReceiptsHook({
+ agentId: 'agent-1',
+ displayMessages: [
+ message({ id: 'user-1', role: 'user' }),
+ message({ id: 'assistant-1', parentId: 'user-1', role: 'assistant' }),
+ ],
+ enabled: true,
+ topicId: 'topic-1',
+ });
+
+ await waitFor(() => {
+ expect(result.current.receiptsByAnchor.get('assistant-1')).toEqual([
+ expect.objectContaining({ id: 'receipt-trigger' }),
+ ]);
+ });
+ expect(result.current.receiptsByAnchor.get('user-1')).toBeUndefined();
+ });
+
+ it('groups trigger-only receipts under the assistant group child message when present', async () => {
+ vi.mocked(agentSignalService.listReceipts).mockResolvedValueOnce({
+ cursor: undefined,
+ receipts: [
+ {
+ ...receipt,
+ anchorMessageId: undefined,
+ id: 'receipt-trigger',
+ triggerMessageId: 'user-1',
+ },
+ ],
+ });
+
+ const { result } = renderReceiptsHook({
+ agentId: 'agent-1',
+ displayMessages: [
+ message({ id: 'user-1', role: 'user' }),
+ message({ id: 'assistant-group-1', parentId: 'user-1', role: 'assistantGroup' }),
+ ],
+ enabled: true,
+ topicId: 'topic-1',
+ });
+
+ await waitFor(() => {
+ expect(result.current.receiptsByAnchor.get('assistant-group-1')).toEqual([
+ expect.objectContaining({ id: 'receipt-trigger' }),
+ ]);
+ });
+ expect(result.current.receiptsByAnchor.get('user-1')).toBeUndefined();
+ });
+
+ it('groups trigger-only receipts under the trigger message when no assistant child exists', async () => {
+ vi.mocked(agentSignalService.listReceipts).mockResolvedValueOnce({
+ cursor: undefined,
+ receipts: [
+ {
+ ...receipt,
+ anchorMessageId: undefined,
+ id: 'receipt-trigger',
+ triggerMessageId: 'user-1',
+ },
+ ],
+ });
+
+ const { result } = renderReceiptsHook({
+ agentId: 'agent-1',
+ displayMessages: [message({ id: 'user-1', role: 'user' })],
+ enabled: true,
+ topicId: 'topic-1',
+ });
+
+ await waitFor(() => {
+ expect(result.current.receiptsByAnchor.get('user-1')).toEqual([
+ expect.objectContaining({ id: 'receipt-trigger' }),
+ ]);
+ });
+ });
+
+ it('does not group receipts without anchorMessageId or triggerMessageId', async () => {
+ vi.mocked(agentSignalService.listReceipts).mockResolvedValueOnce({
+ cursor: undefined,
+ receipts: [{ ...receipt, anchorMessageId: undefined, id: 'receipt-floating' }],
+ });
+
+ const { result } = renderReceiptsHook({
+ agentId: 'agent-1',
+ displayMessages: [message({ id: 'assistant-1', role: 'assistant' })],
+ enabled: true,
+ topicId: 'topic-1',
+ });
+
+ await waitFor(() => {
+ expect(agentSignalService.listReceipts).toHaveBeenCalled();
+ });
+ expect([...result.current.receiptsByAnchor.values()].flat()).toEqual([]);
+ expect('unanchoredReceipts' in result.current).toBe(false);
+ });
+
it('does not fetch receipts when the feature flag is disabled', async () => {
- renderHook(
- () => useAgentSignalReceipts({ agentId: 'agent-1', enabled: false, topicId: 'topic-1' }),
- { wrapper },
- );
+ renderReceiptsHook({
+ agentId: 'agent-1',
+ displayMessages: [],
+ enabled: false,
+ topicId: 'topic-1',
+ });
expect(agentSignalService.listReceipts).not.toHaveBeenCalled();
});
@@ -82,10 +242,12 @@ describe('useAgentSignalReceipts', () => {
receipts: [],
});
- renderHook(
- () => useAgentSignalReceipts({ agentId: 'agent-1', enabled: true, topicId: 'topic-1' }),
- { wrapper },
- );
+ renderReceiptsHook({
+ agentId: 'agent-1',
+ displayMessages: [],
+ enabled: true,
+ topicId: 'topic-1',
+ });
await act(async () => {
await Promise.resolve();
@@ -113,10 +275,12 @@ describe('useAgentSignalReceipts', () => {
receipts: [],
});
- renderHook(
- () => useAgentSignalReceipts({ agentId: 'agent-1', enabled: true, topicId: 'topic-1' }),
- { wrapper },
- );
+ renderReceiptsHook({
+ agentId: 'agent-1',
+ displayMessages: [],
+ enabled: true,
+ topicId: 'topic-1',
+ });
await act(async () => {
await Promise.resolve();
@@ -147,10 +311,12 @@ describe('useAgentSignalReceipts', () => {
receipts: [],
});
- renderHook(
- () => useAgentSignalReceipts({ agentId: 'agent-1', enabled: true, topicId: 'topic-1' }),
- { wrapper },
- );
+ renderReceiptsHook({
+ agentId: 'agent-1',
+ displayMessages: [],
+ enabled: true,
+ topicId: 'topic-1',
+ });
await act(async () => {
await Promise.resolve();
@@ -179,6 +345,7 @@ describe('useAgentSignalReceipts', () => {
({ pollingSignal }) =>
useAgentSignalReceipts({
agentId: 'agent-1',
+ displayMessages: [],
enabled: true,
pollingSignal,
topicId: 'topic-1',
diff --git a/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.ts b/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.ts
index 71d3bf24cbf..289f8b8b1fa 100644
--- a/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.ts
+++ b/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.ts
@@ -1,4 +1,5 @@
-import { useRef } from 'react';
+import type { UIChatMessage } from '@lobechat/types';
+import { useMemo, useRef } from 'react';
import useSWR from 'swr';
import { agentSignalService } from '@/services/agentSignal';
@@ -18,6 +19,7 @@ export type AgentSignalReceiptView = Awaited<
export const useAgentSignalReceipts = (input: {
agentId?: string | null;
+ displayMessages: UIChatMessage[];
enabled?: boolean;
pollingSignal?: string | null;
topicId?: string | null;
@@ -99,26 +101,94 @@ export const useAgentSignalReceipts = (input: {
const receipts = data?.receipts ?? [];
+ const receiptsByAnchor = useMemo(
+ () =>
+ groupAgentSignalReceiptsByEffectiveAnchor({
+ displayMessages: input.displayMessages,
+ receipts,
+ }),
+ [input.displayMessages, receipts],
+ );
+
+ return {
+ isLoading,
+ receiptsByAnchor,
+ };
+};
+
+interface GroupAgentSignalReceiptsByEffectiveAnchorInput {
+ displayMessages: UIChatMessage[];
+ receipts: AgentSignalReceiptView[];
+}
+
+const resolveAssistantReplyFromTrigger = (
+ triggerMessageId: string | undefined,
+ displayMessages: UIChatMessage[],
+) => {
+ if (!triggerMessageId) return undefined;
+
+ return displayMessages.find(
+ (message) =>
+ (message.role === 'assistant' || message.role === 'assistantGroup') &&
+ message.parentId === triggerMessageId,
+ )?.id;
+};
+
+const resolveDisplayedAnchorMessageId = (
+ anchorMessageId: string,
+ displayMessages: UIChatMessage[],
+) => {
+ if (displayMessages.some((message) => message.id === anchorMessageId)) return anchorMessageId;
+
+ return displayMessages.find(
+ (message) =>
+ message.role === 'assistantGroup' &&
+ message.children?.some((block) => block.id === anchorMessageId),
+ )?.id;
+};
+
+const resolveEffectiveAnchorMessageId = (
+ receipt: AgentSignalReceiptView,
+ displayMessages: UIChatMessage[],
+) => {
+ if (receipt.anchorMessageId) {
+ return resolveDisplayedAnchorMessageId(receipt.anchorMessageId, displayMessages);
+ }
+ if (!receipt.triggerMessageId) return undefined;
+
+ const assistantReplyId = resolveAssistantReplyFromTrigger(
+ receipt.triggerMessageId,
+ displayMessages,
+ );
+ 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.
+ return receipt.triggerMessageId;
+};
+
+const groupAgentSignalReceiptsByEffectiveAnchor = ({
+ displayMessages,
+ receipts,
+}: GroupAgentSignalReceiptsByEffectiveAnchorInput) => {
const receiptsByAnchor = new Map<string, AgentSignalReceiptView[]>();
- const unanchoredReceipts: AgentSignalReceiptView[] = [];
for (const receipt of receipts) {
- if (!receipt.anchorMessageId) {
- unanchoredReceipts.push(receipt);
- continue;
- }
+ const anchorMessageId = resolveEffectiveAnchorMessageId(receipt, displayMessages);
+ if (!anchorMessageId) continue;
- receiptsByAnchor.set(receipt.anchorMessageId, [
- ...(receiptsByAnchor.get(receipt.anchorMessageId) ?? []),
+ receiptsByAnchor.set(anchorMessageId, [
+ ...(receiptsByAnchor.get(anchorMessageId) ?? []),
receipt,
]);
}
- return {
- isLoading,
- receiptsByAnchor,
- unanchoredReceipts,
- };
+ return receiptsByAnchor;
};
const mergeReceiptRefresh = (
diff --git a/src/features/Conversation/ChatList/index.tsx b/src/features/Conversation/ChatList/index.tsx
index bfe80979164..b8ca65d4e70 100644
--- a/src/features/Conversation/ChatList/index.tsx
+++ b/src/features/Conversation/ChatList/index.tsx
@@ -80,6 +80,7 @@ const ChatList = memo<ChatListProps>(
const activeAgentId = useChatStore((s) => s.activeAgentId);
const { enableAgentSelfIteration } = useServerConfigStore(featureFlagsSelectors);
useFetchMessages(context, skipFetch);
+ const displayMessages = useConversationStore(dataSelectors.displayMessages);
const displayMessageIds = useConversationStore(dataSelectors.displayMessageIds);
const latestMessageId = displayMessageIds.at(-1);
@@ -87,8 +88,9 @@ const ChatList = memo<ChatListProps>(
const isSharePage = !!context.topicShareId;
// TODO: Migrate Agent Signal receipts behind a dedicated user-visible receipt capability.
const canShowAgentSignalReceipts = enableAgentSelfIteration === true && !isSharePage;
- const { receiptsByAnchor, unanchoredReceipts } = useAgentSignalReceipts({
+ const { receiptsByAnchor } = useAgentSignalReceipts({
agentId: canShowAgentSignalReceipts ? activeAgentId : undefined,
+ displayMessages,
enabled: canShowAgentSignalReceipts,
pollingSignal: latestMessageId,
topicId: canShowAgentSignalReceipts ? context.topicId : undefined,
@@ -105,13 +107,9 @@ const ChatList = memo<ChatListProps>(
(index: number, id: string) => {
const isLatestItem = displayMessageIds.length === index + 1;
const anchoredReceipts = receiptsByAnchor.get(id) ?? [];
- const latestUnanchoredReceipts = isLatestItem ? unanchoredReceipts : [];
const receiptRender =
- anchoredReceipts.length > 0 || latestUnanchoredReceipts.length > 0 ? (
- <>
- <AgentSignalReceiptList receipts={anchoredReceipts} />
- <AgentSignalReceiptList receipts={latestUnanchoredReceipts} />
- </>
+ anchoredReceipts.length > 0 ? (
+ <AgentSignalReceiptList receipts={anchoredReceipts} />
) : undefined;
return (
@@ -124,7 +122,7 @@ const ChatList = memo<ChatListProps>(
/>
);
},
- [displayMessageIds.length, defaultWorkflowExpandLevel, receiptsByAnchor, unanchoredReceipts],
+ [displayMessageIds.length, defaultWorkflowExpandLevel, receiptsByAnchor],
);
const messagesInit = useConversationStore(dataSelectors.messagesInit);
diff --git a/src/server/services/agentSignal/services/__tests__/receiptService.test.ts b/src/server/services/agentSignal/services/__tests__/receiptService.test.ts
index 7dc38fd9ed1..babff292efe 100644
--- a/src/server/services/agentSignal/services/__tests__/receiptService.test.ts
+++ b/src/server/services/agentSignal/services/__tests__/receiptService.test.ts
@@ -53,6 +53,99 @@ const result = (input: {
});
describe('projectAgentSignalReceipts', () => {
+ it('prefers anchorMessageId over assistantMessageId for receipt anchoring', () => {
+ const anchoredSource = createSource({
+ payload: {
+ agentId: 'agent-1',
+ anchorMessageId: 'assistant-anchor-1',
+ assistantMessageId: 'assistant-legacy-1',
+ topicId: 'topic-1',
+ },
+ scope: { topicId: 'topic-1', userId: 'user-1' },
+ scopeKey: 'topic:topic-1',
+ sourceId: 'source-anchor-1',
+ sourceType: 'client.runtime.complete',
+ timestamp: 1_700_000,
+ });
+
+ expect(
+ projectAgentSignalReceipts({
+ actions: [
+ action({
+ actionId: 'action-memory-1',
+ actionType: AGENT_SIGNAL_POLICY_ACTION_TYPES.userMemoryHandle,
+ payload: {},
+ }),
+ ],
+ results: [result({ actionId: 'action-memory-1', status: 'applied' })],
+ source: anchoredSource,
+ userId: 'user-1',
+ }),
+ ).toMatchObject([{ anchorMessageId: 'assistant-anchor-1' }]);
+ });
+
+ it('falls back to assistantMessageId for legacy receipt anchoring payloads', () => {
+ expect(
+ projectAgentSignalReceipts({
+ actions: [
+ action({
+ actionId: 'action-memory-1',
+ actionType: AGENT_SIGNAL_POLICY_ACTION_TYPES.userMemoryHandle,
+ payload: {},
+ }),
+ ],
+ results: [result({ actionId: 'action-memory-1', status: 'applied' })],
+ source,
+ userId: 'user-1',
+ }),
+ ).toMatchObject([{ anchorMessageId: 'assistant-1' }]);
+ });
+
+ it('projects triggerMessageId and falls back to messageId for legacy trigger payloads', () => {
+ const triggerSource = createSource({
+ payload: {
+ agentId: 'agent-1',
+ messageId: 'message-legacy-1',
+ topicId: 'topic-1',
+ triggerMessageId: 'message-trigger-1',
+ },
+ scope: { topicId: 'topic-1', userId: 'user-1' },
+ scopeKey: 'topic:topic-1',
+ sourceId: 'source-trigger-1',
+ sourceType: 'agent.user.message',
+ timestamp: 1_700_000,
+ });
+ const legacyTriggerSource = createSource({
+ payload: {
+ agentId: 'agent-1',
+ messageId: 'message-legacy-1',
+ topicId: 'topic-1',
+ },
+ scope: { topicId: 'topic-1', userId: 'user-1' },
+ scopeKey: 'topic:topic-1',
+ sourceId: 'source-trigger-2',
+ sourceType: 'agent.user.message',
+ timestamp: 1_700_000,
+ });
+
+ const project = (projectSource: typeof triggerSource) =>
+ projectAgentSignalReceipts({
+ actions: [
+ action({
+ actionId: 'action-memory-1',
+ actionType: AGENT_SIGNAL_POLICY_ACTION_TYPES.userMemoryHandle,
+ payload: {},
+ }),
+ ],
+ results: [result({ actionId: 'action-memory-1', status: 'applied' })],
+ source: projectSource,
+ userId: 'user-1',
+ });
+
+ expect(project(triggerSource)).toMatchObject([{ triggerMessageId: 'message-trigger-1' }]);
+ expect(project(legacyTriggerSource)).toMatchObject([{ triggerMessageId: 'message-legacy-1' }]);
+ });
+
it('projects applied memory action results without unstructured feedback as target', () => {
expect(
projectAgentSignalReceipts({
diff --git a/src/server/services/agentSignal/services/receiptService.ts b/src/server/services/agentSignal/services/receiptService.ts
index 5790210efbb..54f0f6eadb1 100644
--- a/src/server/services/agentSignal/services/receiptService.ts
+++ b/src/server/services/agentSignal/services/receiptService.ts
@@ -109,6 +109,8 @@ export interface AgentSignalReceipt {
title: string;
/** Topic where the receipt should be listed. */
topicId: string;
+ /** Message that triggered the Agent Signal source, when known. */
+ triggerMessageId?: string;
/** Owner used to enforce topic index isolation. */
userId: string;
}
@@ -539,6 +541,14 @@ export const projectAgentSignalReceipts = ({
if (!agentId || !topicId) return [];
const actionById = new Map(actions.map((action) => [action.actionId, action]));
+ const anchorMessageId =
+ getPayloadString(payload, 'anchorMessageId') ??
+ // TODO: Remove after producers stop emitting only assistantMessageId.
+ getPayloadString(payload, 'assistantMessageId');
+ const triggerMessageId =
+ getPayloadString(payload, 'triggerMessageId') ??
+ // TODO: Remove after producers stop emitting only messageId.
+ getPayloadString(payload, 'messageId');
return results.flatMap((result) => {
if (result.status !== 'applied') return [];
@@ -555,7 +565,7 @@ export const projectAgentSignalReceipts = ({
{
...visibleOutcome,
agentId,
- anchorMessageId: getPayloadString(payload, 'assistantMessageId'),
+ ...(anchorMessageId ? { anchorMessageId } : {}),
createdAt: source.timestamp,
id: `${source.sourceId}:${result.actionId}:${visibleOutcome.kind}`,
operationId: getPayloadString(payload, 'operationId'),
@@ -563,6 +573,7 @@ export const projectAgentSignalReceipts = ({
sourceType: source.sourceType,
topicId,
...(target ? { target } : {}),
+ ...(triggerMessageId ? { triggerMessageId } : {}),
userId,
},
];
diff --git a/src/server/services/agentSignal/sources/hydration/__tests__/clientRuntimeComplete.test.ts b/src/server/services/agentSignal/sources/hydration/__tests__/clientRuntimeComplete.test.ts
index 422c6a6ec70..46aa6c58e14 100644
--- a/src/server/services/agentSignal/sources/hydration/__tests__/clientRuntimeComplete.test.ts
+++ b/src/server/services/agentSignal/sources/hydration/__tests__/clientRuntimeComplete.test.ts
@@ -82,11 +82,13 @@ describe('resolveClientRuntimeCompleteFeedbackSource', () => {
expect(result.source).toEqual({
payload: {
agentId: 'client-agent',
+ anchorMessageId: assistantMessageId,
message: 'Please remember this workflow.',
messageId: parentMessageId,
threadId: 'client-thread',
topicId,
trigger: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete,
+ triggerMessageId: parentMessageId,
},
scopeKey: `topic:${topicId}`,
sourceId: `${assistantMessageId}:completion:${parentMessageId}`,
@@ -98,6 +100,58 @@ describe('resolveClientRuntimeCompleteFeedbackSource', () => {
DB_HYDRATION_TEST_TIMEOUT,
);
+ /**
+ * @example
+ * client.runtime.complete({ anchorMessageId, triggerMessageId }) keeps explicit message anchors.
+ */
+ it(
+ 'hydrates runtime complete with explicit anchorMessageId and triggerMessageId from the source payload',
+ async () => {
+ const db = await getTestDB();
+ const userId = `user_${uuid()}`;
+ const topicId = `topic_${uuid()}`;
+ const parentMessageId = `msg_${uuid()}`;
+ const assistantMessageId = `msg_${uuid()}`;
+ const anchorMessageId = `msg_${uuid()}`;
+ const triggerMessageId = `msg_${uuid()}`;
+
+ await db.insert(users).values({ id: userId });
+ await db.insert(topics).values({ id: topicId, title: 'Workflow Topic', userId });
+ await db.insert(messages).values({
+ content: 'Keep explicit completion anchors.',
+ id: parentMessageId,
+ role: 'user',
+ topicId,
+ userId,
+ });
+ await db.insert(messages).values({
+ content: 'Completion response.',
+ id: assistantMessageId,
+ parentId: parentMessageId,
+ role: 'assistant',
+ topicId,
+ userId,
+ });
+
+ const result = await resolveClientRuntimeCompleteFeedbackSource(
+ createCompleteSource({
+ anchorMessageId,
+ assistantMessageId,
+ triggerMessageId,
+ }),
+ { db, userId },
+ );
+
+ expect(result.source?.payload).toMatchObject({
+ anchorMessageId,
+ messageId: parentMessageId,
+ trigger: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete,
+ triggerMessageId,
+ });
+ },
+ DB_HYDRATION_TEST_TIMEOUT,
+ );
+
/**
* @example
* client.runtime.complete({}) cannot hydrate without an assistant message id.
diff --git a/src/server/services/agentSignal/sources/hydration/__tests__/clientRuntimeStart.test.ts b/src/server/services/agentSignal/sources/hydration/__tests__/clientRuntimeStart.test.ts
index 8d95ceb5e08..1b2d2cfc007 100644
--- a/src/server/services/agentSignal/sources/hydration/__tests__/clientRuntimeStart.test.ts
+++ b/src/server/services/agentSignal/sources/hydration/__tests__/clientRuntimeStart.test.ts
@@ -1,4 +1,5 @@
// @vitest-environment node
+import type { SourceEventClientRuntimeStart } from '@lobechat/agent-signal/source';
import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';
import { messages, topics, users } from '@lobechat/database/schemas';
import { getTestDB } from '@lobechat/database/test-utils';
@@ -8,6 +9,23 @@ import { uuid } from '@/utils/uuid';
import { resolveClientRuntimeStartFeedbackSource } from '../clientRuntimeStart';
+const createStartSource = (
+ payload: Partial<SourceEventClientRuntimeStart['payload']> = {},
+): SourceEventClientRuntimeStart => ({
+ payload: {
+ agentId: 'agent_1',
+ operationId: `op_${uuid()}`,
+ parentMessageId: `msg_${uuid()}`,
+ parentMessageType: 'user',
+ topicId: 'topic_1',
+ ...payload,
+ },
+ scopeKey: 'topic:topic_1',
+ sourceId: 'client:start',
+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeStart,
+ timestamp: Date.now(),
+});
+
describe('resolveClientRuntimeStartFeedbackSource', { timeout: 15_000 }, () => {
/**
* @example
@@ -85,10 +103,50 @@ describe('resolveClientRuntimeStartFeedbackSource', { timeout: 15_000 }, () => {
messageId,
topicId: 'topic_1',
trigger: 'client.runtime.start',
+ triggerMessageId: messageId,
});
+ expect(result.source?.payload.anchorMessageId).toBeUndefined();
expect(result.source?.payload.serializedContext).toBeUndefined();
});
+ /**
+ * @example
+ * client.runtime.start({ triggerMessageId }) keeps the explicit trigger instead of replacing it.
+ */
+ it('hydrates runtime start with the explicit triggerMessageId from the source payload', async () => {
+ const db = await getTestDB();
+ const userId = `user_${uuid()}`;
+ const topicId = `topic_${uuid()}`;
+ const messageId = `msg_${uuid()}`;
+ const triggerMessageId = `msg_${uuid()}`;
+
+ await db.insert(users).values({ id: userId });
+ await db.insert(topics).values({ id: topicId, title: 'Workflow Topic', userId });
+ await db.insert(messages).values({
+ content: 'Use the source trigger when it is present.',
+ id: messageId,
+ role: 'user',
+ topicId,
+ userId,
+ });
+
+ const result = await resolveClientRuntimeStartFeedbackSource(
+ createStartSource({
+ parentMessageId: messageId,
+ topicId,
+ triggerMessageId,
+ }),
+ { db, userId },
+ );
+
+ expect(result.source?.payload).toMatchObject({
+ messageId,
+ trigger: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeStart,
+ triggerMessageId,
+ });
+ expect(result.source?.payload.anchorMessageId).toBeUndefined();
+ });
+
/**
* @example
* client.runtime.start with mismatched client topic metadata uses trusted persisted topic and scope.
diff --git a/src/server/services/agentSignal/sources/hydration/clientRuntimeComplete.ts b/src/server/services/agentSignal/sources/hydration/clientRuntimeComplete.ts
index 3f5d007c150..4374f96602f 100644
--- a/src/server/services/agentSignal/sources/hydration/clientRuntimeComplete.ts
+++ b/src/server/services/agentSignal/sources/hydration/clientRuntimeComplete.ts
@@ -145,12 +145,14 @@ export const resolveClientRuntimeCompleteFeedbackSource = async (
source: {
payload: {
agentId: parentMessage.agentId ?? assistantMessage.agentId ?? sourceEvent.payload.agentId,
+ anchorMessageId: sourceEvent.payload.anchorMessageId ?? assistantMessage.id,
message: parentMessage.content,
messageId: parentMessage.id,
threadId:
parentMessage.threadId ?? assistantMessage.threadId ?? sourceEvent.payload.threadId,
topicId: trustedTopicId ?? sourceEvent.payload.topicId,
trigger: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete,
+ triggerMessageId: sourceEvent.payload.triggerMessageId ?? parentMessage.id,
},
scopeKey: getTrustedScopeKey(trustedTopicId, sourceEvent.scopeKey),
sourceId: getHydratedSourceId(assistantMessage.id, parentMessage.id),
diff --git a/src/server/services/agentSignal/sources/hydration/clientRuntimeStart.ts b/src/server/services/agentSignal/sources/hydration/clientRuntimeStart.ts
index 284cebc3636..25e1990199a 100644
--- a/src/server/services/agentSignal/sources/hydration/clientRuntimeStart.ts
+++ b/src/server/services/agentSignal/sources/hydration/clientRuntimeStart.ts
@@ -89,6 +89,7 @@ export const resolveClientRuntimeStartFeedbackSource = async (
threadId: parentMessage.threadId ?? sourceEvent.payload.threadId,
topicId: parentMessage.topicId ?? sourceEvent.payload.topicId,
trigger: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeStart,
+ triggerMessageId: sourceEvent.payload.triggerMessageId ?? parentMessage.id,
},
scopeKey: getTrustedScopeKey(parentMessage.topicId, sourceEvent.scopeKey),
sourceId: parentMessage.id,
diff --git a/src/server/services/agentSignal/store/__tests__/redisReceiptStore.test.ts b/src/server/services/agentSignal/store/__tests__/redisReceiptStore.test.ts
index 0b4eedc2518..8087c3403d3 100644
--- a/src/server/services/agentSignal/store/__tests__/redisReceiptStore.test.ts
+++ b/src/server/services/agentSignal/store/__tests__/redisReceiptStore.test.ts
@@ -37,6 +37,7 @@ const receipt = {
},
title: 'Memory saved',
topicId: 'topic-1',
+ triggerMessageId: 'user-message-1',
userId: 'user-1',
};
@@ -74,6 +75,7 @@ describe('redis receipt store', () => {
}),
title: 'Memory saved',
topicId: 'topic-1',
+ triggerMessageId: 'user-message-1',
userId: 'user-1',
});
expect(mockRedis.zadd).toHaveBeenCalledWith(
@@ -146,6 +148,23 @@ describe('redis receipt store', () => {
});
});
+ it('round-trips triggerMessageId with the receipt payload', async () => {
+ const store = await loadStore();
+
+ await store.appendReceipt(receipt, 259_200);
+
+ await expect(
+ store.listReceipts({ agentId: 'agent-1', limit: 10, topicId: 'topic-1', userId: 'user-1' }),
+ ).resolves.toMatchObject({
+ receipts: [
+ {
+ anchorMessageId: 'assistant-1',
+ triggerMessageId: 'user-message-1',
+ },
+ ],
+ });
+ });
+
it('lists receipts created after a known timestamp for refresh polling', async () => {
const store = await loadStore();
diff --git a/src/server/services/agentSignal/store/adapters/redis/receiptStore.ts b/src/server/services/agentSignal/store/adapters/redis/receiptStore.ts
index 61963922f1e..2e5bcb6396d 100644
--- a/src/server/services/agentSignal/store/adapters/redis/receiptStore.ts
+++ b/src/server/services/agentSignal/store/adapters/redis/receiptStore.ts
@@ -20,6 +20,7 @@ const toReceiptHash = (receipt: AgentSignalReceipt): Record<string, string> => (
...(receipt.target ? { target: JSON.stringify(receipt.target) } : {}),
title: receipt.title,
topicId: receipt.topicId,
+ ...(receipt.triggerMessageId ? { triggerMessageId: receipt.triggerMessageId } : {}),
userId: receipt.userId,
});
@@ -113,6 +114,7 @@ const fromReceiptHash = (payload: Record<string, string>): AgentSignalReceipt |
...(target ? { target } : {}),
title: payload.title,
topicId: payload.topicId,
+ triggerMessageId: payload.triggerMessageId,
userId: payload.userId,
};
};
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts
index a0ad1e41d03..2140c314184 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts
@@ -94,8 +94,10 @@ describe('createGatewayEventHandler', () => {
expect(emitClientAgentSignalSourceEvent).toHaveBeenCalledWith(
expect.objectContaining({
payload: expect.objectContaining({
+ anchorMessageId: 'msg-step2',
assistantMessageId: 'msg-step2',
operationId: 'op-1',
+ stepIndex: 0,
}),
sourceType: 'client.gateway.stream_start',
}),
@@ -639,6 +641,7 @@ describe('createGatewayEventHandler', () => {
expect(emitClientAgentSignalSourceEvent).toHaveBeenLastCalledWith(
expect.objectContaining({
payload: expect.objectContaining({
+ anchorMessageId: 'msg-step2',
assistantMessageId: 'msg-step2',
operationId: 'op-1',
}),
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts
index d94d9a60200..77c35111d25 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts
@@ -172,6 +172,17 @@ describe('StreamingExecutor actions', () => {
const operations = Object.values(result.current.operations);
const execOperation = operations.find((op) => op.type === 'execAgentRuntime');
expect(execOperation?.status).toBe('completed');
+ expect(agentSignalBridgeMock.emitClientAgentSignalSourceEvent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ payload: expect.objectContaining({
+ parentMessageId: userMessage.id,
+ parentMessageType: 'user',
+ triggerMessageId: userMessage.id,
+ }),
+ sourceId: `${execOperation?.id}:client:start`,
+ sourceType: 'client.runtime.start',
+ }),
+ );
streamSpy.mockRestore();
});
@@ -1719,9 +1730,11 @@ describe('StreamingExecutor actions', () => {
expect(agentSignalBridgeMock.emitClientAgentSignalSourceEvent).toHaveBeenCalledWith(
expect.objectContaining({
payload: expect.objectContaining({
+ anchorMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
operationId,
status: 'completed',
+ triggerMessageId: TEST_IDS.USER_MESSAGE_ID,
}),
sourceId: `${operationId}:client:complete`,
sourceType: 'client.runtime.complete',
@@ -1806,6 +1819,7 @@ describe('StreamingExecutor actions', () => {
expect(agentSignalBridgeMock.emitClientAgentSignalSourceEvent).toHaveBeenCalledWith(
expect.objectContaining({
payload: expect.objectContaining({
+ anchorMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
operationId,
status: 'completed',
@@ -1814,6 +1828,15 @@ describe('StreamingExecutor actions', () => {
sourceType: 'client.runtime.complete',
}),
);
+ expect(agentSignalBridgeMock.emitClientAgentSignalSourceEvent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ payload: expect.not.objectContaining({
+ triggerMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
+ }),
+ sourceId: `${operationId}:client:complete`,
+ sourceType: 'client.runtime.complete',
+ }),
+ );
});
it('does not attach an unrelated assistant message id to client.runtime.complete', async () => {
@@ -1968,9 +1991,11 @@ describe('StreamingExecutor actions', () => {
expect(agentSignalBridgeMock.emitClientAgentSignalSourceEvent).toHaveBeenCalledWith(
expect.objectContaining({
payload: expect.objectContaining({
+ anchorMessageId: 'assistant-final',
assistantMessageId: 'assistant-final',
operationId,
status: 'completed',
+ triggerMessageId: TEST_IDS.USER_MESSAGE_ID,
}),
sourceId: `${operationId}:client:complete`,
sourceType: 'client.runtime.complete',
diff --git a/src/store/chat/slices/aiChat/actions/agentSignalBridge.test.ts b/src/store/chat/slices/aiChat/actions/agentSignalBridge.test.ts
index 09bebebfa81..551644137d4 100644
--- a/src/store/chat/slices/aiChat/actions/agentSignalBridge.test.ts
+++ b/src/store/chat/slices/aiChat/actions/agentSignalBridge.test.ts
@@ -46,6 +46,7 @@ describe('emitClientAgentSignalSourceEvent', () => {
parentMessageType: 'user',
threadId: 'thread-1',
topicId: 'topic-1',
+ triggerMessageId: 'msg-1',
},
sourceId: 'op-1:client:start',
sourceType: 'client.runtime.start',
@@ -60,6 +61,7 @@ describe('emitClientAgentSignalSourceEvent', () => {
parentMessageType: 'user',
threadId: 'thread-1',
topicId: 'topic-1',
+ triggerMessageId: 'msg-1',
},
sourceId: 'op-1:client:start',
sourceType: 'client.runtime.start',
@@ -80,11 +82,13 @@ describe('emitClientAgentSignalSourceEvent', () => {
await emitClientAgentSignalSourceEvent({
payload: {
agentId: 'agent-1',
+ anchorMessageId: 'asst-1',
assistantMessageId: 'asst-1',
operationId: 'op-1',
status: 'completed',
threadId: 'thread-1',
topicId: 'topic-1',
+ triggerMessageId: 'msg-1',
},
sourceId: 'op-1:client:complete',
sourceType: 'client.runtime.complete',
@@ -94,11 +98,13 @@ describe('emitClientAgentSignalSourceEvent', () => {
expect(agentSignalService.emitClientGatewaySourceEvent).toHaveBeenCalledWith({
payload: {
agentId: 'agent-1',
+ anchorMessageId: 'asst-1',
assistantMessageId: 'asst-1',
operationId: 'op-1',
status: 'completed',
threadId: 'thread-1',
topicId: 'topic-1',
+ triggerMessageId: 'msg-1',
},
sourceId: 'op-1:client:complete',
sourceType: 'client.runtime.complete',
diff --git a/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts b/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts
index 323f40a5771..3bdefb1cf7e 100644
--- a/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts
+++ b/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts
@@ -301,7 +301,10 @@ export const createGatewayEventHandler = (
payload: {
agentId: context.agentId,
...(currentAssistantMessageId
- ? { assistantMessageId: currentAssistantMessageId }
+ ? {
+ anchorMessageId: currentAssistantMessageId,
+ assistantMessageId: currentAssistantMessageId,
+ }
: {}),
operationId,
stepIndex: event.stepIndex,
@@ -470,7 +473,10 @@ export const createGatewayEventHandler = (
payload: {
agentId: context.agentId,
...(currentAssistantMessageId
- ? { assistantMessageId: currentAssistantMessageId }
+ ? {
+ anchorMessageId: currentAssistantMessageId,
+ assistantMessageId: currentAssistantMessageId,
+ }
: {}),
operationId,
topicId: context.topicId ?? undefined,
diff --git a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
index ba949dd7bd5..6fbfefe2158 100644
--- a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
+++ b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
@@ -545,6 +545,7 @@ export class StreamingExecutorActionImpl {
parentMessageType,
threadId: threadId ?? undefined,
topicId: topicId ?? undefined,
+ ...(parentMessageType === 'user' ? { triggerMessageId: parentMessageId } : {}),
},
sourceId: `${operationId}:client:start`,
sourceType: 'client.runtime.start',
@@ -652,11 +653,13 @@ export class StreamingExecutorActionImpl {
void emitClientAgentSignalSourceEvent({
payload: {
agentId,
+ ...(assistantMessageId ? { anchorMessageId: assistantMessageId } : {}),
assistantMessageId,
operationId,
status: normalizeClientRuntimeCompleteStatus(state.status, operationStatus),
threadId: threadId ?? undefined,
topicId: topicId ?? undefined,
+ ...(parentMessageType === 'user' ? { triggerMessageId: parentMessageId } : {}),
},
sourceId: `${operationId}:client:complete`,
sourceType: 'client.runtime.complete',