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): persist memory receipt routing metadata (#14912)

AmAzing-d6b5e81a5731
diff --git a/src/features/Conversation/ChatList/components/AgentSignalReceiptList.test.tsx b/src/features/Conversation/ChatList/components/AgentSignalReceiptList.test.tsx
index bc8f0aac454..fc87752efca 100644
--- a/src/features/Conversation/ChatList/components/AgentSignalReceiptList.test.tsx
+++ b/src/features/Conversation/ChatList/components/AgentSignalReceiptList.test.tsx
@@ -1,3 +1,4 @@
+import { LayersEnum } from '@lobechat/types';
import { fireEvent, render, screen } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
@@ -262,4 +263,37 @@ describe('AgentSignalReceiptList', () => {
expect(mocks.navigate).toHaveBeenCalledWith('/memory');
});
+
+ it('opens memory receipts on their layer detail route when target metadata is available', () => {
+ 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: {
+ id: 'preference-1',
+ memoryId: 'memory-1',
+ memoryLayer: LayersEnum.Preference,
+ title: 'Decision-first PR review preference',
+ type: 'memory',
+ },
+ title: 'Memory saved',
+ topicId: 'topic-1',
+ userId: 'user-1',
+ },
+ ]}
+ />,
+ );
+
+ fireEvent.click(screen.getByText('Open'));
+
+ expect(mocks.navigate).toHaveBeenCalledWith('/memory/preferences?preferenceId=preference-1');
+ });
});
diff --git a/src/features/Conversation/ChatList/components/AgentSignalReceiptList.tsx b/src/features/Conversation/ChatList/components/AgentSignalReceiptList.tsx
index 4a837886789..9a2dc75f10f 100644
--- a/src/features/Conversation/ChatList/components/AgentSignalReceiptList.tsx
+++ b/src/features/Conversation/ChatList/components/AgentSignalReceiptList.tsx
@@ -1,5 +1,6 @@
'use client';
+import { LayersEnum } from '@lobechat/types';
import { Icon } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
import type { LucideIcon } from 'lucide-react';
@@ -14,6 +15,13 @@ import { useChatStore } from '@/store/chat';
import type { AgentSignalReceiptView } from '../hooks/useAgentSignalReceipts';
const PAGE_ROUTE_PATTERN = /^\/agent\/([^/]+)\/([^/]+)\/page(?:\/[^/?#]+)?/;
+const MEMORY_ROUTE_BY_LAYER = {
+ [LayersEnum.Activity]: { idParam: 'activityId', path: '/memory/activities' },
+ [LayersEnum.Context]: { idParam: 'contextId', path: '/memory/contexts' },
+ [LayersEnum.Experience]: { idParam: 'experienceId', path: '/memory/experiences' },
+ [LayersEnum.Identity]: { idParam: 'identityId', path: '/memory/identities' },
+ [LayersEnum.Preference]: { idParam: 'preferenceId', path: '/memory/preferences' },
+} satisfies Record<LayersEnum, { idParam: string; path: string }>;
const styles = createStaticStyles(({ css, cssVar }) => ({
agentSignalDescription: css`
@@ -58,6 +66,17 @@ interface AgentSignalReceiptItemProps {
receipt: AgentSignalReceiptView;
}
+const getMemoryRoute = (target?: AgentSignalReceiptView['target']) => {
+ if (target?.type !== 'memory') return;
+
+ if (!target.memoryLayer) return '/memory';
+
+ const route = MEMORY_ROUTE_BY_LAYER[target.memoryLayer];
+ if (!route) return '/memory';
+
+ return target.id ? `${route.path}?${route.idParam}=${encodeURIComponent(target.id)}` : route.path;
+};
+
const AgentSignalReceiptItem = memo<AgentSignalReceiptItemProps>(({ receipt }) => {
const { t } = useTranslation(['chat', 'common']);
const navigate = useStableNavigate();
@@ -84,10 +103,11 @@ const AgentSignalReceiptItem = memo<AgentSignalReceiptItemProps>(({ receipt }) =
);
const target = receipt.target;
const documentId = target?.type === 'skill' ? (target.documentId ?? target.id) : undefined;
- const canOpen = target?.type === 'memory' || Boolean(documentId);
+ const memoryRoute = getMemoryRoute(target);
+ const canOpen = Boolean(memoryRoute) || Boolean(documentId);
const handleOpen = useCallback(() => {
- if (target?.type === 'memory') {
- navigate('/memory');
+ if (memoryRoute) {
+ navigate(memoryRoute);
return;
}
@@ -103,7 +123,7 @@ const AgentSignalReceiptItem = memo<AgentSignalReceiptItemProps>(({ receipt }) =
}
openDocument(documentId);
- }, [documentId, navigate, openDocument, target]);
+ }, [documentId, memoryRoute, navigate, openDocument, target]);
return (
<PortalResourceCard
@@ -112,7 +132,6 @@ const AgentSignalReceiptItem = memo<AgentSignalReceiptItemProps>(({ receipt }) =
openLabel={canOpen ? t('common:cmdk.toOpen', 'Open') : undefined}
title={title}
tooltip={tooltip}
- // TODO: Replace memory fallback with category/id-aware routes when Agent Signal receipts expose them.
onOpen={canOpen ? handleOpen : undefined}
/>
);
diff --git a/src/server/services/agentSignal/policies/analyzeIntent/actions/__tests__/userMemory.test.ts b/src/server/services/agentSignal/policies/analyzeIntent/actions/__tests__/userMemory.test.ts
index b41a0a18b42..67324c6b861 100644
--- a/src/server/services/agentSignal/policies/analyzeIntent/actions/__tests__/userMemory.test.ts
+++ b/src/server/services/agentSignal/policies/analyzeIntent/actions/__tests__/userMemory.test.ts
@@ -1,8 +1,9 @@
// @vitest-environment node
+import { LayersEnum } from '@lobechat/types';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { RuntimeProcessorContext } from '../../../../runtime/context';
-import { defineUserMemoryActionHandler } from '../userMemory';
+import { defineUserMemoryActionHandler, resolveMemoryActionTargetFromState } from '../userMemory';
const memoryActionRunner = vi.fn();
@@ -73,6 +74,64 @@ describe('defineUserMemoryActionHandler', () => {
expect(context.runtimeState.touchGuardState).toHaveBeenCalledTimes(1);
});
+ it('returns the applied memory target from the memory agent runner', async () => {
+ memoryActionRunner.mockResolvedValue({
+ detail: 'Arvin Xu 希望助手在输出时每个段落/模块都写得更长、更展开。',
+ status: 'applied',
+ target: {
+ id: 'mem_td3XirTeX4f7',
+ memoryId: 'mem_8gISOK6BhxGP',
+ memoryLayer: LayersEnum.Preference,
+ summary: 'Arvin Xu 希望助手在输出时每个段落/模块都写得更长、更展开。',
+ title: '偏好更详细、更长的回答段落',
+ type: 'memory',
+ },
+ });
+
+ const handler = defineUserMemoryActionHandler({
+ db: {} as never,
+ memoryActionRunner,
+ userId: 'user_1',
+ });
+
+ const result = await handler.handle(
+ {
+ actionId: 'act_memory_target',
+ actionType: 'action.user-memory.handle',
+ chain: { chainId: 'chain_1', rootSourceId: 'source_1' },
+ payload: {
+ agentId: 'agent_1',
+ idempotencyKey: 'source_1:memory:msg_1',
+ message:
+ '<speaker id="833816919" username="nivra2000" nickname="Aa T" />\n每一块都有点太短了?能否长一点呢',
+ topicId: 'topic_1',
+ },
+ signal: {
+ signalId: 'sig_1',
+ signalType: 'signal.feedback.domain.memory',
+ },
+ source: { sourceId: 'source_1', sourceType: 'agent.user.message' },
+ timestamp: 1,
+ },
+ context,
+ );
+
+ expect(result).toMatchObject({
+ detail: 'Arvin Xu 希望助手在输出时每个段落/模块都写得更长、更展开。',
+ output: {
+ target: {
+ id: 'mem_td3XirTeX4f7',
+ memoryId: 'mem_8gISOK6BhxGP',
+ memoryLayer: LayersEnum.Preference,
+ summary: 'Arvin Xu 希望助手在输出时每个段落/模块都写得更长、更展开。',
+ title: '偏好更详细、更长的回答段落',
+ type: 'memory',
+ },
+ },
+ status: 'applied',
+ });
+ });
+
it('skips memory actions when the feedback message is missing', async () => {
const handler = defineUserMemoryActionHandler({
db: {} as never,
@@ -241,3 +300,301 @@ describe('defineUserMemoryActionHandler', () => {
expect(memoryActionRunner).toHaveBeenCalledTimes(2);
});
});
+
+describe('resolveMemoryActionTargetFromState', () => {
+ it('extracts the successful memory title from runtime tool calls', () => {
+ const target = resolveMemoryActionTargetFromState({
+ messages: [
+ {
+ id: 'msg_bad',
+ role: 'assistant',
+ tool_calls: [
+ {
+ function: {
+ arguments: '{,',
+ name: 'lobe-user-memory____addPreferenceMemory',
+ },
+ id: 'call_bad',
+ type: 'function',
+ },
+ ],
+ },
+ {
+ content: 'The tool call arguments string is not valid JSON.',
+ role: 'tool',
+ tool_call_id: 'call_bad',
+ },
+ {
+ id: 'msg_good',
+ role: 'assistant',
+ tool_calls: [
+ {
+ function: {
+ arguments: JSON.stringify({
+ details: '用户反馈当前回复的每个模块都太短,希望后续展开得更充分。',
+ summary: 'Arvin Xu 希望助手在输出时每个段落/模块都写得更长、更展开。',
+ title: '偏好更详细、更长的回答段落',
+ withPreference: {
+ conclusionDirectives: '回答时展开每个段落和模块。',
+ },
+ }),
+ name: 'lobe-user-memory____addPreferenceMemory',
+ },
+ id: 'call_good',
+ type: 'function',
+ },
+ ],
+ },
+ {
+ content:
+ 'Preference memory "偏好更详细、更长的回答段落" saved with memoryId: "mem_8gISOK6BhxGP" and preferenceId: "mem_td3XirTeX4f7"',
+ role: 'tool',
+ tool_call_id: 'call_good',
+ },
+ ],
+ } as never);
+
+ expect(target).toEqual({
+ id: 'mem_td3XirTeX4f7',
+ memoryId: 'mem_8gISOK6BhxGP',
+ memoryLayer: LayersEnum.Preference,
+ summary: 'Arvin Xu 希望助手在输出时每个段落/模块都写得更长、更展开。',
+ title: '偏好更详细、更长的回答段落',
+ type: 'memory',
+ });
+ });
+
+ it('resolves update identity targets from nested set arguments', () => {
+ const target = resolveMemoryActionTargetFromState({
+ messages: [
+ {
+ id: 'msg_update_identity',
+ role: 'assistant',
+ tool_calls: [
+ {
+ function: {
+ arguments: JSON.stringify({
+ id: 'identity-existing',
+ mergeStrategy: 'replace',
+ set: {
+ details: 'The user clarified that they maintain LobeHub Agent Signal code.',
+ summary: 'The user maintains Agent Signal memory receipt behavior.',
+ title: 'Maintains Agent Signal receipts',
+ },
+ }),
+ name: 'lobe-user-memory____updateIdentityMemory',
+ },
+ id: 'call_update_identity',
+ type: 'function',
+ },
+ ],
+ },
+ {
+ content: 'Identity memory updated: identity-existing',
+ pluginState: { identityId: 'identity-existing' },
+ role: 'tool',
+ tool_call_id: 'call_update_identity',
+ },
+ ],
+ } as never);
+
+ expect(target).toEqual({
+ id: 'identity-existing',
+ memoryLayer: LayersEnum.Identity,
+ summary: 'The user maintains Agent Signal memory receipt behavior.',
+ title: 'Maintains Agent Signal receipts',
+ type: 'memory',
+ });
+ });
+
+ it('resolves receipt targets from persisted tool snapshots', () => {
+ const target = resolveMemoryActionTargetFromState({
+ messages: [
+ {
+ id: 'msg_persisted_tool',
+ role: 'assistant',
+ tools: [
+ null,
+ {
+ apiName: 'addPreferenceMemory',
+ arguments: {
+ title: 'Persisted preference title',
+ withPreference: {
+ conclusionDirectives: 'Use persisted tool metadata for receipt targets.',
+ },
+ },
+ id: 'call_persisted',
+ identifier: 'lobe-user-memory',
+ },
+ ],
+ },
+ {
+ content: 'Preference memory saved',
+ plugin: { id: 'call_persisted' },
+ pluginState: { memoryId: 'mem_persisted', preferenceId: 'pref_persisted' },
+ role: 'tool',
+ },
+ ],
+ } as never);
+
+ expect(target).toEqual({
+ id: 'pref_persisted',
+ memoryId: 'mem_persisted',
+ memoryLayer: LayersEnum.Preference,
+ summary: 'Use persisted tool metadata for receipt targets.',
+ title: 'Persisted preference title',
+ type: 'memory',
+ });
+ });
+
+ it('skips confirmed memory tool calls with invalid arguments', () => {
+ const target = resolveMemoryActionTargetFromState({
+ messages: [
+ {
+ id: 'msg_confirmed',
+ role: 'assistant',
+ tool_calls: [
+ {
+ function: {
+ arguments: JSON.stringify({
+ details: 'Fallback details for a valid confirmed target.',
+ title: 'Valid confirmed preference',
+ }),
+ name: 'lobe-user-memory____addPreferenceMemory',
+ },
+ id: 'call_confirmed',
+ type: 'function',
+ },
+ ],
+ },
+ {
+ content:
+ 'Preference memory "Valid confirmed preference" saved with memoryId: "mem_confirmed" and preferenceId: "pref_confirmed"',
+ role: 'tool',
+ tool_call_id: 'call_confirmed',
+ },
+ {
+ id: 'msg_invalid',
+ role: 'assistant',
+ tool_calls: [
+ {
+ function: {
+ arguments: '{,',
+ name: 'lobe-user-memory____addPreferenceMemory',
+ },
+ id: 'call_invalid',
+ type: 'function',
+ },
+ ],
+ },
+ {
+ content:
+ 'Preference memory "Invalid latest preference" saved with memoryId: "mem_invalid" and preferenceId: "pref_invalid"',
+ role: 'tool',
+ tool_call_id: 'call_invalid',
+ },
+ ],
+ } as never);
+
+ expect(target).toEqual({
+ id: 'pref_confirmed',
+ memoryId: 'mem_confirmed',
+ memoryLayer: LayersEnum.Preference,
+ summary: 'Fallback details for a valid confirmed target.',
+ title: 'Valid confirmed preference',
+ type: 'memory',
+ });
+ });
+
+ it('ignores unconfirmed memory write tool calls when resolving receipt targets', () => {
+ const target = resolveMemoryActionTargetFromState({
+ messages: [
+ {
+ id: 'msg_confirmed',
+ role: 'assistant',
+ tool_calls: [
+ {
+ function: {
+ arguments: JSON.stringify({
+ summary: 'The user prefers longer, more developed answers.',
+ title: 'Confirmed preference title',
+ }),
+ name: 'lobe-user-memory____addPreferenceMemory',
+ },
+ id: 'call_confirmed',
+ type: 'function',
+ },
+ ],
+ },
+ {
+ content:
+ 'Preference memory "Confirmed preference title" saved with memoryId: "mem_confirmed" and preferenceId: "pref_confirmed"',
+ role: 'tool',
+ tool_call_id: 'call_confirmed',
+ },
+ {
+ id: 'msg_unconfirmed',
+ role: 'assistant',
+ tool_calls: [
+ {
+ function: {
+ arguments: JSON.stringify({
+ summary: 'This write was not confirmed by a successful tool result.',
+ title: 'Unconfirmed preference title',
+ }),
+ name: 'lobe-user-memory____addPreferenceMemory',
+ },
+ id: 'call_unconfirmed',
+ type: 'function',
+ },
+ ],
+ },
+ {
+ content: 'addPreferenceMemory with error detail: database timeout',
+ role: 'tool',
+ tool_call_id: 'call_unconfirmed',
+ },
+ ],
+ } as never);
+
+ expect(target).toEqual({
+ id: 'pref_confirmed',
+ memoryId: 'mem_confirmed',
+ memoryLayer: LayersEnum.Preference,
+ summary: 'The user prefers longer, more developed answers.',
+ title: 'Confirmed preference title',
+ type: 'memory',
+ });
+ });
+
+ it('does not resolve a target when no memory write has a successful tool result', () => {
+ const target = resolveMemoryActionTargetFromState({
+ messages: [
+ {
+ id: 'msg_unconfirmed',
+ role: 'assistant',
+ tool_calls: [
+ {
+ function: {
+ arguments: JSON.stringify({
+ summary: 'This write was not confirmed by a successful tool result.',
+ title: 'Unconfirmed preference title',
+ }),
+ name: 'lobe-user-memory____addPreferenceMemory',
+ },
+ id: 'call_unconfirmed',
+ type: 'function',
+ },
+ ],
+ },
+ {
+ content: 'addPreferenceMemory with error detail: database timeout',
+ role: 'tool',
+ tool_call_id: 'call_unconfirmed',
+ },
+ ],
+ } as never);
+
+ expect(target).toBeUndefined();
+ });
+});
diff --git a/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts b/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts
index 597b77d80c6..8aa23ca6b1e 100644
--- a/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts
+++ b/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts
@@ -11,7 +11,7 @@ import {
createAgentSignalMemoryWriterPrompt,
createAgentSignalMemoryWriterSystemRole,
} from '@lobechat/prompts';
-import { RequestTrigger } from '@lobechat/types';
+import { LayersEnum, RequestTrigger } from '@lobechat/types';
import { nanoid } from '@lobechat/utils';
import { PluginModel } from '@/database/models/plugin';
@@ -44,21 +44,45 @@ import { AGENT_SIGNAL_POLICY_ACTION_TYPES } from '../../types';
const MEMORY_AGENT_MAX_STEPS = 8;
+const MEMORY_WRITE_API_NAMES = [
+ MemoryApiName.addActivityMemory,
+ MemoryApiName.addContextMemory,
+ MemoryApiName.addExperienceMemory,
+ MemoryApiName.addIdentityMemory,
+ MemoryApiName.addPreferenceMemory,
+ MemoryApiName.removeIdentityMemory,
+ MemoryApiName.updateIdentityMemory,
+] as const;
+
const MEMORY_WRITE_TOOL_NAMES = new Set(
- [
- MemoryApiName.addActivityMemory,
- MemoryApiName.addContextMemory,
- MemoryApiName.addExperienceMemory,
- MemoryApiName.addIdentityMemory,
- MemoryApiName.addPreferenceMemory,
- MemoryApiName.removeIdentityMemory,
- MemoryApiName.updateIdentityMemory,
- ].map((apiName) => `${MemoryIdentifier}/${apiName}`),
+ MEMORY_WRITE_API_NAMES.map((apiName) => `${MemoryIdentifier}/${apiName}`),
);
+const MEMORY_WRITE_API_NAME_SET = new Set<string>(MEMORY_WRITE_API_NAMES);
+const MEMORY_WRITE_TARGET_BY_API_NAME: Record<string, { idKey: string; layer: LayersEnum }> = {
+ [MemoryApiName.addActivityMemory]: { idKey: 'activityId', layer: LayersEnum.Activity },
+ [MemoryApiName.addContextMemory]: { idKey: 'contextId', layer: LayersEnum.Context },
+ [MemoryApiName.addExperienceMemory]: { idKey: 'experienceId', layer: LayersEnum.Experience },
+ [MemoryApiName.addIdentityMemory]: { idKey: 'identityId', layer: LayersEnum.Identity },
+ [MemoryApiName.addPreferenceMemory]: { idKey: 'preferenceId', layer: LayersEnum.Preference },
+ [MemoryApiName.removeIdentityMemory]: { idKey: 'identityId', layer: LayersEnum.Identity },
+ [MemoryApiName.updateIdentityMemory]: { idKey: 'identityId', layer: LayersEnum.Identity },
+};
+const TOOL_NAME_SEPARATOR = '____';
+
+export interface MemoryActionTarget {
+ id?: string;
+ memoryId?: string;
+ memoryLayer?: LayersEnum;
+ summary?: string;
+ title: string;
+ type: 'memory';
+}
+
export interface MemoryAgentActionResult {
detail?: string;
status: 'applied' | 'failed' | 'skipped';
+ target?: MemoryActionTarget;
}
export interface UserMemoryActionHandlerOptions {
@@ -153,6 +177,196 @@ const hasFailedMemoryWrite = (state: AgentState) => {
);
};
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === 'object' && value !== null && !Array.isArray(value);
+
+const getString = (value: unknown) => {
+ return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;
+};
+
+const parseToolArguments = (value: unknown): Record<string, unknown> | undefined => {
+ if (isRecord(value)) return value;
+
+ if (typeof value !== 'string') return;
+
+ try {
+ const parsed: unknown = JSON.parse(value);
+
+ return isRecord(parsed) ? parsed : undefined;
+ } catch {
+ return;
+ }
+};
+
+interface MemoryToolCallSnapshot {
+ apiName?: string;
+ arguments?: unknown;
+ id?: string;
+ identifier?: string;
+}
+
+const getToolCallsFromMessage = (message: unknown): MemoryToolCallSnapshot[] => {
+ if (!isRecord(message)) return [];
+
+ const toolCalls: MemoryToolCallSnapshot[] = [];
+ const persistedTools = Array.isArray(message.tools) ? message.tools : [];
+
+ for (const tool of persistedTools) {
+ if (!isRecord(tool)) continue;
+
+ toolCalls.push({
+ apiName: getString(tool.apiName),
+ arguments: tool.arguments,
+ id: getString(tool.id),
+ identifier: getString(tool.identifier),
+ });
+ }
+
+ const rawToolCalls = Array.isArray(message.tool_calls) ? message.tool_calls : [];
+
+ for (const toolCall of rawToolCalls) {
+ if (!isRecord(toolCall)) continue;
+
+ const fn = isRecord(toolCall.function) ? toolCall.function : undefined;
+ const name = getString(fn?.name);
+ if (!name) continue;
+
+ const [identifier, apiName] = name.split(TOOL_NAME_SEPARATOR);
+
+ toolCalls.push({
+ apiName: apiName || name,
+ arguments: fn?.arguments,
+ id: getString(toolCall.id),
+ identifier: apiName ? identifier : undefined,
+ });
+ }
+
+ return toolCalls;
+};
+
+const isMemoryWriteToolCall = (
+ toolCall: MemoryToolCallSnapshot,
+): toolCall is MemoryToolCallSnapshot & { apiName: string } => {
+ if (!toolCall.apiName || !MEMORY_WRITE_API_NAME_SET.has(toolCall.apiName)) return false;
+
+ return !toolCall.identifier || toolCall.identifier === MemoryIdentifier;
+};
+
+const getToolMessageCallId = (message: unknown) => {
+ if (!isRecord(message)) return;
+
+ const plugin = isRecord(message.plugin) ? message.plugin : undefined;
+
+ return getString(message.tool_call_id) ?? getString(plugin?.id);
+};
+
+const getMemoryIdsFromToolMessage = (message: unknown) => {
+ if (!isRecord(message)) return;
+
+ const ids: Record<string, string> = {};
+ const addId = (key: string, value: unknown) => {
+ if (!key.endsWith('Id')) return;
+
+ const id = getString(value);
+ if (id) ids[key] = id;
+ };
+
+ const pluginState = isRecord(message.pluginState) ? message.pluginState : undefined;
+ if (pluginState) {
+ for (const [key, value] of Object.entries(pluginState)) {
+ addId(key, value);
+ }
+ }
+
+ const content = getString(message.content);
+ if (content) {
+ for (const match of content.matchAll(/([A-Za-z]\w*Id):\s*"([^"]+)"/g)) {
+ addId(match[1], match[2]);
+ }
+ }
+
+ return Object.keys(ids).length > 0 ? ids : undefined;
+};
+
+const getMemoryToolResultIds = (state: AgentState) => {
+ const resultIds = new Map<string, Record<string, string>>();
+
+ for (const message of state.messages ?? []) {
+ const callId = getToolMessageCallId(message);
+ const ids = getMemoryIdsFromToolMessage(message);
+
+ if (callId && ids) resultIds.set(callId, ids);
+ }
+
+ return resultIds;
+};
+
+const getNestedString = (payload: Record<string, unknown>, keys: string[]) => {
+ let current: unknown = payload;
+
+ for (const key of keys) {
+ if (!isRecord(current)) return;
+
+ current = current[key];
+ }
+
+ return getString(current);
+};
+
+const getToolArgumentString = (args: Record<string, unknown>, key: string) => {
+ return getString(args[key]) ?? getNestedString(args, ['set', key]);
+};
+
+const createTargetFromToolArguments = (
+ args: Record<string, unknown>,
+ toolCall: MemoryToolCallSnapshot & { apiName: string },
+ resultIds?: Record<string, string>,
+): MemoryActionTarget | undefined => {
+ const title = getToolArgumentString(args, 'title');
+ if (!title) return;
+
+ const targetConfig = MEMORY_WRITE_TARGET_BY_API_NAME[toolCall.apiName];
+ const id = targetConfig ? resultIds?.[targetConfig.idKey] : undefined;
+ const memoryId = resultIds?.memoryId;
+ const summary =
+ getToolArgumentString(args, 'summary') ??
+ getToolArgumentString(args, 'details') ??
+ getNestedString(args, ['withPreference', 'conclusionDirectives']);
+
+ return {
+ ...((id ?? memoryId) ? { id: id ?? memoryId } : {}),
+ ...(memoryId ? { memoryId } : {}),
+ ...(targetConfig ? { memoryLayer: targetConfig.layer } : {}),
+ ...(summary ? { summary } : {}),
+ title,
+ type: 'memory',
+ };
+};
+
+export const resolveMemoryActionTargetFromState = (
+ state: AgentState,
+): MemoryActionTarget | undefined => {
+ const resultIds = getMemoryToolResultIds(state);
+
+ for (const message of [...(state.messages ?? [])].reverse()) {
+ const toolCalls = getToolCallsFromMessage(message).reverse();
+
+ for (const toolCall of toolCalls) {
+ if (!isMemoryWriteToolCall(toolCall)) continue;
+ if (!toolCall.id) continue;
+
+ const confirmedResultIds = resultIds.get(toolCall.id);
+ if (!confirmedResultIds) continue;
+
+ const args = parseToolArguments(toolCall.arguments);
+ if (!args) continue;
+
+ const target = createTargetFromToolArguments(args, toolCall, confirmedResultIds);
+ if (target) return target;
+ }
+ }
+};
+
export const runMemoryActionAgent = async (
input: {
agentId?: string;
@@ -289,7 +503,13 @@ export const runMemoryActionAgent = async (
}
if (hasSuccessfulMemoryWrite(finalState)) {
- return { status: 'applied' };
+ const target = resolveMemoryActionTargetFromState(finalState);
+
+ return {
+ ...(target?.summary ? { detail: target.summary } : {}),
+ status: 'applied',
+ ...(target ? { target } : {}),
+ };
}
if (hasFailedMemoryWrite(finalState)) {
@@ -372,13 +592,15 @@ export const handleUserMemoryAction = async (
topicId: typeof action.payload.topicId === 'string' ? action.payload.topicId : undefined,
};
const runner = options.memoryActionRunner ?? ((input) => runMemoryActionAgent(input, options));
+ let memoryActionResult: MemoryAgentActionResult | undefined;
const memoryService = createMemoryService({
writeMemory: async () => {
const result = await runner(runnerInput);
+ memoryActionResult = result;
if (result.status === 'applied') {
return {
- memoryId: idempotencyKey ?? action.actionId,
+ memoryId: result.target?.id ?? idempotencyKey ?? action.actionId,
summary: result.detail,
};
}
@@ -402,6 +624,7 @@ export const handleUserMemoryAction = async (
.then<MemoryAgentActionResult>((writeResult) => ({
detail: writeResult.summary,
status: 'applied',
+ ...(memoryActionResult?.target ? { target: memoryActionResult.target } : {}),
}))
.catch((error: unknown): MemoryAgentActionResult => {
if (error instanceof MemoryActionError) {
@@ -421,6 +644,7 @@ export const handleUserMemoryAction = async (
actionId: action.actionId,
attempt: finalizeAttempt(startedAt, 'succeeded'),
detail: result.detail,
+ ...(result.target ? { output: { target: result.target } } : {}),
status: 'applied',
};
}
diff --git a/src/server/services/agentSignal/services/__tests__/receiptService.test.ts b/src/server/services/agentSignal/services/__tests__/receiptService.test.ts
index fe87856d2e3..7dc38fd9ed1 100644
--- a/src/server/services/agentSignal/services/__tests__/receiptService.test.ts
+++ b/src/server/services/agentSignal/services/__tests__/receiptService.test.ts
@@ -1,6 +1,7 @@
// @vitest-environment node
import type { BaseAction, ExecutorResult } from '@lobechat/agent-signal';
import { createSource } from '@lobechat/agent-signal';
+import { LayersEnum } from '@lobechat/types';
import { describe, expect, it, vi } from 'vitest';
import { AGENT_SIGNAL_POLICY_ACTION_TYPES } from '../../policies/types';
@@ -52,7 +53,7 @@ const result = (input: {
});
describe('projectAgentSignalReceipts', () => {
- it('projects applied memory action results', () => {
+ it('projects applied memory action results without unstructured feedback as target', () => {
expect(
projectAgentSignalReceipts({
actions: [
@@ -78,10 +79,6 @@ describe('projectAgentSignalReceipts', () => {
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',
@@ -89,6 +86,53 @@ describe('projectAgentSignalReceipts', () => {
]);
});
+ it('prefers the memory target title from action output over the feedback message', () => {
+ expect(
+ projectAgentSignalReceipts({
+ actions: [
+ action({
+ actionId: 'action-memory-1',
+ actionType: AGENT_SIGNAL_POLICY_ACTION_TYPES.userMemoryHandle,
+ payload: {
+ message:
+ '<speaker id="833816919" username="nivra2000" nickname="Aa T" />\nEvery section is too short. Can it be longer?',
+ },
+ }),
+ ],
+ results: [
+ result({
+ actionId: 'action-memory-1',
+ output: {
+ target: {
+ id: 'preference_1',
+ memoryId: 'mem_1',
+ memoryLayer: LayersEnum.Preference,
+ summary: 'The user prefers longer, more developed answer sections.',
+ title: 'Preference for detailed answer sections',
+ type: 'memory',
+ },
+ },
+ status: 'applied',
+ }),
+ ],
+ source,
+ userId: 'user-1',
+ }),
+ ).toMatchObject([
+ {
+ kind: 'memory',
+ target: {
+ id: 'preference_1',
+ memoryId: 'mem_1',
+ memoryLayer: LayersEnum.Preference,
+ summary: 'The user prefers longer, more developed answer sections.',
+ title: 'Preference for detailed answer sections',
+ type: 'memory',
+ },
+ },
+ ]);
+ });
+
it('projects applied skill-management results as updated skill receipts', () => {
expect(
projectAgentSignalReceipts({
diff --git a/src/server/services/agentSignal/services/receiptService.ts b/src/server/services/agentSignal/services/receiptService.ts
index 8297caa59d9..5790210efbb 100644
--- a/src/server/services/agentSignal/services/receiptService.ts
+++ b/src/server/services/agentSignal/services/receiptService.ts
@@ -1,4 +1,5 @@
import type { AgentSignalSource, BaseAction, ExecutorResult } from '@lobechat/agent-signal';
+import { LayersEnum } from '@lobechat/types';
import { AGENT_SIGNAL_DEFAULTS } from '../constants';
import { AGENT_SIGNAL_POLICY_ACTION_TYPES } from '../policies/types';
@@ -93,6 +94,10 @@ export interface AgentSignalReceipt {
documentId?: string;
/** Backing resource id for future navigation when still available. Skill ids use `documents.id`. */
id?: string;
+ /** User memory base id for audit and fallback lookup. */
+ memoryId?: string;
+ /** User memory layer used to route memory receipts to their detail page. */
+ memoryLayer?: LayersEnum;
/** Short summary captured at write time. */
summary?: string;
/** Human-readable resource title captured at write time. */
@@ -236,6 +241,10 @@ const getPayloadString = (payload: Record<string, unknown>, key: string) => {
const getClampedString = (value: string, maxLength = 96) =>
value.length > maxLength ? `${value.slice(0, maxLength - 1)}...` : value;
+const isMemoryLayer = (value: unknown): value is LayersEnum => {
+ return Object.values(LayersEnum).includes(value as LayersEnum);
+};
+
const getReceiptTarget = (
action: BaseAction,
result: ExecutorResult,
@@ -262,6 +271,12 @@ const getReceiptTarget = (
? { documentId: payload.documentId }
: {}),
...(typeof payload.id === 'string' && payload.id.length > 0 ? { id: payload.id } : {}),
+ ...(type === 'memory' && typeof payload.memoryId === 'string' && payload.memoryId.length > 0
+ ? { memoryId: payload.memoryId }
+ : {}),
+ ...(type === 'memory' && isMemoryLayer(payload.memoryLayer)
+ ? { memoryLayer: payload.memoryLayer }
+ : {}),
...(typeof payload.summary === 'string' && payload.summary.length > 0
? { summary: payload.summary }
: {}),
@@ -272,14 +287,6 @@ const getReceiptTarget = (
}
if (kind !== 'memory') return;
-
- const message = getPayloadString(action.payload, 'message')?.trim();
- if (!message) return;
-
- return {
- title: getClampedString(message),
- type: 'memory',
- };
};
const toReceiptKind = (
diff --git a/src/server/services/agentSignal/store/__tests__/redisReceiptStore.test.ts b/src/server/services/agentSignal/store/__tests__/redisReceiptStore.test.ts
index ce15194819e..0b4eedc2518 100644
--- a/src/server/services/agentSignal/store/__tests__/redisReceiptStore.test.ts
+++ b/src/server/services/agentSignal/store/__tests__/redisReceiptStore.test.ts
@@ -1,4 +1,5 @@
// @vitest-environment node
+import { LayersEnum } from '@lobechat/types';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
@@ -27,6 +28,9 @@ const receipt = {
sourceType: 'client.gateway.runtime_end',
status: 'applied' as const,
target: {
+ id: 'preference-1',
+ memoryId: 'memory-1',
+ memoryLayer: LayersEnum.Preference,
summary: 'Use short answers in future chats',
title: 'Short answer preference',
type: 'memory' as const,
@@ -61,6 +65,9 @@ describe('redis receipt store', () => {
sourceType: 'client.gateway.runtime_end',
status: 'applied',
target: JSON.stringify({
+ id: 'preference-1',
+ memoryId: 'memory-1',
+ memoryLayer: LayersEnum.Preference,
summary: 'Use short answers in future chats',
title: 'Short answer preference',
type: 'memory',
diff --git a/src/server/services/agentSignal/store/adapters/redis/receiptStore.ts b/src/server/services/agentSignal/store/adapters/redis/receiptStore.ts
index 50388f5ec8a..61963922f1e 100644
--- a/src/server/services/agentSignal/store/adapters/redis/receiptStore.ts
+++ b/src/server/services/agentSignal/store/adapters/redis/receiptStore.ts
@@ -1,3 +1,5 @@
+import { LayersEnum } from '@lobechat/types';
+
import { AGENT_SIGNAL_KEYS } from '../../../constants';
import type { AgentSignalReceipt } from '../../../services/receiptService';
import type { AgentSignalReceiptStore } from '../../types';
@@ -21,6 +23,9 @@ const toReceiptHash = (receipt: AgentSignalReceipt): Record<string, string> => (
userId: receipt.userId,
});
+const isMemoryLayer = (value: unknown): value is LayersEnum =>
+ Object.values(LayersEnum).includes(value as LayersEnum);
+
const parseReceiptTarget = (value?: string): AgentSignalReceipt['target'] | undefined => {
if (!value) return;
@@ -38,6 +43,14 @@ const parseReceiptTarget = (value?: string): AgentSignalReceipt['target'] | unde
? { documentId: target.documentId }
: {}),
...(typeof target.id === 'string' && target.id.length > 0 ? { id: target.id } : {}),
+ ...(target.type === 'memory' &&
+ typeof target.memoryId === 'string' &&
+ target.memoryId.length > 0
+ ? { memoryId: target.memoryId }
+ : {}),
+ ...(target.type === 'memory' && isMemoryLayer(target.memoryLayer)
+ ? { memoryLayer: target.memoryLayer }
+ : {}),
...(typeof target.summary === 'string' && target.summary.length > 0
? { summary: target.summary }
: {}),