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.

✨ feat(app,agent-signal): new agent recent activities to display for signal receipts triggered (#14407)

Neko317fdcec13b4
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 484eeac0b02..0440410020b 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -24,6 +24,11 @@
"agentProfile.knowledgeBases_other": "{{count}} 个知识库",
"agentProfile.skills_one": "{{count}} 项技能",
"agentProfile.skills_other": "{{count}} 项技能",
+ "agentSignal.receipts.memory.detail": "已保存,后续回复会参考",
+ "agentSignal.receipts.memory.title": "记忆已保存",
+ "agentSignal.receipts.recentActivity": "近期活动",
+ "agentSignal.receipts.skill.detail": "已改进这个助理处理类似请求的方式",
+ "agentSignal.receipts.skill.title": "技能已更新",
"agents": "助理",
"artifact.generating": "生成中",
"artifact.inThread": "子话题中暂不支持查看。请回到主对话区打开",
diff --git a/packages/agent-signal/src/source/sourceTypes.ts b/packages/agent-signal/src/source/sourceTypes.ts
index 7a543f4ba75..b2f45c4cb0e 100644
--- a/packages/agent-signal/src/source/sourceTypes.ts
+++ b/packages/agent-signal/src/source/sourceTypes.ts
@@ -65,6 +65,7 @@ export interface AgentSignalSourcePayloadMap {
};
[AGENT_SIGNAL_SOURCE_TYPES.clientGatewayError]: {
agentId?: string;
+ assistantMessageId?: string;
errorMessage?: string;
operationId: string;
serializedContext?: string;
@@ -72,12 +73,14 @@ export interface AgentSignalSourcePayloadMap {
};
[AGENT_SIGNAL_SOURCE_TYPES.clientGatewayRuntimeEnd]: {
agentId?: string;
+ assistantMessageId?: string;
operationId: string;
serializedContext?: string;
topicId?: string;
};
[AGENT_SIGNAL_SOURCE_TYPES.clientGatewayStepComplete]: {
agentId?: string;
+ assistantMessageId?: string;
operationId: string;
serializedContext?: string;
stepIndex: number;
@@ -85,6 +88,7 @@ export interface AgentSignalSourcePayloadMap {
};
[AGENT_SIGNAL_SOURCE_TYPES.clientGatewayStreamStart]: {
agentId?: string;
+ assistantMessageId?: string;
operationId: string;
serializedContext?: string;
stepIndex: number;
diff --git a/src/features/Conversation/ChatList/components/AgentSignalReceiptList.test.tsx b/src/features/Conversation/ChatList/components/AgentSignalReceiptList.test.tsx
new file mode 100644
index 00000000000..eef92a41bc1
--- /dev/null
+++ b/src/features/Conversation/ChatList/components/AgentSignalReceiptList.test.tsx
@@ -0,0 +1,169 @@
+import { fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import AgentSignalReceiptList from './AgentSignalReceiptList';
+
+const mocks = vi.hoisted(() => ({
+ navigate: vi.fn(),
+ openDocument: vi.fn(),
+}));
+
+vi.mock('@/hooks/useStableNavigate', () => ({
+ useStableNavigate: () => mocks.navigate,
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (state: { openDocument: (documentId: string) => void }) => unknown) =>
+ selector({ openDocument: mocks.openDocument }),
+}));
+
+describe('AgentSignalReceiptList', () => {
+ afterEach(() => {
+ mocks.navigate.mockReset();
+ mocks.openDocument.mockReset();
+ });
+
+ it('renders visible memory and skill receipts', () => {
+ render(
+ <AgentSignalReceiptList
+ receipts={[
+ {
+ agentId: 'agent-1',
+ createdAt: 1,
+ detail: 'Saved this for future replies',
+ id: 'receipt-1',
+ kind: 'memory',
+ sourceId: 'source-1',
+ sourceType: 'client.gateway.runtime_end',
+ status: 'applied',
+ target: {
+ summary: 'Use decision-first PR reviews in future chats',
+ title: 'Decision-first PR review preference',
+ type: 'memory',
+ },
+ title: 'Memory saved',
+ topicId: 'topic-1',
+ userId: 'user-1',
+ },
+ {
+ agentId: 'agent-1',
+ createdAt: 2,
+ detail: 'Improved how this assistant handles similar requests',
+ id: 'receipt-2',
+ kind: 'skill',
+ sourceId: 'source-2',
+ sourceType: 'client.gateway.runtime_end',
+ status: 'updated',
+ target: {
+ id: 'agent-document-1',
+ summary: 'Review metadata, diff, merge status, blockers, and risks',
+ title: 'GitHub PR review workflow',
+ type: 'skill',
+ },
+ title: 'Skill updated',
+ topicId: 'topic-1',
+ userId: 'user-1',
+ },
+ ]}
+ />,
+ );
+
+ expect(screen.getByText('Decision-first PR review preference')).toBeInTheDocument();
+ expect(screen.getByText('GitHub PR review workflow')).toBeInTheDocument();
+ expect(screen.getByText('Memory saved')).toBeInTheDocument();
+ expect(screen.getByText('Skill updated')).toBeInTheDocument();
+ });
+
+ it('collapses recent activity receipts from the label', () => {
+ render(
+ <AgentSignalReceiptList
+ showRecentLabel
+ receipts={[
+ {
+ agentId: 'agent-1',
+ createdAt: 1,
+ detail: 'Saved this for future replies',
+ id: 'receipt-1',
+ kind: 'memory',
+ sourceId: 'source-1',
+ sourceType: 'client.gateway.runtime_end',
+ status: 'applied',
+ target: {
+ summary: 'Saved this for future replies',
+ title: 'Future reply preference',
+ type: 'memory',
+ },
+ title: 'Memory saved',
+ topicId: 'topic-1',
+ userId: 'user-1',
+ },
+ ]}
+ />,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: 'agentSignal.receipts.recentActivity' }));
+
+ expect(screen.queryByText('Future reply preference')).not.toBeInTheDocument();
+ });
+
+ it('opens skill target documents from a receipt item', () => {
+ render(
+ <AgentSignalReceiptList
+ receipts={[
+ {
+ agentId: 'agent-1',
+ createdAt: 1,
+ detail: 'Improved how this assistant handles similar requests',
+ id: 'receipt-1',
+ kind: 'skill',
+ sourceId: 'source-1',
+ sourceType: 'client.gateway.runtime_end',
+ status: 'updated',
+ target: {
+ id: 'document-1',
+ title: 'GitHub PR review workflow',
+ type: 'skill',
+ },
+ title: 'Skill updated',
+ topicId: 'topic-1',
+ userId: 'user-1',
+ },
+ ]}
+ />,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: /GitHub PR review workflow/ }));
+
+ expect(mocks.openDocument).toHaveBeenCalledWith('document-1');
+ });
+
+ it('navigates memory receipts to the memory surface', () => {
+ render(
+ <AgentSignalReceiptList
+ receipts={[
+ {
+ agentId: 'agent-1',
+ createdAt: 1,
+ detail: 'Saved this for future replies',
+ id: 'receipt-1',
+ kind: 'memory',
+ sourceId: 'source-1',
+ sourceType: 'client.gateway.runtime_end',
+ status: 'applied',
+ target: {
+ title: 'Decision-first PR review preference',
+ type: 'memory',
+ },
+ title: 'Memory saved',
+ topicId: 'topic-1',
+ userId: 'user-1',
+ },
+ ]}
+ />,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: /Decision-first PR review preference/ }));
+
+ expect(mocks.navigate).toHaveBeenCalledWith('/memory');
+ });
+});
diff --git a/src/features/Conversation/ChatList/components/AgentSignalReceiptList.tsx b/src/features/Conversation/ChatList/components/AgentSignalReceiptList.tsx
new file mode 100644
index 00000000000..23331f154e1
--- /dev/null
+++ b/src/features/Conversation/ChatList/components/AgentSignalReceiptList.tsx
@@ -0,0 +1,221 @@
+'use client';
+
+import { Block, Flexbox, Icon, Tooltip } from '@lobehub/ui';
+import { createStyles } from 'antd-style';
+import { Activity, CheckCircle, ChevronRight, Sparkles } from 'lucide-react';
+import { AnimatePresence, m as motion } from 'motion/react';
+import { memo, useCallback, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useStableNavigate } from '@/hooks/useStableNavigate';
+import { useChatStore } from '@/store/chat';
+
+import type { AgentSignalReceiptView } from '../hooks/useAgentSignalReceipts';
+
+const PAGE_ROUTE_PATTERN = /^\/agent\/([^/]+)\/([^/]+)\/page(?:\/[^/?#]+)?/;
+
+const useStyles = createStyles(({ css, token }) => ({
+ content: css`
+ overflow: hidden;
+ `,
+ item: css`
+ width: 100%;
+ padding-block: 6px;
+ padding-inline: 8px;
+ border: 1px solid ${token.colorBorderSecondary};
+ border-radius: 8px;
+
+ font-size: 12px;
+ line-height: 1.45;
+ color: ${token.colorTextSecondary};
+
+ background: ${token.colorFillQuaternary};
+ `,
+ itemButton: css`
+ cursor: pointer;
+
+ display: flex;
+ gap: 8px;
+ align-items: center;
+
+ width: 100%;
+ padding: 0;
+ border: 0;
+
+ color: inherit;
+ text-align: start;
+
+ background: transparent;
+ `,
+ label: css`
+ cursor: pointer;
+
+ display: flex;
+ gap: 6px;
+ align-items: center;
+
+ width: fit-content;
+ max-width: min(520px, 100%);
+ margin-block-start: 4px;
+ padding: 0;
+ border: 0;
+
+ font-size: 12px;
+ line-height: 1.45;
+ color: ${token.colorTextTertiary};
+
+ background: transparent;
+ `,
+ labelText: css`
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ labelIcon: css`
+ transition: transform 120ms ease;
+ `,
+ labelIconOpen: css`
+ transform: rotate(90deg);
+ `,
+ title: css`
+ font-weight: 500;
+ color: ${token.colorText};
+ `,
+ titleGroup: css`
+ overflow: hidden;
+ min-width: 0;
+ `,
+}));
+
+const collapseTransition = {
+ duration: 0.16,
+ ease: [0.4, 0, 0.2, 1],
+} as const;
+
+interface AgentSignalReceiptListProps {
+ receipts: AgentSignalReceiptView[];
+ showRecentLabel?: boolean;
+}
+
+interface AgentSignalReceiptItemProps {
+ receipt: AgentSignalReceiptView;
+}
+
+const AgentSignalReceiptItem = memo<AgentSignalReceiptItemProps>(({ receipt }) => {
+ const { styles } = useStyles();
+ const { t } = useTranslation('chat');
+ const navigate = useStableNavigate();
+ const openDocument = useChatStore((s) => s.openDocument);
+ const ReceiptIcon = receipt.kind === 'memory' ? CheckCircle : Sparkles;
+ const fallbackTitle = t(`agentSignal.receipts.${receipt.kind}.title`, receipt.title);
+ const title = receipt.target?.title ?? fallbackTitle;
+ const detail = t(`agentSignal.receipts.${receipt.kind}.detail`, receipt.detail);
+ const summary = receipt.target?.summary ?? detail;
+ const tooltip = `${fallbackTitle}: ${summary}`;
+ const target = receipt.target;
+ const handleOpen = useCallback(() => {
+ if (target?.type === 'memory') {
+ navigate('/memory');
+ return;
+ }
+
+ if (target?.type !== 'skill' || !target.id) return;
+
+ const pathname = globalThis.location?.pathname ?? '';
+ const pageMatch = PAGE_ROUTE_PATTERN.exec(pathname);
+
+ if (pageMatch?.[1] && pageMatch[2]) {
+ navigate(`/agent/${pageMatch[1]}/${pageMatch[2]}/page/${target.id}`);
+ return;
+ }
+
+ openDocument(target.id);
+ }, [navigate, openDocument, target]);
+
+ return (
+ <div className={styles.item}>
+ <Tooltip placement={'topLeft'} title={tooltip}>
+ <button
+ className={styles.itemButton}
+ type={'button'}
+ // TODO: Replace memory fallback with category/id-aware routes when Agent Signal receipts expose them.
+ onClick={handleOpen}
+ >
+ <Block
+ horizontal
+ align={'center'}
+ flex={'none'}
+ height={24}
+ justify={'center'}
+ style={{ fontSize: 12 }}
+ variant={'outlined'}
+ width={24}
+ >
+ <Icon icon={ReceiptIcon} />
+ </Block>
+ <Flexbox className={styles.titleGroup}>
+ <span className={styles.title}>{title}</span>
+ <span className={styles.labelText}>{fallbackTitle}</span>
+ </Flexbox>
+ </button>
+ </Tooltip>
+ </div>
+ );
+});
+
+AgentSignalReceiptItem.displayName = 'AgentSignalReceiptItem';
+
+const AgentSignalReceiptList = memo<AgentSignalReceiptListProps>(
+ ({ receipts, showRecentLabel }) => {
+ const { styles } = useStyles();
+ const { t } = useTranslation('chat');
+ const [open, setOpen] = useState(true);
+
+ if (receipts.length === 0) return null;
+
+ // TODO: Migrate this temporary receipt UI into the final Agent Signal feedback surface.
+ return (
+ <Flexbox gap={4}>
+ {showRecentLabel && (
+ <button className={styles.label} type={'button'} onClick={() => setOpen(!open)}>
+ <Block
+ horizontal
+ align={'center'}
+ flex={'none'}
+ height={24}
+ justify={'center'}
+ style={{ fontSize: 12 }}
+ variant={'outlined'}
+ width={24}
+ >
+ <Icon icon={Activity} />
+ </Block>
+ <span className={styles.labelText}>{t('agentSignal.receipts.recentActivity')}</span>
+ <Icon className={open ? styles.labelIconOpen : styles.labelIcon} icon={ChevronRight} />
+ </button>
+ )}
+ <AnimatePresence initial={false}>
+ {(!showRecentLabel || open) && (
+ <motion.div
+ animate={{ height: 'auto', opacity: 1 }}
+ className={styles.content}
+ exit={{ height: 0, opacity: 0 }}
+ initial={{ height: 0, opacity: 0 }}
+ transition={collapseTransition}
+ >
+ <Flexbox gap={4}>
+ {receipts.map((receipt) => (
+ <AgentSignalReceiptItem key={receipt.id} receipt={receipt} />
+ ))}
+ </Flexbox>
+ </motion.div>
+ )}
+ </AnimatePresence>
+ </Flexbox>
+ );
+ },
+);
+
+AgentSignalReceiptList.displayName = 'AgentSignalReceiptList';
+
+export default AgentSignalReceiptList;
diff --git a/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.test.ts b/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.test.ts
new file mode 100644
index 00000000000..89a4f2e6572
--- /dev/null
+++ b/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.test.ts
@@ -0,0 +1,46 @@
+import { renderHook, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { agentSignalService } from '@/services/agentSignal';
+
+import { useAgentSignalReceipts } from './useAgentSignalReceipts';
+
+vi.mock('@/services/agentSignal', () => ({
+ agentSignalService: {
+ listReceipts: vi.fn().mockResolvedValue({
+ cursor: undefined,
+ receipts: [{ anchorMessageId: 'assistant-1', id: 'receipt-1', kind: 'memory' }],
+ }),
+ },
+}));
+
+describe('useAgentSignalReceipts', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('groups receipts by anchor and keeps unanchored receipts separate', async () => {
+ const { result } = renderHook(() =>
+ useAgentSignalReceipts({ agentId: 'agent-1', enabled: true, topicId: 'topic-1' }),
+ );
+
+ await waitFor(() => {
+ expect(result.current.receiptsByAnchor.get('assistant-1')).toEqual([
+ expect.objectContaining({ id: 'receipt-1' }),
+ ]);
+ });
+ expect(agentSignalService.listReceipts).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ limit: 20,
+ topicId: 'topic-1',
+ });
+ });
+
+ it('does not fetch receipts when the feature flag is disabled', async () => {
+ renderHook(() =>
+ useAgentSignalReceipts({ agentId: 'agent-1', enabled: false, topicId: 'topic-1' }),
+ );
+
+ expect(agentSignalService.listReceipts).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.ts b/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.ts
new file mode 100644
index 00000000000..4634cba744c
--- /dev/null
+++ b/src/features/Conversation/ChatList/hooks/useAgentSignalReceipts.ts
@@ -0,0 +1,51 @@
+import useSWR from 'swr';
+
+import { agentSignalService } from '@/services/agentSignal';
+
+export type AgentSignalReceiptView = Awaited<
+ ReturnType<typeof agentSignalService.listReceipts>
+>['receipts'][number];
+
+export const useAgentSignalReceipts = (input: {
+ agentId?: string | null;
+ enabled?: boolean;
+ topicId?: string | null;
+}) => {
+ // TODO: Migrate Agent Signal receipt visibility to a dedicated product capability flag.
+ const shouldFetch = input.enabled === true && Boolean(input.agentId && input.topicId);
+ const { data, isLoading } = useSWR(
+ shouldFetch ? ['agentSignalReceipts', input.agentId, input.topicId] : null,
+ () =>
+ agentSignalService.listReceipts({
+ agentId: input.agentId!,
+ limit: 20,
+ topicId: input.topicId!,
+ }),
+ {
+ revalidateOnFocus: false,
+ },
+ );
+
+ const receipts = data?.receipts ?? [];
+
+ const receiptsByAnchor = new Map<string, AgentSignalReceiptView[]>();
+ const unanchoredReceipts: AgentSignalReceiptView[] = [];
+
+ for (const receipt of receipts) {
+ if (!receipt.anchorMessageId) {
+ unanchoredReceipts.push(receipt);
+ continue;
+ }
+
+ receiptsByAnchor.set(receipt.anchorMessageId, [
+ ...(receiptsByAnchor.get(receipt.anchorMessageId) ?? []),
+ receipt,
+ ]);
+ }
+
+ return {
+ isLoading,
+ receiptsByAnchor,
+ unanchoredReceipts,
+ };
+};
diff --git a/src/features/Conversation/ChatList/index.tsx b/src/features/Conversation/ChatList/index.tsx
index 18b35927f16..f0b97651bae 100644
--- a/src/features/Conversation/ChatList/index.tsx
+++ b/src/features/Conversation/ChatList/index.tsx
@@ -7,6 +7,7 @@ import { useFetchAgentDocuments } from '@/hooks/useFetchAgentDocuments';
import { useFetchTopicMemories } from '@/hooks/useFetchMemoryForTopic';
import { useFetchNotebookDocuments } from '@/hooks/useFetchNotebookDocuments';
import { useChatStore } from '@/store/chat';
+import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
import { useUserStore } from '@/store/user';
import { settingsSelectors } from '@/store/user/selectors';
@@ -16,7 +17,9 @@ import MessageItem from '../Messages';
import type { WorkflowExpandLevelDefault } from '../Messages/AssistantGroup/components/WorkflowCollapse';
import { MessageActionProvider } from '../Messages/Contexts/MessageActionProvider';
import { dataSelectors, useConversationStore } from '../store';
+import AgentSignalReceiptList from './components/AgentSignalReceiptList';
import VirtualizedList from './components/VirtualizedList';
+import { useAgentSignalReceipts } from './hooks/useAgentSignalReceipts';
export interface ChatListProps {
/**
@@ -62,10 +65,18 @@ const ChatList = memo<ChatListProps>(
s.useFetchMessages,
]);
const activeAgentId = useChatStore((s) => s.activeAgentId);
+ const { enableAgentSelfIteration } = useServerConfigStore(featureFlagsSelectors);
useFetchMessages(context, skipFetch);
// Skip fetching notebook and memories for share pages (they require authentication)
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({
+ agentId: canShowAgentSignalReceipts ? activeAgentId : undefined,
+ enabled: canShowAgentSignalReceipts,
+ topicId: canShowAgentSignalReceipts ? context.topicId : undefined,
+ });
// Fetch notebook documents when topic is selected (skip for share pages)
useFetchAgentDocuments(isSharePage ? undefined : activeAgentId);
@@ -79,16 +90,27 @@ const ChatList = memo<ChatListProps>(
const defaultItemContent = useCallback(
(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 showRecentLabel receipts={latestUnanchoredReceipts} />
+ </>
+ ) : undefined;
+
return (
<MessageItem
defaultWorkflowExpandLevel={defaultWorkflowExpandLevel}
+ endRender={receiptRender}
id={id}
index={index}
isLatestItem={isLatestItem}
/>
);
},
- [displayMessageIds.length, defaultWorkflowExpandLevel],
+ [displayMessageIds.length, defaultWorkflowExpandLevel, receiptsByAnchor, unanchoredReceipts],
);
const messagesInit = useConversationStore(dataSelectors.messagesInit);
diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.ts
index 3272874fbdb..6f42e6e8fe8 100644
--- a/src/locales/default/chat.ts
+++ b/src/locales/default/chat.ts
@@ -32,6 +32,11 @@ export default {
'agentProfile.knowledgeBases_other': '{{count}} knowledge bases',
'agentProfile.skills_one': '{{count}} skill',
'agentProfile.skills_other': '{{count}} skills',
+ 'agentSignal.receipts.memory.detail': 'Saved this for future replies',
+ 'agentSignal.receipts.memory.title': 'Memory saved',
+ 'agentSignal.receipts.recentActivity': 'Recent activity',
+ 'agentSignal.receipts.skill.detail': 'Improved how this assistant handles similar requests',
+ 'agentSignal.receipts.skill.title': 'Skill updated',
'agents': 'Agents',
'artifact.generating': 'Generating',
'artifact.inThread':
diff --git a/src/server/routers/lambda/agentSignal.test.ts b/src/server/routers/lambda/agentSignal.test.ts
index a5059a8d5f7..8a3ed32dda4 100644
--- a/src/server/routers/lambda/agentSignal.test.ts
+++ b/src/server/routers/lambda/agentSignal.test.ts
@@ -5,6 +5,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { createCallerFactory } from '@/libs/trpc/lambda';
import { type AuthContext } from '@/libs/trpc/lambda/context';
import { createContextInner } from '@/libs/trpc/lambda/context';
+import { listAgentSignalReceipts } from '@/server/services/agentSignal/services/receiptService';
import { agentSignalRouter } from './agentSignal';
@@ -18,6 +19,28 @@ vi.mock('@/server/services/agentSignal', () => ({
.mockResolvedValue({ accepted: true, scopeKey: 'topic:topic-1', workflowRunId: 'wfr_1' }),
}));
+vi.mock('@/server/services/agentSignal/services/receiptService', () => ({
+ listAgentSignalReceipts: vi.fn().mockResolvedValue({
+ cursor: undefined,
+ receipts: [
+ {
+ agentId: 'agent-1',
+ anchorMessageId: 'assistant-1',
+ createdAt: 1_700_000,
+ detail: 'Saved this for future replies',
+ id: 'receipt-1',
+ kind: 'memory',
+ sourceId: 'source-1',
+ sourceType: 'client.gateway.runtime_end',
+ status: 'applied',
+ title: 'Memory saved',
+ topicId: 'topic-1',
+ userId: 'user-1',
+ },
+ ],
+ }),
+}));
+
const createCaller = createCallerFactory(agentSignalRouter);
describe('agentSignalRouter', () => {
@@ -60,4 +83,28 @@ describe('agentSignalRouter', () => {
}),
).rejects.toBeInstanceOf(TRPCError);
});
+
+ it('lists receipts for the current user topic', async () => {
+ await expect(
+ router.listReceipts({ agentId: 'agent-1', limit: 20, topicId: 'topic-1' }),
+ ).resolves.toEqual({
+ cursor: undefined,
+ receipts: [
+ expect.objectContaining({
+ agentId: 'agent-1',
+ id: 'receipt-1',
+ kind: 'memory',
+ topicId: 'topic-1',
+ }),
+ ],
+ });
+
+ expect(listAgentSignalReceipts).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ cursor: undefined,
+ limit: 20,
+ topicId: 'topic-1',
+ userId: 'user-1',
+ });
+ });
});
diff --git a/src/server/routers/lambda/agentSignal.ts b/src/server/routers/lambda/agentSignal.ts
index 60d922fcf81..ebdd430b2fd 100644
--- a/src/server/routers/lambda/agentSignal.ts
+++ b/src/server/routers/lambda/agentSignal.ts
@@ -7,6 +7,7 @@ import { z } from 'zod';
import { authedProcedure, router } from '@/libs/trpc/lambda';
import { enqueueAgentSignalSourceEvent } from '@/server/services/agentSignal';
+import { listAgentSignalReceipts } from '@/server/services/agentSignal/services/receiptService';
const log = debug('lobe-server:agent-signal:router');
@@ -43,4 +44,22 @@ export const agentSignalRouter = router({
userId: ctx.userId,
});
}),
+ listReceipts: agentSignalProcedure
+ .input(
+ z.object({
+ agentId: z.string().min(1),
+ cursor: z.number().int().min(0).optional(),
+ limit: z.number().int().min(1).max(50).default(20),
+ topicId: z.string().min(1),
+ }),
+ )
+ .query(async ({ ctx, input }) => {
+ return listAgentSignalReceipts({
+ agentId: input.agentId,
+ cursor: input.cursor,
+ limit: input.limit,
+ topicId: input.topicId,
+ userId: ctx.userId,
+ });
+ }),
});
diff --git a/src/server/services/agentSignal/constants.ts b/src/server/services/agentSignal/constants.ts
index 8e71f9d5bad..b2131013229 100644
--- a/src/server/services/agentSignal/constants.ts
+++ b/src/server/services/agentSignal/constants.ts
@@ -7,6 +7,10 @@ export const AGENT_SIGNAL_KEYS = {
lock: (scopeKey: string) => `${AGENT_SIGNAL_PREFIX}lock:${scopeKey}`,
policy: (policyId: string, scopeKey: string) =>
`${AGENT_SIGNAL_PREFIX}policy:${policyId}:${scopeKey}`,
+ receipt: (receiptId: string) => `${AGENT_SIGNAL_PREFIX}receipt:${receiptId}`,
+ receiptDedupe: (receiptId: string) => `${AGENT_SIGNAL_PREFIX}receipt-dedupe:${receiptId}`,
+ receiptIndex: (input: { agentId: string; topicId: string; userId: string }) =>
+ `${AGENT_SIGNAL_PREFIX}receipts:user:${input.userId}:agent:${input.agentId}:topic:${input.topicId}`,
waypoint: (scopeKey: string) => `${AGENT_SIGNAL_PREFIX}waypoint:${scopeKey}`,
waypointEvents: (scopeKey: string) => `${AGENT_SIGNAL_PREFIX}waypoint:${scopeKey}:events`,
window: (scopeKey: string) => `${AGENT_SIGNAL_PREFIX}window:${scopeKey}`,
@@ -15,6 +19,7 @@ export const AGENT_SIGNAL_KEYS = {
/** Server-owned timing defaults for AgentSignal storage and generation. */
export const AGENT_SIGNAL_DEFAULTS = {
generationLockTtlSeconds: 5,
+ receiptTtlSeconds: 3 * 24 * 60 * 60,
runtimeGuardTtlSeconds: 3600,
runtimeWaypointTtlSeconds: 3600,
signalDedupeTtlSeconds: 300,
diff --git a/src/server/services/agentSignal/observability/__tests__/traceEvents.test.ts b/src/server/services/agentSignal/observability/__tests__/traceEvents.test.ts
index 1ba9d683eaa..7582c6d7a2b 100644
--- a/src/server/services/agentSignal/observability/__tests__/traceEvents.test.ts
+++ b/src/server/services/agentSignal/observability/__tests__/traceEvents.test.ts
@@ -105,4 +105,48 @@ describe('toAgentSignalTraceEvents', () => {
}),
);
});
+
+ /**
+ * @example
+ * const event = toAgentSignalTraceEvents({ signals: [{ payload: { result: 'satisfied' } }] }).at(1);
+ * expect(event?.data.satisfactionResult).toBe('satisfied');
+ */
+ it('copies classifier signal payload summaries into trace events', () => {
+ const events = toAgentSignalTraceEvents({
+ actions: [],
+ results: [],
+ signals: [
+ {
+ chain: { chainId: 'chain_1', parentNodeId: 'source_1', rootSourceId: 'source_1' },
+ payload: {
+ confidence: 0.86,
+ reason: 'implicit but strong future skill-learning instruction',
+ result: 'not_satisfied',
+ target: 'skill',
+ },
+ signalId: 'signal_1',
+ signalType: 'signal.feedback.domain.skill',
+ source: { sourceId: 'source_1', sourceType: 'agent.user.message' },
+ timestamp: 2,
+ },
+ ],
+ source: {
+ chain: { chainId: 'chain_1', rootSourceId: 'source_1' },
+ payload: { message: 'remember this', messageId: 'msg_1' },
+ scopeKey: 'topic:t1',
+ sourceId: 'source_1',
+ sourceType: 'agent.user.message',
+ timestamp: 1,
+ },
+ });
+
+ expect(events.at(1)?.data).toEqual(
+ expect.objectContaining({
+ confidence: 0.86,
+ reason: 'implicit but strong future skill-learning instruction',
+ satisfactionResult: 'not_satisfied',
+ target: 'skill',
+ }),
+ );
+ });
});
diff --git a/src/server/services/agentSignal/observability/traceEvents.ts b/src/server/services/agentSignal/observability/traceEvents.ts
index cb7dad2e1f7..01b21deb078 100644
--- a/src/server/services/agentSignal/observability/traceEvents.ts
+++ b/src/server/services/agentSignal/observability/traceEvents.ts
@@ -16,6 +16,12 @@ export interface AgentSignalTraceEvent {
| 'agent_signal.source';
}
+const readRecord = (value: unknown): Record<string, unknown> | undefined => {
+ return typeof value === 'object' && value !== null
+ ? (value as Record<string, unknown>)
+ : undefined;
+};
+
/** Formats AgentSignal nodes into compact tracing events. */
export const toAgentSignalTraceEvents = (input: {
actions: BaseAction[];
@@ -35,16 +41,24 @@ export const toAgentSignalTraceEvents = (input: {
type: 'agent_signal.source',
};
- const signalEvents: AgentSignalTraceEvent[] = input.signals.map((signal) => ({
- data: {
- parentNodeId: signal.chain.parentNodeId,
- signalId: signal.signalId,
- signalType: signal.signalType,
- sourceId: signal.source.sourceId,
- },
- timestamp: signal.timestamp,
- type: 'agent_signal.signal',
- }));
+ const signalEvents: AgentSignalTraceEvent[] = input.signals.map((signal) => {
+ const payload = readRecord(signal.payload);
+
+ return {
+ data: {
+ confidence: payload?.confidence,
+ parentNodeId: signal.chain.parentNodeId,
+ reason: payload?.reason,
+ signalId: signal.signalId,
+ signalType: signal.signalType,
+ sourceId: signal.source.sourceId,
+ satisfactionResult: payload?.result,
+ target: payload?.target,
+ },
+ timestamp: signal.timestamp,
+ type: 'agent_signal.signal',
+ };
+ });
const actionEvents: AgentSignalTraceEvent[] = input.actions.map((action) => ({
data: {
diff --git a/src/server/services/agentSignal/orchestrator.ts b/src/server/services/agentSignal/orchestrator.ts
index 56b88fcc0a6..afe7f0961c7 100644
--- a/src/server/services/agentSignal/orchestrator.ts
+++ b/src/server/services/agentSignal/orchestrator.ts
@@ -20,13 +20,15 @@ import { createDefaultAgentSignalPolicies } from './policies';
import { createProcedurePolicyOptions } from './procedure';
import type { RuntimeGuardBackend } from './runtime/AgentSignalRuntime';
import { createAgentSignalRuntime } from './runtime/AgentSignalRuntime';
+import { persistAgentSignalReceipts, projectAgentSignalReceipts } from './services/receiptService';
import { emitSourceEvent } from './sources';
import { redisPolicyStateStore } from './store/adapters/redis/policyStateStore';
-import type { AgentSignalSourceEventStore } from './store/types';
+import type { AgentSignalReceiptStore, AgentSignalSourceEventStore } from './store/types';
export { createAgentSignalRuntime } from './runtime/AgentSignalRuntime';
interface ExecuteAgentSignalSourceEventOptions extends AgentSignalEmitOptions {
+ receiptStore?: AgentSignalReceiptStore;
runtimeGuardBackend?: RuntimeGuardBackend;
store?: AgentSignalSourceEventStore;
}
@@ -140,6 +142,13 @@ const executeAgentSignalSourceEventCore = async <TSourceType extends AgentSignal
const orchestration = buildRuntimeOrchestrationResult(emission.source, runtimeResult);
await persistAgentSignalObservability(orchestration.observability);
+ const receipts = projectAgentSignalReceipts({
+ actions: orchestration.actions,
+ results: orchestration.results,
+ source: emission.source,
+ userId: context.userId,
+ });
+ await persistAgentSignalReceipts(receipts, { store: options.receiptStore });
return {
...emission,
diff --git a/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackSatisfaction.test.ts b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackSatisfaction.test.ts
index 2ed072b0e26..32fdbe78ae3 100644
--- a/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackSatisfaction.test.ts
+++ b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackSatisfaction.test.ts
@@ -216,7 +216,7 @@ describe('feedbackSatisfactionJudge', () => {
);
});
- it('treats skill reuse hints as satisfied weak positive feedback', async () => {
+ it('treats explicit Chinese skill conversion requests as unsatisfied actionable feedback', async () => {
const judge = {
judgeSatisfaction: vi.fn(),
};
@@ -234,8 +234,8 @@ describe('feedbackSatisfactionJudge', () => {
const processor = createFeedbackSatisfactionJudgeProcessor({ judge });
const result = await processor.handle(
createUserMessageSource(
- 'source_skill_reuse',
- '这个 review 流程挺好,下次也可以参考。',
+ 'source_skill_convert',
+ '刚才 chat agent 写的 SKILL.md 草稿可以用,把它转成真正的 skills/bundle。',
'topic=repo-review',
['skill'],
),
@@ -248,7 +248,110 @@ describe('feedbackSatisfactionJudge', () => {
signals: [
expect.objectContaining({
payload: expect.objectContaining({
- reason: 'source hinted reusable skill or workflow feedback',
+ reason: 'source hinted explicit skill-management change request',
+ result: 'not_satisfied',
+ }),
+ }),
+ ],
+ }),
+ );
+ });
+
+ it('falls back to the judge for implicit strong skill learning instructions', async () => {
+ const judge = {
+ judgeSatisfaction: vi.fn().mockResolvedValue({
+ confidence: 0.86,
+ evidence: [
+ {
+ cue: 'future scoped procedure reuse',
+ excerpt: '以后遇到这种数据库迁移 review,就按刚才那套检查顺序来。',
+ },
+ ],
+ reason: 'implicit but strong future skill-learning instruction',
+ result: 'not_satisfied',
+ }),
+ };
+ const ctx = createRuntimeProcessorContext({
+ backend: {
+ async getGuardState() {
+ return {};
+ },
+ async touchGuardState() {
+ return {};
+ },
+ },
+ scopeKey: 'topic:thread_1',
+ });
+ const processor = createFeedbackSatisfactionJudgeProcessor({ judge });
+ const result = await processor.handle(
+ createUserMessageSource(
+ 'source_skill_implicit_strong',
+ '以后遇到这种数据库迁移 review,就按刚才那套检查顺序来。',
+ 'topic=database-migration-review',
+ ['skill'],
+ ),
+ ctx,
+ );
+
+ expect(judge.judgeSatisfaction).toHaveBeenCalledWith({
+ message: '以后遇到这种数据库迁移 review,就按刚才那套检查顺序来。',
+ serializedContext: 'topic=database-migration-review',
+ });
+ expect(result).toEqual(
+ expect.objectContaining({
+ signals: [
+ expect.objectContaining({
+ payload: expect.objectContaining({
+ reason: 'implicit but strong future skill-learning instruction',
+ result: 'not_satisfied',
+ }),
+ }),
+ ],
+ }),
+ );
+ });
+
+ it('falls back to the judge for generic weak positive skill feedback', async () => {
+ const judge = {
+ judgeSatisfaction: vi.fn().mockResolvedValue({
+ confidence: 0.78,
+ evidence: [{ cue: 'generic praise', excerpt: '这个解释挺有帮助的。' }],
+ reason: 'generic positive feedback without a durable learning instruction',
+ result: 'satisfied',
+ }),
+ };
+ const ctx = createRuntimeProcessorContext({
+ backend: {
+ async getGuardState() {
+ return {};
+ },
+ async touchGuardState() {
+ return {};
+ },
+ },
+ scopeKey: 'topic:thread_1',
+ });
+ const processor = createFeedbackSatisfactionJudgeProcessor({ judge });
+ const result = await processor.handle(
+ createUserMessageSource(
+ 'source_skill_weak_positive',
+ '这个解释挺有帮助的。',
+ 'topic=debugging-help',
+ ['skill'],
+ ),
+ ctx,
+ );
+
+ expect(judge.judgeSatisfaction).toHaveBeenCalledWith({
+ message: '这个解释挺有帮助的。',
+ serializedContext: 'topic=debugging-help',
+ });
+ expect(result).toEqual(
+ expect.objectContaining({
+ signals: [
+ expect.objectContaining({
+ payload: expect.objectContaining({
+ reason: 'generic positive feedback without a durable learning instruction',
result: 'satisfied',
}),
}),
diff --git a/src/server/services/agentSignal/policies/analyzeIntent/actions/__tests__/skillManagement.test.ts b/src/server/services/agentSignal/policies/analyzeIntent/actions/__tests__/skillManagement.test.ts
index 735d27bd2d5..02b49b43907 100644
--- a/src/server/services/agentSignal/policies/analyzeIntent/actions/__tests__/skillManagement.test.ts
+++ b/src/server/services/agentSignal/policies/analyzeIntent/actions/__tests__/skillManagement.test.ts
@@ -76,6 +76,28 @@ describe('defineSkillManagementActionHandler', () => {
reason: 'authored reusable workflow',
title: 'PR Review Checklist',
});
+ createSkill.mockResolvedValue({
+ bundle: {
+ agentDocumentId: 'pr-review-checklist-bundle-id',
+ documentId: 'pr-review-checklist-bundle-doc',
+ filename: 'pr-review-checklist',
+ title: 'PR Review Checklist',
+ },
+ content: '# PR Review Checklist',
+ description: 'Use when creating reusable PR review checklists.',
+ frontmatter: {
+ description: 'Use when creating reusable PR review checklists.',
+ name: 'pr-review-checklist',
+ },
+ index: {
+ agentDocumentId: 'pr-review-checklist-index-id',
+ documentId: 'pr-review-checklist-index-doc',
+ filename: 'SKILL.md',
+ title: 'SKILL.md',
+ },
+ name: 'pr-review-checklist',
+ title: 'PR Review Checklist',
+ });
skillMaintainerService.getSkill.mockImplementation(async ({ agentDocumentId }) => ({
bundle: {
agentDocumentId,
@@ -359,6 +381,12 @@ describe('defineSkillManagementActionHandler', () => {
expect(result).toMatchObject({
output: {
decision: { action: 'create', confidence: 0.9, reason: 'reusable workflow feedback' },
+ target: {
+ id: 'pr-review-checklist-bundle-doc',
+ summary: 'Use when creating reusable PR review checklists.',
+ title: 'PR Review Checklist',
+ type: 'skill',
+ },
},
status: 'applied',
});
diff --git a/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts b/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts
index 4a65845257e..317365262d1 100644
--- a/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts
+++ b/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts
@@ -114,6 +114,14 @@ export interface SkillManagementActionResult {
decision: SkillManagementDecision;
detail?: string;
status: 'applied' | 'failed' | 'skipped';
+ target?: SkillManagementActionTarget;
+}
+
+export interface SkillManagementActionTarget {
+ id: string;
+ summary?: string;
+ title: string;
+ type: 'skill';
}
export interface SkillManagementActionInput {
@@ -1200,6 +1208,15 @@ const isMaintainerDecision = (
): decision is SkillManagementDecision & { action: 'consolidate' | 'refine' } =>
decision.action === 'refine' || decision.action === 'consolidate';
+const toSkillActionTarget = (
+ skill: Pick<SkillSummary, 'bundle' | 'description' | 'title'>,
+): SkillManagementActionTarget => ({
+ id: skill.bundle.documentId,
+ summary: skill.description,
+ title: skill.title,
+ type: 'skill',
+});
+
const readTargetSkills = async (
service: SkillManagementOperationService,
agentId: string,
@@ -1276,24 +1293,36 @@ const runMaintainerWorkflow = async (
);
const canonical = targetSkills[0];
+ if (!canonical) {
+ return {
+ decision,
+ detail: `Skill-management ${decision.action} could not resolve targetSkillRefs.`,
+ status: 'skipped',
+ };
+ }
+
+ let updatedSkill: SkillDetail | SkillSummary = canonical;
+
try {
if (workflowResult.rename?.newName || workflowResult.rename?.newTitle) {
- await service.renameSkill({
+ updatedSkill =
+ (await service.renameSkill({
+ agentDocumentId: canonical.bundle.agentDocumentId,
+ agentId: input.agentId,
+ newName: workflowResult.rename.newName,
+ newTitle: workflowResult.rename.newTitle,
+ updateReason: workflowResult.reason,
+ })) ?? updatedSkill;
+ }
+
+ updatedSkill =
+ (await service.replaceSkillIndex({
agentDocumentId: canonical.bundle.agentDocumentId,
agentId: input.agentId,
- newName: workflowResult.rename.newName,
- newTitle: workflowResult.rename.newTitle,
+ bodyMarkdown: workflowResult.bodyMarkdown,
+ description: workflowResult.description,
updateReason: workflowResult.reason,
- });
- }
-
- await service.replaceSkillIndex({
- agentDocumentId: canonical.bundle.agentDocumentId,
- agentId: input.agentId,
- bodyMarkdown: workflowResult.bodyMarkdown,
- description: workflowResult.description,
- updateReason: workflowResult.reason,
- });
+ })) ?? updatedSkill;
} catch (error) {
return {
decision,
@@ -1306,6 +1335,7 @@ const runMaintainerWorkflow = async (
decision,
detail: workflowResult.reason ?? `Applied ${decision.action} maintainer workflow.`,
status: 'applied',
+ target: toSkillActionTarget(updatedSkill),
};
};
@@ -1368,7 +1398,7 @@ const runCreateWorkflow = async (
createDefaultSkillManagementService(options);
try {
- await service.createSkill({
+ const skill = await service.createSkill({
agentId: input.agentId,
bodyMarkdown: authored.bodyMarkdown,
description: authored.description,
@@ -1381,6 +1411,7 @@ const runCreateWorkflow = async (
decision,
detail: authored.reason ?? `Created skill ${authored.name}.`,
status: 'applied',
+ target: toSkillActionTarget(skill),
};
} catch (error) {
if (error instanceof Error && error.message.includes('already exists')) {
@@ -1533,7 +1564,7 @@ export const handleSkillManagementAction = async (
actionId: action.actionId,
attempt: finalizeAttempt(startedAt, 'succeeded'),
detail: result.detail,
- output: { decision: result.decision },
+ output: { decision: result.decision, ...(result.target ? { target: result.target } : {}) },
status: 'applied',
};
}
diff --git a/src/server/services/agentSignal/policies/analyzeIntent/feedbackSatisfaction.ts b/src/server/services/agentSignal/policies/analyzeIntent/feedbackSatisfaction.ts
index bec7bd063d1..80d1a552b85 100644
--- a/src/server/services/agentSignal/policies/analyzeIntent/feedbackSatisfaction.ts
+++ b/src/server/services/agentSignal/policies/analyzeIntent/feedbackSatisfaction.ts
@@ -254,9 +254,7 @@ const resolveJudge = (
};
const explicitSkillChangePattern =
- /create|update|refine|merge|consolidate|combine|deduplicate|reorganize|创建|更新|合并|去重|整理/i;
-
-const weakPositiveSkillPattern = /keep|reuse|reference|保留|复用|参考/i;
+ /create|update|refine|merge|consolidate|combine|deduplicate|reorganize|创建|更新|合并|去重|整理|变成|变为|转换|转成|做成|沉淀|固化/i;
const resolveSkillHintSatisfaction = (
source: SourceAgentUserMessage,
@@ -265,20 +263,14 @@ const resolveSkillHintSatisfaction = (
const message = source.payload.message.trim();
const explicitChangeRequest = explicitSkillChangePattern.test(message);
- const result =
- !explicitChangeRequest && weakPositiveSkillPattern.test(message)
- ? 'satisfied'
- : 'not_satisfied';
+
+ if (!explicitChangeRequest) return undefined;
return {
confidence: 0.8,
evidence: [{ cue: 'skill source hint', excerpt: message }],
- reason: explicitChangeRequest
- ? 'source hinted explicit skill-management change request'
- : result === 'satisfied'
- ? 'source hinted reusable skill or workflow feedback'
- : 'source hinted skill-management feedback',
- result,
+ reason: 'source hinted explicit skill-management change request',
+ result: 'not_satisfied',
};
};
diff --git a/src/server/services/agentSignal/services/__tests__/receiptService.test.ts b/src/server/services/agentSignal/services/__tests__/receiptService.test.ts
new file mode 100644
index 00000000000..0773a0de839
--- /dev/null
+++ b/src/server/services/agentSignal/services/__tests__/receiptService.test.ts
@@ -0,0 +1,233 @@
+// @vitest-environment node
+import type { BaseAction, ExecutorResult } from '@lobechat/agent-signal';
+import { createSource } from '@lobechat/agent-signal';
+import { describe, expect, it, vi } from 'vitest';
+
+import { AGENT_SIGNAL_POLICY_ACTION_TYPES } from '../../policies/types';
+import type { AgentSignalReceiptStore } from '../receiptService';
+import { persistAgentSignalReceipts, projectAgentSignalReceipts } from '../receiptService';
+
+const source = createSource({
+ payload: {
+ agentId: 'agent-1',
+ assistantMessageId: 'assistant-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ },
+ scope: { topicId: 'topic-1', userId: 'user-1' },
+ scopeKey: 'topic:topic-1',
+ sourceId: 'source-1',
+ sourceType: 'client.gateway.runtime_end',
+ timestamp: 1_700_000,
+});
+
+const action = (input: {
+ actionId: string;
+ actionType: string;
+ payload: Record<string, unknown>;
+}): BaseAction => ({
+ actionId: input.actionId,
+ actionType: input.actionType,
+ chain: { rootSourceId: 'source-1' },
+ payload: input.payload,
+ signal: { signalId: 'signal-1', signalType: 'signal.feedback.domain.memory' },
+ source: { sourceId: 'source-1', sourceType: 'client.gateway.runtime_end' },
+ timestamp: 1_700_000,
+});
+
+const result = (input: {
+ actionId: string;
+ output?: Record<string, unknown>;
+ status: 'applied' | 'skipped';
+}): ExecutorResult => ({
+ actionId: input.actionId,
+ attempt: {
+ completedAt: 1_700_001,
+ current: 1,
+ startedAt: 1_700_000,
+ status: input.status === 'applied' ? 'succeeded' : input.status,
+ },
+ ...(input.output ? { output: input.output } : {}),
+ status: input.status,
+});
+
+describe('projectAgentSignalReceipts', () => {
+ it('projects applied memory action results', () => {
+ expect(
+ projectAgentSignalReceipts({
+ actions: [
+ action({
+ actionId: 'action-memory-1',
+ actionType: AGENT_SIGNAL_POLICY_ACTION_TYPES.userMemoryHandle,
+ payload: { message: 'Remember that future PR reviews should be decision-first.' },
+ }),
+ ],
+ results: [result({ actionId: 'action-memory-1', status: 'applied' })],
+ source,
+ userId: 'user-1',
+ }),
+ ).toEqual([
+ {
+ agentId: 'agent-1',
+ anchorMessageId: 'assistant-1',
+ createdAt: 1_700_000,
+ detail: 'Saved this for future replies',
+ id: 'source-1:action-memory-1:memory',
+ kind: 'memory',
+ operationId: 'op-1',
+ sourceId: 'source-1',
+ sourceType: 'client.gateway.runtime_end',
+ status: 'applied',
+ target: {
+ title: 'Remember that future PR reviews should be decision-first.',
+ type: 'memory',
+ },
+ title: 'Memory saved',
+ topicId: 'topic-1',
+ userId: 'user-1',
+ },
+ ]);
+ });
+
+ it('projects applied skill-management results as updated skill receipts', () => {
+ expect(
+ projectAgentSignalReceipts({
+ actions: [
+ action({
+ actionId: 'action-skill-1',
+ actionType: AGENT_SIGNAL_POLICY_ACTION_TYPES.skillManagementHandle,
+ payload: {},
+ }),
+ ],
+ results: [result({ actionId: 'action-skill-1', status: 'applied' })],
+ source,
+ userId: 'user-1',
+ }),
+ ).toMatchObject([{ kind: 'skill', status: 'updated', title: 'Skill updated' }]);
+ });
+
+ it('projects skill target snapshots from action results', () => {
+ expect(
+ projectAgentSignalReceipts({
+ actions: [
+ action({
+ actionId: 'action-skill-1',
+ actionType: AGENT_SIGNAL_POLICY_ACTION_TYPES.skillManagementHandle,
+ payload: {},
+ }),
+ ],
+ results: [
+ result({
+ actionId: 'action-skill-1',
+ output: {
+ target: {
+ id: 'document-1',
+ summary: 'Review metadata before diff and produce a merge decision.',
+ title: 'GitHub PR review workflow',
+ type: 'skill',
+ },
+ },
+ status: 'applied',
+ }),
+ ],
+ source,
+ userId: 'user-1',
+ }),
+ ).toMatchObject([
+ {
+ kind: 'skill',
+ target: {
+ id: 'document-1',
+ summary: 'Review metadata before diff and produce a merge decision.',
+ title: 'GitHub PR review workflow',
+ type: 'skill',
+ },
+ },
+ ]);
+ });
+
+ it('does not project skipped, failed, procedure, or missing-topic results', () => {
+ expect(
+ projectAgentSignalReceipts({
+ actions: [
+ action({
+ actionId: 'action-memory-1',
+ actionType: AGENT_SIGNAL_POLICY_ACTION_TYPES.userMemoryHandle,
+ payload: {},
+ }),
+ action({
+ actionId: 'action-other-1',
+ actionType: 'action.procedure.handle',
+ payload: {},
+ }),
+ ],
+ results: [
+ result({ actionId: 'action-memory-1', status: 'skipped' }),
+ result({ actionId: 'action-other-1', status: 'applied' }),
+ ],
+ source,
+ userId: 'user-1',
+ }),
+ ).toEqual([]);
+ });
+});
+
+describe('persistAgentSignalReceipts', () => {
+ it('persists all receipts with the configured TTL', async () => {
+ const store: AgentSignalReceiptStore = {
+ appendReceipt: vi.fn().mockResolvedValue(true),
+ listReceipts: vi.fn(),
+ };
+ const receipt = {
+ agentId: 'agent-1',
+ createdAt: 1,
+ detail: 'Saved this for future replies',
+ id: 'receipt-1',
+ kind: 'memory' as const,
+ sourceId: 'source-1',
+ sourceType: 'client.gateway.runtime_end',
+ status: 'applied' as const,
+ title: 'Memory saved',
+ topicId: 'topic-1',
+ userId: 'user-1',
+ };
+
+ await persistAgentSignalReceipts([receipt], { store });
+
+ expect(store.appendReceipt).toHaveBeenCalledWith(receipt, 259_200);
+ });
+
+ it('does not reject when receipt persistence fails', async () => {
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const store: AgentSignalReceiptStore = {
+ appendReceipt: vi.fn().mockRejectedValue(new Error('redis unavailable')),
+ listReceipts: vi.fn(),
+ };
+ const receipt = {
+ agentId: 'agent-1',
+ createdAt: 1,
+ detail: 'Saved this for future replies',
+ id: 'receipt-1',
+ kind: 'memory' as const,
+ sourceId: 'source-1',
+ sourceType: 'client.gateway.runtime_end',
+ status: 'applied' as const,
+ title: 'Memory saved',
+ topicId: 'topic-1',
+ userId: 'user-1',
+ };
+
+ await expect(persistAgentSignalReceipts([receipt], { store })).resolves.toBeUndefined();
+
+ expect(consoleError).toHaveBeenCalledWith(
+ '[AgentSignal] Failed to persist receipt:',
+ expect.objectContaining({
+ id: 'receipt-1',
+ kind: 'memory',
+ sourceId: 'source-1',
+ topicId: 'topic-1',
+ }),
+ );
+ consoleError.mockRestore();
+ });
+});
diff --git a/src/server/services/agentSignal/services/index.ts b/src/server/services/agentSignal/services/index.ts
index b3f472b2040..000a14a8aaf 100644
--- a/src/server/services/agentSignal/services/index.ts
+++ b/src/server/services/agentSignal/services/index.ts
@@ -1,4 +1,5 @@
export * from './actionServices';
export * from './classifierServices';
export * from './procedureStateService';
+export * from './receiptService';
export * from './types';
diff --git a/src/server/services/agentSignal/services/receiptService.ts b/src/server/services/agentSignal/services/receiptService.ts
new file mode 100644
index 00000000000..302ec02202d
--- /dev/null
+++ b/src/server/services/agentSignal/services/receiptService.ts
@@ -0,0 +1,261 @@
+import type { AgentSignalSource, BaseAction, ExecutorResult } from '@lobechat/agent-signal';
+
+import { AGENT_SIGNAL_DEFAULTS } from '../constants';
+import { AGENT_SIGNAL_POLICY_ACTION_TYPES } from '../policies/types';
+import { redisReceiptStore } from '../store/adapters/redis/receiptStore';
+
+/**
+ * User-visible Agent Signal receipt persisted for recent topic activity.
+ */
+export interface AgentSignalReceipt {
+ /** Agent that owns the topic. */
+ agentId: string;
+ /** Assistant message this receipt should render under when known. */
+ anchorMessageId?: string;
+ /** Millisecond timestamp used for newest-first receipt indexes. */
+ createdAt: number;
+ /** Fallback detail copy for clients without locale keys. */
+ detail: string;
+ /** Stable receipt id used as Redis member and payload key suffix. */
+ id: string;
+ /** User-facing durable outcome domain. */
+ kind: 'memory' | 'skill';
+ /** Agent runtime operation that produced the receipt, when known. */
+ operationId?: string;
+ /** Source event id that triggered the receipt. */
+ sourceId: string;
+ /** Source event type that triggered the receipt. */
+ sourceType: string;
+ /** User-facing terminal status. */
+ status: 'applied' | 'updated';
+ /** Snapshot of the resource affected when the receipt was produced. */
+ target?: {
+ /** Backing resource id for future navigation when still available. Skill ids use `documents.id`. */
+ id?: string;
+ /** Short summary captured at write time. */
+ summary?: string;
+ /** Human-readable resource title captured at write time. */
+ title: string;
+ /** User-facing resource domain. */
+ type: 'memory' | 'skill';
+ };
+ /** Fallback title copy for clients without locale keys. */
+ title: string;
+ /** Topic where the receipt should be listed. */
+ topicId: string;
+ /** Owner used to enforce topic index isolation. */
+ userId: string;
+}
+
+/** Query input for one scoped receipt page. */
+export interface AgentSignalReceiptListInput {
+ /** Agent whose topic receipts should be listed. */
+ agentId: string;
+ /** Zero-based sorted-set offset for the next page. */
+ cursor?: number;
+ /** Maximum receipt count to return. */
+ limit: number;
+ /** Topic whose receipts should be listed. */
+ topicId: string;
+ /** Current authenticated user. */
+ userId: string;
+}
+
+/** Newest-first receipt page. */
+export interface AgentSignalReceiptListResult {
+ /** Next zero-based sorted-set offset, when another page exists. */
+ cursor?: number;
+ /** Receipts newest first. */
+ receipts: AgentSignalReceipt[];
+}
+
+/** Storage contract for user-visible Agent Signal receipt history. */
+export interface AgentSignalReceiptStore {
+ appendReceipt: (receipt: AgentSignalReceipt, ttlSeconds: number) => Promise<boolean>;
+ listReceipts: (input: AgentSignalReceiptListInput) => Promise<AgentSignalReceiptListResult>;
+}
+
+interface ProjectAgentSignalReceiptsInput {
+ actions: BaseAction[];
+ results: ExecutorResult[];
+ source: AgentSignalSource;
+ userId: string;
+}
+
+interface PersistAgentSignalReceiptsOptions {
+ store?: AgentSignalReceiptStore;
+}
+
+const getPayloadString = (payload: Record<string, unknown>, key: string) => {
+ const value = payload[key];
+
+ return typeof value === 'string' && value.length > 0 ? value : undefined;
+};
+
+const getClampedString = (value: string, maxLength = 96) =>
+ value.length > maxLength ? `${value.slice(0, maxLength - 1)}...` : value;
+
+const getReceiptTarget = (
+ action: BaseAction,
+ result: ExecutorResult,
+ kind: AgentSignalReceipt['kind'],
+): AgentSignalReceipt['target'] | undefined => {
+ const target = result.output?.target;
+
+ if (target && typeof target === 'object') {
+ const payload = target as Record<string, unknown>;
+ const title = typeof payload.title === 'string' ? payload.title.trim() : undefined;
+ const type = payload.type === 'memory' || payload.type === 'skill' ? payload.type : kind;
+
+ if (title) {
+ return {
+ ...(typeof payload.id === 'string' && payload.id.length > 0 ? { id: payload.id } : {}),
+ ...(typeof payload.summary === 'string' && payload.summary.length > 0
+ ? { summary: payload.summary }
+ : {}),
+ title,
+ type,
+ };
+ }
+ }
+
+ if (kind !== 'memory') return;
+
+ const message = getPayloadString(action.payload, 'message')?.trim();
+ if (!message) return;
+
+ return {
+ title: getClampedString(message),
+ type: 'memory',
+ };
+};
+
+const toReceiptKind = (
+ action: BaseAction,
+): Pick<AgentSignalReceipt, 'detail' | 'kind' | 'status' | 'title'> | undefined => {
+ if (action.actionType === AGENT_SIGNAL_POLICY_ACTION_TYPES.userMemoryHandle) {
+ return {
+ detail: 'Saved this for future replies',
+ kind: 'memory',
+ status: 'applied',
+ title: 'Memory saved',
+ };
+ }
+
+ if (action.actionType === AGENT_SIGNAL_POLICY_ACTION_TYPES.skillManagementHandle) {
+ return {
+ detail: 'Improved how this assistant handles similar requests',
+ kind: 'skill',
+ status: 'updated',
+ title: 'Skill updated',
+ };
+ }
+
+ return;
+};
+
+/**
+ * Projects terminal Agent Signal runtime results into user-visible receipts.
+ *
+ * Use when:
+ * - Runtime orchestration has completed and action executor results are available
+ * - Only durable, applied memory/skill outcomes should be shown to users
+ *
+ * Expects:
+ * - `results` reference `actions` by `actionId`
+ * - `source.payload.agentId` and `source.payload.topicId` identify the chat context
+ *
+ * Returns:
+ * - Zero or more receipt payloads safe to persist in the recent receipt store
+ */
+export const projectAgentSignalReceipts = ({
+ actions,
+ results,
+ source,
+ userId,
+}: ProjectAgentSignalReceiptsInput): AgentSignalReceipt[] => {
+ const payload = source.payload as Record<string, unknown>;
+ const agentId = getPayloadString(payload, 'agentId');
+ const topicId = getPayloadString(payload, 'topicId');
+
+ if (!agentId || !topicId) return [];
+
+ const actionById = new Map(actions.map((action) => [action.actionId, action]));
+
+ return results.flatMap((result) => {
+ if (result.status !== 'applied') return [];
+
+ const action = actionById.get(result.actionId);
+ if (!action) return [];
+
+ const visibleOutcome = toReceiptKind(action);
+ if (!visibleOutcome) return [];
+
+ const target = getReceiptTarget(action, result, visibleOutcome.kind);
+
+ return [
+ {
+ ...visibleOutcome,
+ agentId,
+ anchorMessageId: getPayloadString(payload, 'assistantMessageId'),
+ createdAt: source.timestamp,
+ id: `${source.sourceId}:${result.actionId}:${visibleOutcome.kind}`,
+ operationId: getPayloadString(payload, 'operationId'),
+ sourceId: source.sourceId,
+ sourceType: source.sourceType,
+ topicId,
+ ...(target ? { target } : {}),
+ userId,
+ },
+ ];
+ });
+};
+
+/**
+ * Persists user-visible Agent Signal receipts into recent Redis history.
+ *
+ * Use when:
+ * - Agent Signal orchestration has projected terminal receipt outcomes
+ * - The caller wants deduped, TTL-bound product feedback
+ *
+ * Expects:
+ * - Receipts already passed product filtering
+ *
+ * Returns:
+ * - Nothing; individual duplicate receipts are ignored by the store
+ */
+export const persistAgentSignalReceipts = async (
+ receipts: AgentSignalReceipt[],
+ options: PersistAgentSignalReceiptsOptions = {},
+): Promise<void> => {
+ const store = options.store ?? redisReceiptStore;
+
+ const results = await Promise.allSettled(
+ receipts.map((receipt) =>
+ store.appendReceipt(receipt, AGENT_SIGNAL_DEFAULTS.receiptTtlSeconds),
+ ),
+ );
+
+ for (const [index, result] of results.entries()) {
+ if (result.status === 'fulfilled') continue;
+
+ const receipt = receipts[index];
+ console.error('[AgentSignal] Failed to persist receipt:', {
+ error: result.reason,
+ id: receipt?.id,
+ kind: receipt?.kind,
+ sourceId: receipt?.sourceId,
+ topicId: receipt?.topicId,
+ });
+ }
+};
+
+/**
+ * Lists recent Agent Signal receipts for one user-owned topic.
+ */
+export const listAgentSignalReceipts = async (
+ input: AgentSignalReceiptListInput,
+ options: { store?: AgentSignalReceiptStore } = {},
+) => {
+ return (options.store ?? redisReceiptStore).listReceipts(input);
+};
diff --git a/src/server/services/agentSignal/store/__tests__/redisReceiptStore.test.ts b/src/server/services/agentSignal/store/__tests__/redisReceiptStore.test.ts
new file mode 100644
index 00000000000..20b00fe3106
--- /dev/null
+++ b/src/server/services/agentSignal/store/__tests__/redisReceiptStore.test.ts
@@ -0,0 +1,121 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ type AgentSignalRedisTestGlobal,
+ installStatefulRedisMock,
+ mockRedis,
+ resetRedisState,
+} from './redisTestUtils';
+
+const loadStore = async () => {
+ vi.resetModules();
+ (globalThis as AgentSignalRedisTestGlobal).__agentSignalRedisClient = mockRedis;
+
+ return import('../adapters/redis/receiptStore');
+};
+
+const receipt = {
+ agentId: 'agent-1',
+ anchorMessageId: 'assistant-1',
+ createdAt: 1_700_000,
+ detail: 'Saved this for future replies',
+ id: 'receipt-1',
+ kind: 'memory' as const,
+ operationId: 'op-1',
+ sourceId: 'source-1',
+ sourceType: 'client.gateway.runtime_end',
+ status: 'applied' as const,
+ target: {
+ summary: 'Use short answers in future chats',
+ title: 'Short answer preference',
+ type: 'memory' as const,
+ },
+ title: 'Memory saved',
+ topicId: 'topic-1',
+ userId: 'user-1',
+};
+
+describe('redis receipt store', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ resetRedisState();
+ installStatefulRedisMock();
+ (globalThis as AgentSignalRedisTestGlobal).__agentSignalRedisClient = mockRedis;
+ });
+
+ it('appends a receipt payload and indexes it by user, agent, and topic', async () => {
+ const store = await loadStore();
+
+ await expect(store.appendReceipt(receipt, 259_200)).resolves.toBe(true);
+
+ expect(mockRedis.hset).toHaveBeenCalledWith('agent-signal:receipt:receipt-1', {
+ agentId: 'agent-1',
+ anchorMessageId: 'assistant-1',
+ createdAt: '1700000',
+ detail: 'Saved this for future replies',
+ id: 'receipt-1',
+ kind: 'memory',
+ operationId: 'op-1',
+ sourceId: 'source-1',
+ sourceType: 'client.gateway.runtime_end',
+ status: 'applied',
+ target: JSON.stringify({
+ summary: 'Use short answers in future chats',
+ title: 'Short answer preference',
+ type: 'memory',
+ }),
+ title: 'Memory saved',
+ topicId: 'topic-1',
+ userId: 'user-1',
+ });
+ expect(mockRedis.zadd).toHaveBeenCalledWith(
+ 'agent-signal:receipts:user:user-1:agent:agent-1:topic:topic-1',
+ 1_700_000,
+ 'receipt-1',
+ );
+ expect(mockRedis.expire).toHaveBeenCalledWith('agent-signal:receipt:receipt-1', 259_200);
+ });
+
+ it('lists newest receipts and removes dangling index members', async () => {
+ const store = await loadStore();
+
+ await store.appendReceipt(receipt, 259_200);
+ await store.appendReceipt({ ...receipt, createdAt: 1_700_010, id: 'receipt-2' }, 259_200);
+ await mockRedis.zadd(
+ 'agent-signal:receipts:user:user-1:agent:agent-1:topic:topic-1',
+ 1_700_020,
+ 'expired-receipt',
+ );
+
+ await expect(
+ store.listReceipts({ agentId: 'agent-1', limit: 10, topicId: 'topic-1', userId: 'user-1' }),
+ ).resolves.toEqual({
+ cursor: undefined,
+ receipts: [{ ...receipt, createdAt: 1_700_010, id: 'receipt-2' }, receipt],
+ });
+
+ expect(mockRedis.zrem).toHaveBeenCalledWith(
+ 'agent-signal:receipts:user:user-1:agent:agent-1:topic:topic-1',
+ 'expired-receipt',
+ );
+ });
+
+ it('dedupes repeated receipt appends', async () => {
+ const store = await loadStore();
+
+ await expect(store.appendReceipt(receipt, 259_200)).resolves.toBe(true);
+ await expect(store.appendReceipt(receipt, 259_200)).resolves.toBe(false);
+ });
+
+ it('returns an empty page when redis is unavailable', async () => {
+ const store = await loadStore();
+
+ (globalThis as AgentSignalRedisTestGlobal).__agentSignalRedisClient = null;
+
+ await expect(
+ store.listReceipts({ agentId: 'agent-1', limit: 10, topicId: 'topic-1', userId: 'user-1' }),
+ ).resolves.toEqual({ cursor: undefined, receipts: [] });
+ await expect(store.appendReceipt(receipt, 259_200)).resolves.toBe(false);
+ });
+});
diff --git a/src/server/services/agentSignal/store/__tests__/redisTestUtils.ts b/src/server/services/agentSignal/store/__tests__/redisTestUtils.ts
index 5a6397a447f..f0a0842ffed 100644
--- a/src/server/services/agentSignal/store/__tests__/redisTestUtils.ts
+++ b/src/server/services/agentSignal/store/__tests__/redisTestUtils.ts
@@ -7,9 +7,13 @@ export interface AgentSignalRedisTestGlobal {
type HashState = Map<string, Record<string, string>>;
type ListState = Map<string, string[]>;
+type SortedSetState = Map<string, Map<string, number>>;
+type StringState = Set<string>;
export const hashes: HashState = new Map();
export const lists: ListState = new Map();
+export const sortedSets: SortedSetState = new Map();
+export const strings: StringState = new Set();
const cloneHash = (value?: Record<string, string>) => {
return value ? { ...value } : {};
@@ -30,6 +34,8 @@ const applyHashWrite = (key: string, payload: Record<string, string>) => {
export const resetRedisState = () => {
hashes.clear();
lists.clear();
+ sortedSets.clear();
+ strings.clear();
};
const queuedExecResults: Array<Array<readonly [null, 'OK']> | null | undefined> = [];
@@ -49,6 +55,9 @@ const createMockRedisClient = () => {
set: vi.fn(),
unwatch: vi.fn(),
watch: vi.fn(),
+ zadd: vi.fn(),
+ zrem: vi.fn(),
+ zrevrange: vi.fn(),
};
};
@@ -57,7 +66,11 @@ const casClients: Array<typeof mockRedis> = [];
const installRedisClientBehavior = (client: typeof mockRedis) => {
client.del.mockImplementation(async (key: string) => {
- const removed = Number(hashes.delete(key)) + Number(lists.delete(key));
+ const removed =
+ Number(hashes.delete(key)) +
+ Number(lists.delete(key)) +
+ Number(sortedSets.delete(key)) +
+ Number(strings.delete(key));
return removed;
});
client.expire.mockImplementation(async () => 1);
@@ -88,6 +101,47 @@ const installRedisClientBehavior = (client: typeof mockRedis) => {
return current.length;
});
+ client.set.mockImplementation(
+ async (key: string, value: string, mode?: string, ttlSeconds?: number, nx?: string) => {
+ void value;
+ void ttlSeconds;
+
+ if (mode === 'EX' && nx === 'NX') {
+ if (strings.has(key)) return null;
+
+ strings.add(key);
+ return 'OK';
+ }
+
+ strings.add(key);
+ return 'OK';
+ },
+ );
+ client.zadd.mockImplementation(async (key: string, score: number, member: string) => {
+ const current = sortedSets.get(key) ?? new Map<string, number>();
+ current.set(member, score);
+ sortedSets.set(key, current);
+
+ return 1;
+ });
+ client.zrem.mockImplementation(async (key: string, ...members: string[]) => {
+ const current = sortedSets.get(key) ?? new Map<string, number>();
+ let removed = 0;
+
+ for (const member of members) {
+ if (current.delete(member)) removed++;
+ }
+
+ sortedSets.set(key, current);
+
+ return removed;
+ });
+ client.zrevrange.mockImplementation(async (key: string, start: number, stop: number) => {
+ const entries = [...(sortedSets.get(key)?.entries() ?? [])].sort((a, b) => b[1] - a[1]);
+ const normalizedStop = stop < 0 ? entries.length + stop + 1 : stop + 1;
+
+ return entries.slice(start, normalizedStop).map(([member]) => member);
+ });
client.watch.mockImplementation(async () => 'OK');
client.unwatch.mockImplementation(async () => 'OK');
client.quit.mockImplementation(async () => 'OK');
diff --git a/src/server/services/agentSignal/store/adapters/redis/receiptStore.ts b/src/server/services/agentSignal/store/adapters/redis/receiptStore.ts
new file mode 100644
index 00000000000..1d61cb799ba
--- /dev/null
+++ b/src/server/services/agentSignal/store/adapters/redis/receiptStore.ts
@@ -0,0 +1,140 @@
+import { AGENT_SIGNAL_KEYS } from '../../../constants';
+import type { AgentSignalReceipt } from '../../../services/receiptService';
+import type { AgentSignalReceiptStore } from '../../types';
+import { getRedisClient, readHash, trySetNx, writeHash } from './shared';
+
+const toReceiptHash = (receipt: AgentSignalReceipt): Record<string, string> => ({
+ agentId: receipt.agentId,
+ ...(receipt.anchorMessageId ? { anchorMessageId: receipt.anchorMessageId } : {}),
+ createdAt: String(receipt.createdAt),
+ detail: receipt.detail,
+ id: receipt.id,
+ kind: receipt.kind,
+ ...(receipt.operationId ? { operationId: receipt.operationId } : {}),
+ sourceId: receipt.sourceId,
+ sourceType: receipt.sourceType,
+ status: receipt.status,
+ ...(receipt.target ? { target: JSON.stringify(receipt.target) } : {}),
+ title: receipt.title,
+ topicId: receipt.topicId,
+ userId: receipt.userId,
+});
+
+const parseReceiptTarget = (value?: string): AgentSignalReceipt['target'] | undefined => {
+ if (!value) return;
+
+ try {
+ const target = JSON.parse(value) as Record<string, unknown>;
+
+ if (target.type !== 'memory' && target.type !== 'skill') return;
+ if (typeof target.title !== 'string' || target.title.length === 0) return;
+
+ return {
+ ...(typeof target.id === 'string' && target.id.length > 0 ? { id: target.id } : {}),
+ ...(typeof target.summary === 'string' && target.summary.length > 0
+ ? { summary: target.summary }
+ : {}),
+ title: target.title,
+ type: target.type,
+ };
+ } catch {
+ return;
+ }
+};
+
+const fromReceiptHash = (payload: Record<string, string>): AgentSignalReceipt | undefined => {
+ const createdAt = Number(payload.createdAt);
+
+ if (!payload.id || !payload.userId || !payload.agentId || !payload.topicId) return;
+ if (payload.kind !== 'memory' && payload.kind !== 'skill') return;
+ if (payload.status !== 'applied' && payload.status !== 'updated') return;
+ if (!Number.isFinite(createdAt)) return;
+
+ const target = parseReceiptTarget(payload.target);
+
+ return {
+ agentId: payload.agentId,
+ anchorMessageId: payload.anchorMessageId,
+ createdAt,
+ detail: payload.detail,
+ id: payload.id,
+ kind: payload.kind,
+ operationId: payload.operationId,
+ sourceId: payload.sourceId,
+ sourceType: payload.sourceType,
+ status: payload.status,
+ ...(target ? { target } : {}),
+ title: payload.title,
+ topicId: payload.topicId,
+ userId: payload.userId,
+ };
+};
+
+/** Appends one deduped receipt payload and its scoped topic index entry. */
+export const appendReceipt: AgentSignalReceiptStore['appendReceipt'] = async (
+ receipt,
+ ttlSeconds,
+) => {
+ const redis = getRedisClient();
+ if (!redis) return false;
+
+ const accepted = await trySetNx(AGENT_SIGNAL_KEYS.receiptDedupe(receipt.id), ttlSeconds);
+ if (!accepted) return false;
+
+ const receiptKey = AGENT_SIGNAL_KEYS.receipt(receipt.id);
+ const indexKey = AGENT_SIGNAL_KEYS.receiptIndex(receipt);
+
+ await writeHash(receiptKey, toReceiptHash(receipt), ttlSeconds);
+ await redis.zadd(indexKey, receipt.createdAt, receipt.id);
+ await redis.expire(indexKey, ttlSeconds);
+
+ return true;
+};
+
+/**
+ * Lists newest receipts from one scoped topic index and prunes expired payload references.
+ */
+export const listReceipts: AgentSignalReceiptStore['listReceipts'] = async (input) => {
+ const redis = getRedisClient();
+ if (!redis) return { cursor: undefined, receipts: [] };
+
+ const indexKey = AGENT_SIGNAL_KEYS.receiptIndex(input);
+ const start = input.cursor ?? 0;
+ const stop = start + input.limit;
+ const ids = await redis.zrevrange(indexKey, start, stop);
+ const receipts: AgentSignalReceipt[] = [];
+ const missingIds: string[] = [];
+
+ for (const id of ids.slice(0, input.limit)) {
+ const payload = await readHash(AGENT_SIGNAL_KEYS.receipt(id));
+ const receipt = payload ? fromReceiptHash(payload) : undefined;
+
+ if (!receipt) {
+ missingIds.push(id);
+ continue;
+ }
+
+ if (
+ receipt.userId === input.userId &&
+ receipt.agentId === input.agentId &&
+ receipt.topicId === input.topicId
+ ) {
+ receipts.push(receipt);
+ }
+ }
+
+ if (missingIds.length > 0) {
+ await redis.zrem(indexKey, ...missingIds);
+ }
+
+ return {
+ cursor: ids.length > input.limit ? start + input.limit : undefined,
+ receipts,
+ };
+};
+
+/** Redis-backed Agent Signal receipt store. */
+export const redisReceiptStore: AgentSignalReceiptStore = {
+ appendReceipt,
+ listReceipts,
+};
diff --git a/src/server/services/agentSignal/store/types.ts b/src/server/services/agentSignal/store/types.ts
index 1dec3324fe0..b6bda92bf58 100644
--- a/src/server/services/agentSignal/store/types.ts
+++ b/src/server/services/agentSignal/store/types.ts
@@ -1,3 +1,5 @@
+import type { AgentSignalReceiptStore } from '../services/receiptService';
+
/** Persisted policy-state payload for one AgentSignal scope. */
export interface AgentSignalPolicyStatePayload {
[key: string]: string;
@@ -34,3 +36,5 @@ export interface AgentSignalSourceEventStore {
ttlSeconds: number,
) => Promise<void>;
}
+
+export type { AgentSignalReceiptStore };
diff --git a/src/services/agentSignal.ts b/src/services/agentSignal.ts
index 17c4262ac8a..a690c59ad8e 100644
--- a/src/services/agentSignal.ts
+++ b/src/services/agentSignal.ts
@@ -10,7 +10,18 @@ type ClientGatewaySourceType = Extract<AgentSignalSourceType, `client.${string}`
type ClientGatewaySourceEventInput<TSourceType extends ClientGatewaySourceType> =
AgentSignalSourceEventInput<TSourceType>;
+export interface ListAgentSignalReceiptsParams {
+ agentId: string;
+ cursor?: number;
+ limit?: number;
+ topicId: string;
+}
+
class AgentSignalService {
+ listReceipts = async (params: ListAgentSignalReceiptsParams) => {
+ return lambdaClient.agentSignal.listReceipts.query(params);
+ };
+
emitSourceEvent = async (payload: ClientGatewaySourceEventInput<ClientGatewaySourceType>) => {
return lambdaClient.agentSignal.emitSourceEvent.mutate(payload);
};
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 30eb230b42d..cdbed9db805 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts
@@ -2,6 +2,7 @@ import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { messageService } from '@/services/message';
+import { emitClientAgentSignalSourceEvent } from '@/store/chat/slices/aiChat/actions/agentSignalBridge';
import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNotification';
import { createGatewayEventHandler } from '../gatewayEventHandler';
@@ -15,6 +16,9 @@ vi.mock('@/services/message', () => ({
vi.mock('@/store/chat/utils/desktopNotification', () => ({
notifyDesktopHumanApprovalRequired: vi.fn().mockResolvedValue(undefined),
}));
+vi.mock('@/store/chat/slices/aiChat/actions/agentSignalBridge', () => ({
+ emitClientAgentSignalSourceEvent: vi.fn().mockResolvedValue(undefined),
+}));
// ─── Test Helpers ───
@@ -74,6 +78,15 @@ describe('createGatewayEventHandler', () => {
expect(store.associateMessageWithOperation).toHaveBeenCalledWith('msg-step2', 'op-1');
expect(store.replaceMessages).toHaveBeenCalled();
+ expect(emitClientAgentSignalSourceEvent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ payload: expect.objectContaining({
+ assistantMessageId: 'msg-step2',
+ operationId: 'op-1',
+ }),
+ sourceType: 'client.gateway.stream_start',
+ }),
+ );
});
it('should keep current ID if event data has no assistantMessage', async () => {
@@ -349,6 +362,25 @@ describe('createGatewayEventHandler', () => {
expect(store.completeOperation).toHaveBeenCalledWith('op-1');
expect(store.replaceMessages).toHaveBeenCalled();
});
+
+ it('should emit runtime end signal with the current assistant message id', async () => {
+ const store = createMockStore();
+ const handler = createHandler(store);
+
+ handler(makeEvent('stream_start', { assistantMessage: { id: 'msg-step2' } }));
+ handler(makeEvent('agent_runtime_end'));
+ await flush();
+
+ expect(emitClientAgentSignalSourceEvent).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ payload: expect.objectContaining({
+ assistantMessageId: 'msg-step2',
+ operationId: 'op-1',
+ }),
+ sourceType: 'client.gateway.runtime_end',
+ }),
+ );
+ });
});
describe('error', () => {
diff --git a/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts b/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts
index 7790ca941cf..d88a961587b 100644
--- a/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts
+++ b/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts
@@ -123,6 +123,7 @@ export const createGatewayEventHandler = (
void emitClientAgentSignalSourceEvent({
payload: {
agentId: context.agentId,
+ ...(newAssistantMessageId ? { assistantMessageId: newAssistantMessageId } : {}),
operationId,
stepIndex: event.stepIndex,
topicId: context.topicId ?? undefined,
@@ -272,6 +273,9 @@ export const createGatewayEventHandler = (
void emitClientAgentSignalSourceEvent({
payload: {
agentId: context.agentId,
+ ...(currentAssistantMessageId
+ ? { assistantMessageId: currentAssistantMessageId }
+ : {}),
operationId,
topicId: context.topicId ?? undefined,
},