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: fix identity memory not working (#10916)

Arvin Xufbd0b666f04a
diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.json
index c6caedcf0aa..2bd354a0b4b 100644
--- a/locales/en-US/plugin.json
+++ b/locales/en-US/plugin.json
@@ -92,6 +92,14 @@
"builtins.lobe-page-agent.apiName.updateNode": "Update Node",
"builtins.lobe-page-agent.apiName.wrapNodes": "Wrap Nodes",
"builtins.lobe-page-agent.title": "Page",
+ "builtins.lobe-user-memory.apiName.addContextMemory": "Add Context Memory",
+ "builtins.lobe-user-memory.apiName.addExperienceMemory": "Add Experience Memory",
+ "builtins.lobe-user-memory.apiName.addIdentityMemory": "Add Identity Memory",
+ "builtins.lobe-user-memory.apiName.addPreferenceMemory": "Add Preference Memory",
+ "builtins.lobe-user-memory.apiName.removeIdentityMemory": "Remove Identity Memory",
+ "builtins.lobe-user-memory.apiName.searchUserMemory": "Search Memory",
+ "builtins.lobe-user-memory.apiName.updateIdentityMemory": "Update Identity Memory",
+ "builtins.lobe-user-memory.title": "Memory",
"builtins.lobe-web-browsing.apiName.crawlMultiPages": "Read Multiple Pages",
"builtins.lobe-web-browsing.apiName.crawlSinglePage": "Read Page Content",
"builtins.lobe-web-browsing.apiName.search": "Search Web Pages",
diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.json
index 19223fc639d..8876d8b26a2 100644
--- a/locales/zh-CN/plugin.json
+++ b/locales/zh-CN/plugin.json
@@ -92,6 +92,14 @@
"builtins.lobe-page-agent.apiName.updateNode": "更新节点",
"builtins.lobe-page-agent.apiName.wrapNodes": "包装节点",
"builtins.lobe-page-agent.title": "文档",
+ "builtins.lobe-user-memory.apiName.addContextMemory": "添加情境记忆",
+ "builtins.lobe-user-memory.apiName.addExperienceMemory": "添加经验记忆",
+ "builtins.lobe-user-memory.apiName.addIdentityMemory": "添加身份记忆",
+ "builtins.lobe-user-memory.apiName.addPreferenceMemory": "添加偏好记忆",
+ "builtins.lobe-user-memory.apiName.removeIdentityMemory": "删除身份记忆",
+ "builtins.lobe-user-memory.apiName.searchUserMemory": "搜索记忆",
+ "builtins.lobe-user-memory.apiName.updateIdentityMemory": "更新身份记忆",
+ "builtins.lobe-user-memory.title": "记忆",
"builtins.lobe-web-browsing.apiName.crawlMultiPages": "读取多个页面内容",
"builtins.lobe-web-browsing.apiName.crawlSinglePage": "读取页面内容",
"builtins.lobe-web-browsing.apiName.search": "搜索页面",
diff --git a/packages/builtin-agents/src/agents/inbox/systemRole.ts b/packages/builtin-agents/src/agents/inbox/systemRole.ts
index d42a585264d..9a36a50d6c9 100644
--- a/packages/builtin-agents/src/agents/inbox/systemRole.ts
+++ b/packages/builtin-agents/src/agents/inbox/systemRole.ts
@@ -6,7 +6,7 @@
export const systemRole = `You are Lobe, an AI Agent will help users.
Current model: {{model}}
-Today's date: {{currentDate}}
+Today's date: {{date}}
Your role is to:
- Answer questions accurately and helpfully
diff --git a/packages/builtin-tool-memory/src/systemRole.ts b/packages/builtin-tool-memory/src/systemRole.ts
index c3564895704..ab4b4f2a0f5 100644
--- a/packages/builtin-tool-memory/src/systemRole.ts
+++ b/packages/builtin-tool-memory/src/systemRole.ts
@@ -4,7 +4,6 @@ export const systemPrompt = `You have a LobeHub Memory Tool. This tool is to rec
Current user: {{username}}
Session date: {{date}}
Conversation language: {{language}}
-Available memory categories: {{available_categories}}
</session_context>
<core_responsibilities>
diff --git a/packages/context-engine/src/base/BaseFirstUserContentProvider.ts b/packages/context-engine/src/base/BaseFirstUserContentProvider.ts
new file mode 100644
index 00000000000..3c8056b2951
--- /dev/null
+++ b/packages/context-engine/src/base/BaseFirstUserContentProvider.ts
@@ -0,0 +1,142 @@
+import type { Message, PipelineContext, ProcessorOptions } from '../types';
+import { BaseProcessor } from './BaseProcessor';
+
+/**
+ * Marker to identify system injection messages
+ */
+const SYSTEM_INJECTION_MARKER = 'systemInjection';
+
+/**
+ * Base Provider for prepending content before the first user message
+ * Used for injecting static context like knowledge and user memories
+ *
+ * Features:
+ * - First provider creates a new user message before the first user message
+ * - Subsequent providers append to the existing system injection message
+ * - All injected content is consolidated into a single message
+ */
+export abstract class BaseFirstUserContentProvider extends BaseProcessor {
+ constructor(options: ProcessorOptions = {}) {
+ super(options);
+ }
+
+ /**
+ * Build the content to inject
+ * Subclasses must implement this method
+ * @returns The content string to inject, or null to skip injection
+ */
+ protected abstract buildContent(context: PipelineContext): string | null;
+
+ /**
+ * Find the index of the first user message
+ */
+ protected findFirstUserMessageIndex(messages: Message[]): number {
+ return messages.findIndex((msg) => msg.role === 'user');
+ }
+
+ /**
+ * Find the existing system injection message (if any)
+ */
+ protected findSystemInjectionMessage(messages: Message[]): Message | undefined {
+ return messages.find((msg) => msg.meta?.[SYSTEM_INJECTION_MARKER] === true);
+ }
+
+ /**
+ * Find the index of the existing system injection message
+ */
+ protected findSystemInjectionMessageIndex(messages: Message[]): number {
+ return messages.findIndex((msg) => msg.meta?.[SYSTEM_INJECTION_MARKER] === true);
+ }
+
+ /**
+ * Create a new system injection message
+ */
+ protected createSystemInjectionMessage(content: string): Message {
+ return {
+ content,
+ createdAt: Date.now(),
+ id: `system-injection-${Date.now()}`,
+ meta: { [SYSTEM_INJECTION_MARKER]: true },
+ role: 'user' as const,
+ updatedAt: Date.now(),
+ };
+ }
+
+ /**
+ * Append content to an existing message
+ */
+ protected appendToMessage(message: Message, contentToAppend: string): Message {
+ const currentContent = message.content;
+
+ if (typeof currentContent === 'string') {
+ return {
+ ...message,
+ content: currentContent + '\n\n' + contentToAppend,
+ updatedAt: Date.now(),
+ };
+ }
+
+ // Handle array content (multimodal messages) - find last text part and append
+ if (Array.isArray(currentContent)) {
+ const lastTextIndex = currentContent.findLastIndex((part: any) => part.type === 'text');
+
+ if (lastTextIndex !== -1) {
+ const newContent = [...currentContent];
+ newContent[lastTextIndex] = {
+ ...newContent[lastTextIndex],
+ text: newContent[lastTextIndex].text + '\n\n' + contentToAppend,
+ };
+ return {
+ ...message,
+ content: newContent,
+ updatedAt: Date.now(),
+ };
+ }
+
+ // No text part found, add a new one
+ return {
+ ...message,
+ content: [...currentContent, { text: contentToAppend, type: 'text' }],
+ updatedAt: Date.now(),
+ };
+ }
+
+ return message;
+ }
+
+ /**
+ * Process the context by injecting content before the first user message
+ * If a system injection message already exists, append to it instead
+ */
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ const content = this.buildContent(context);
+
+ if (!content) {
+ return this.markAsExecuted(context);
+ }
+
+ const clonedContext = this.cloneContext(context);
+ const existingIndex = this.findSystemInjectionMessageIndex(clonedContext.messages);
+
+ if (existingIndex !== -1) {
+ // Append to existing system injection message
+ clonedContext.messages[existingIndex] = this.appendToMessage(
+ clonedContext.messages[existingIndex],
+ content,
+ );
+ } else {
+ // Create new system injection message before first user message
+ const firstUserIndex = this.findFirstUserMessageIndex(clonedContext.messages);
+
+ if (firstUserIndex === -1) {
+ // No user messages found, skip injection
+ return this.markAsExecuted(clonedContext);
+ }
+
+ const injectionMessage = this.createSystemInjectionMessage(content);
+ clonedContext.messages.splice(firstUserIndex, 0, injectionMessage);
+ }
+
+ return this.markAsExecuted(clonedContext);
+ }
+}
diff --git a/packages/context-engine/src/base/__tests__/BaseFirstUserContentProvider.test.ts b/packages/context-engine/src/base/__tests__/BaseFirstUserContentProvider.test.ts
new file mode 100644
index 00000000000..b23b1580932
--- /dev/null
+++ b/packages/context-engine/src/base/__tests__/BaseFirstUserContentProvider.test.ts
@@ -0,0 +1,379 @@
+import { describe, expect, it } from 'vitest';
+
+import type { PipelineContext } from '../../types';
+import { BaseFirstUserContentProvider } from '../BaseFirstUserContentProvider';
+
+class TestFirstUserContentProvider extends BaseFirstUserContentProvider {
+ readonly name = 'TestFirstUserContentProvider';
+ private contentToReturn: string | null = 'Test content';
+
+ setContent(content: string | null) {
+ this.contentToReturn = content;
+ }
+
+ protected buildContent(_context: PipelineContext): string | null {
+ return this.contentToReturn;
+ }
+
+ // Expose protected methods for testing
+ testFindFirstUserMessageIndex(messages: any[]) {
+ return this.findFirstUserMessageIndex(messages);
+ }
+
+ testFindSystemInjectionMessage(messages: any[]) {
+ return this.findSystemInjectionMessage(messages);
+ }
+
+ testFindSystemInjectionMessageIndex(messages: any[]) {
+ return this.findSystemInjectionMessageIndex(messages);
+ }
+
+ testCreateSystemInjectionMessage(content: string) {
+ return this.createSystemInjectionMessage(content);
+ }
+
+ testAppendToMessage(message: any, content: string) {
+ return this.appendToMessage(message, content);
+ }
+}
+
+// Second provider for testing multiple injections
+class SecondFirstUserContentProvider extends BaseFirstUserContentProvider {
+ readonly name = 'SecondFirstUserContentProvider';
+
+ protected buildContent(_context: PipelineContext): string | null {
+ return 'Second content';
+ }
+}
+
+describe('BaseFirstUserContentProvider', () => {
+ const createContext = (messages: any[] = []): PipelineContext => ({
+ initialState: {
+ messages: [],
+ model: 'test-model',
+ provider: 'test-provider',
+ },
+ isAborted: false,
+ messages,
+ metadata: {
+ maxTokens: 4000,
+ model: 'test-model',
+ },
+ });
+
+ describe('findFirstUserMessageIndex', () => {
+ it('should find the first user message in a simple conversation', () => {
+ const provider = new TestFirstUserContentProvider();
+ const messages = [
+ { content: 'System prompt', role: 'system' },
+ { content: 'Hello', role: 'user' },
+ { content: 'Hi there', role: 'assistant' },
+ { content: 'How are you?', role: 'user' },
+ ];
+
+ const index = provider.testFindFirstUserMessageIndex(messages);
+ expect(index).toBe(1);
+ });
+
+ it('should find the first user message when it is at the beginning', () => {
+ const provider = new TestFirstUserContentProvider();
+ const messages = [
+ { content: 'Hello', role: 'user' },
+ { content: 'Hi there', role: 'assistant' },
+ ];
+
+ const index = provider.testFindFirstUserMessageIndex(messages);
+ expect(index).toBe(0);
+ });
+
+ it('should return -1 when no user messages exist', () => {
+ const provider = new TestFirstUserContentProvider();
+ const messages = [
+ { content: 'System prompt', role: 'system' },
+ { content: 'Assistant response', role: 'assistant' },
+ ];
+
+ const index = provider.testFindFirstUserMessageIndex(messages);
+ expect(index).toBe(-1);
+ });
+
+ it('should return -1 for empty messages array', () => {
+ const provider = new TestFirstUserContentProvider();
+ const index = provider.testFindFirstUserMessageIndex([]);
+ expect(index).toBe(-1);
+ });
+ });
+
+ describe('findSystemInjectionMessage', () => {
+ it('should find existing system injection message', () => {
+ const provider = new TestFirstUserContentProvider();
+ const messages = [
+ { content: 'System prompt', role: 'system' },
+ { content: 'Injected content', meta: { systemInjection: true }, role: 'user' },
+ { content: 'User message', role: 'user' },
+ ];
+
+ const message = provider.testFindSystemInjectionMessage(messages);
+ expect(message).toBeDefined();
+ expect(message?.content).toBe('Injected content');
+ });
+
+ it('should return undefined when no system injection message exists', () => {
+ const provider = new TestFirstUserContentProvider();
+ const messages = [
+ { content: 'System prompt', role: 'system' },
+ { content: 'User message', role: 'user' },
+ ];
+
+ const message = provider.testFindSystemInjectionMessage(messages);
+ expect(message).toBeUndefined();
+ });
+ });
+
+ describe('createSystemInjectionMessage', () => {
+ it('should create a properly structured message', () => {
+ const provider = new TestFirstUserContentProvider();
+ const message = provider.testCreateSystemInjectionMessage('Test content');
+
+ expect(message.content).toBe('Test content');
+ expect(message.role).toBe('user');
+ expect(message.meta?.systemInjection).toBe(true);
+ expect(message.id).toContain('system-injection-');
+ expect(message.createdAt).toBeDefined();
+ expect(message.updatedAt).toBeDefined();
+ });
+ });
+
+ describe('appendToMessage', () => {
+ it('should append content to string message content', () => {
+ const provider = new TestFirstUserContentProvider();
+ const message = { content: 'Original content', role: 'user' };
+
+ const result = provider.testAppendToMessage(message, 'Appended content');
+
+ expect(result.content).toBe('Original content\n\nAppended content');
+ });
+
+ it('should append content to array message content with text part', () => {
+ const provider = new TestFirstUserContentProvider();
+ const message = {
+ content: [
+ { text: 'Original text', type: 'text' },
+ { image_url: { url: 'http://example.com/image.png' }, type: 'image_url' },
+ ],
+ role: 'user',
+ };
+
+ const result = provider.testAppendToMessage(message, 'Appended content');
+
+ expect(result.content[0].text).toBe('Original text\n\nAppended content');
+ expect(result.content[1].type).toBe('image_url');
+ });
+
+ it('should add new text part when array content has no text part', () => {
+ const provider = new TestFirstUserContentProvider();
+ const message = {
+ content: [{ image_url: { url: 'http://example.com/image.png' }, type: 'image_url' }],
+ role: 'user',
+ };
+
+ const result = provider.testAppendToMessage(message, 'Appended content');
+
+ expect(result.content).toHaveLength(2);
+ expect(result.content[1]).toEqual({
+ text: 'Appended content',
+ type: 'text',
+ });
+ });
+
+ it('should append to last text part in multimodal message', () => {
+ const provider = new TestFirstUserContentProvider();
+ const message = {
+ content: [
+ { text: 'First text', type: 'text' },
+ { image_url: { url: 'http://example.com/image.png' }, type: 'image_url' },
+ { text: 'Last text', type: 'text' },
+ ],
+ role: 'user',
+ };
+
+ const result = provider.testAppendToMessage(message, 'Appended content');
+
+ expect(result.content[2].text).toBe('Last text\n\nAppended content');
+ expect(result.content[0].text).toBe('First text');
+ });
+ });
+
+ describe('process integration', () => {
+ it('should insert new message before first user message when no injection exists', async () => {
+ const provider = new TestFirstUserContentProvider();
+ const context = createContext([
+ { content: 'System prompt', role: 'system' },
+ { content: 'User question', role: 'user' },
+ { content: 'Assistant response', role: 'assistant' },
+ ]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages).toHaveLength(4);
+ expect(result.messages[0].content).toBe('System prompt');
+ expect(result.messages[1].content).toBe('Test content');
+ expect(result.messages[1].meta?.systemInjection).toBe(true);
+ expect(result.messages[2].content).toBe('User question');
+ });
+
+ it('should append to existing injection message when it exists', async () => {
+ const provider = new TestFirstUserContentProvider();
+ const context = createContext([
+ { content: 'System prompt', role: 'system' },
+ { content: 'First injection', meta: { systemInjection: true }, role: 'user' },
+ { content: 'User question', role: 'user' },
+ ]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages).toHaveLength(3);
+ expect(result.messages[1].content).toBe('First injection\n\nTest content');
+ expect(result.messages[1].meta?.systemInjection).toBe(true);
+ });
+
+ it('should skip injection when buildContent returns null', async () => {
+ const provider = new TestFirstUserContentProvider();
+ provider.setContent(null);
+
+ const context = createContext([
+ { content: 'System prompt', role: 'system' },
+ { content: 'User question', role: 'user' },
+ ]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages).toHaveLength(2);
+ expect(result.messages[0].content).toBe('System prompt');
+ expect(result.messages[1].content).toBe('User question');
+ });
+
+ it('should skip injection when no user messages exist', async () => {
+ const provider = new TestFirstUserContentProvider();
+ const context = createContext([
+ { content: 'System prompt', role: 'system' },
+ { content: 'Assistant response', role: 'assistant' },
+ ]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages).toHaveLength(2);
+ });
+
+ it('should insert before first user message even when there is no system message', async () => {
+ const provider = new TestFirstUserContentProvider();
+ const context = createContext([
+ { content: 'User question', role: 'user' },
+ { content: 'Assistant response', role: 'assistant' },
+ ]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages).toHaveLength(3);
+ expect(result.messages[0].content).toBe('Test content');
+ expect(result.messages[0].meta?.systemInjection).toBe(true);
+ expect(result.messages[1].content).toBe('User question');
+ });
+ });
+
+ describe('multiple providers injection', () => {
+ it('should consolidate content from multiple providers into single message', async () => {
+ const provider1 = new TestFirstUserContentProvider();
+ const provider2 = new SecondFirstUserContentProvider();
+
+ const context = createContext([
+ { content: 'System prompt', role: 'system' },
+ { content: 'User question', role: 'user' },
+ ]);
+
+ // First provider creates injection message
+ const result1 = await provider1.process(context);
+ // Second provider appends to existing injection message
+ const result2 = await provider2.process(result1);
+
+ expect(result2.messages).toHaveLength(3);
+ expect(result2.messages[1].content).toBe('Test content\n\nSecond content');
+ expect(result2.messages[1].meta?.systemInjection).toBe(true);
+ expect(result2.messages[2].content).toBe('User question');
+ });
+
+ it('should maintain correct order with multiple providers', async () => {
+ const provider1 = new TestFirstUserContentProvider();
+ provider1.setContent('<user_memories>Memory content</user_memories>');
+
+ const provider2 = new SecondFirstUserContentProvider();
+
+ const context = createContext([
+ { content: 'System prompt', role: 'system' },
+ { content: 'User question', role: 'user' },
+ ]);
+
+ const result1 = await provider1.process(context);
+ const result2 = await provider2.process(result1);
+
+ const injectedContent = result2.messages[1].content as string;
+ expect(injectedContent).toContain('<user_memories>Memory content</user_memories>');
+ expect(injectedContent).toContain('Second content');
+ // First provider's content should come before second provider's content
+ expect(injectedContent.indexOf('user_memories')).toBeLessThan(
+ injectedContent.indexOf('Second content'),
+ );
+ });
+
+ it('should work with array content in injection message', async () => {
+ const provider = new TestFirstUserContentProvider();
+ const context = createContext([
+ { content: 'System prompt', role: 'system' },
+ {
+ content: [{ text: 'Existing injection', type: 'text' }],
+ meta: { systemInjection: true },
+ role: 'user',
+ },
+ { content: 'User question', role: 'user' },
+ ]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages).toHaveLength(3);
+ expect(result.messages[1].content[0].text).toBe('Existing injection\n\nTest content');
+ });
+ });
+
+ describe('edge cases', () => {
+ it('should handle empty content gracefully', async () => {
+ const provider = new TestFirstUserContentProvider();
+ provider.setContent('');
+
+ const context = createContext([{ content: 'User question', role: 'user' }]);
+
+ const result = await provider.process(context);
+
+ // Empty string is falsy, so it should skip injection
+ expect(result.messages).toHaveLength(1);
+ });
+
+ it('should handle complex message structure', async () => {
+ const provider = new TestFirstUserContentProvider();
+ const context = createContext([
+ { content: 'System prompt', role: 'system' },
+ { content: 'First user message', role: 'user' },
+ { content: 'Assistant response', role: 'assistant' },
+ { content: 'Second user message', role: 'user' },
+ { content: 'Another assistant response', role: 'assistant' },
+ ]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages).toHaveLength(6);
+ // Injection should be at index 1, before the first user message
+ expect(result.messages[1].content).toBe('Test content');
+ expect(result.messages[1].meta?.systemInjection).toBe(true);
+ expect(result.messages[2].content).toBe('First user message');
+ });
+ });
+});
diff --git a/packages/context-engine/src/engine/messages/MessagesEngine.ts b/packages/context-engine/src/engine/messages/MessagesEngine.ts
index 8a5bd96adf6..bf99c35d44c 100644
--- a/packages/context-engine/src/engine/messages/MessagesEngine.ts
+++ b/packages/context-engine/src/engine/messages/MessagesEngine.ts
@@ -159,25 +159,38 @@ export class MessagesEngine {
systemPrompt: agentGroup?.systemPrompt,
}),
- // 4. Knowledge injection (full content for agent files + metadata for knowledge bases)
+ // =============================================
+ // Phase 2.5: First User Message Context Injection
+ // These providers inject content before the first user message
+ // Order matters: first executed = first in content
+ // =============================================
+
+ // 4. User memory injection (conditionally added, injected first)
+ ...(isUserMemoryEnabled ? [new UserMemoryInjector(userMemory)] : []),
+
+ // 5. Knowledge injection (full content for agent files + metadata for knowledge bases)
new KnowledgeInjector({
fileContents: knowledge?.fileContents,
knowledgeBases: knowledge?.knowledgeBases,
}),
- // 5. Agent Builder context injection (current agent config/meta for editing)
+ // =============================================
+ // Phase 2.6: Additional System Context
+ // =============================================
+
+ // 6. Agent Builder context injection (current agent config/meta for editing)
new AgentBuilderContextInjector({
enabled: isAgentBuilderEnabled,
agentContext: agentBuilderContext,
}),
- // 6. Group Agent Builder context injection (current group config/members for editing)
+ // 7. Group Agent Builder context injection (current group config/members for editing)
new GroupAgentBuilderContextInjector({
enabled: isGroupAgentBuilderEnabled,
groupContext: groupAgentBuilderContext,
}),
- // 7. Tool system role injection (conditionally added)
+ // 8. Tool system role injection (conditionally added)
...(toolsConfig?.tools && toolsConfig.tools.length > 0
? [
new ToolSystemRoleProvider({
@@ -190,22 +203,12 @@ export class MessagesEngine {
]
: []),
- // 8. History summary injection
+ // 9. History summary injection
new HistorySummaryProvider({
formatHistorySummary,
historySummary,
}),
- // 9. User memory injection (conditionally added)
- ...(isUserMemoryEnabled
- ? [
- new UserMemoryInjector({
- fetchedAt: userMemory.fetchedAt,
- memories: userMemory.memories,
- }),
- ]
- : []),
-
// =============================================
// Phase 3: Message Transformation
// =============================================
diff --git a/packages/context-engine/src/engine/messages/index.ts b/packages/context-engine/src/engine/messages/index.ts
index ae64e48a5e9..6e5c7c37ccf 100644
--- a/packages/context-engine/src/engine/messages/index.ts
+++ b/packages/context-engine/src/engine/messages/index.ts
@@ -17,6 +17,7 @@ export type {
UserMemoryContextItem,
UserMemoryData,
UserMemoryExperienceItem,
+ UserMemoryIdentityItem,
UserMemoryPreferenceItem,
VariableGenerators,
} from './types';
diff --git a/packages/context-engine/src/engine/messages/types.ts b/packages/context-engine/src/engine/messages/types.ts
index d12863d474d..3f3fe459d08 100644
--- a/packages/context-engine/src/engine/messages/types.ts
+++ b/packages/context-engine/src/engine/messages/types.ts
@@ -82,6 +82,15 @@ export interface UserMemoryPreferenceItem {
[key: string]: unknown;
}
+export interface UserMemoryIdentityItem {
+ description?: string | null;
+ id?: string;
+ role?: string | null;
+ /** Identity type: personal (角色), professional (职业), demographic (属性) */
+ type?: 'demographic' | 'personal' | 'professional' | string | null;
+ [key: string]: unknown;
+}
+
/**
* User memory data structure
* Compatible with SearchMemoryResult from @lobechat/types
@@ -89,6 +98,7 @@ export interface UserMemoryPreferenceItem {
export interface UserMemoryData {
contexts: UserMemoryContextItem[];
experiences: UserMemoryExperienceItem[];
+ identities?: UserMemoryIdentityItem[];
preferences: UserMemoryPreferenceItem[];
}
diff --git a/packages/context-engine/src/index.ts b/packages/context-engine/src/index.ts
index a593095ff72..035b9cfd3dc 100644
--- a/packages/context-engine/src/index.ts
+++ b/packages/context-engine/src/index.ts
@@ -2,6 +2,7 @@
export * from './types';
// Base classes
+export { BaseFirstUserContentProvider } from './base/BaseFirstUserContentProvider';
export { BaseLastUserContentProvider } from './base/BaseLastUserContentProvider';
export { BaseProcessor } from './base/BaseProcessor';
export { BaseProvider } from './base/BaseProvider';
diff --git a/packages/context-engine/src/processors/PlaceholderVariables.ts b/packages/context-engine/src/processors/PlaceholderVariables.ts
index b372dcb3036..08a89e8730a 100644
--- a/packages/context-engine/src/processors/PlaceholderVariables.ts
+++ b/packages/context-engine/src/processors/PlaceholderVariables.ts
@@ -86,12 +86,29 @@ export const parsePlaceholderVariables = (
for (let i = 0; i < depth; i++) {
try {
const extractedVariables = extractPlaceholderVariables(result);
+
+ log('Extracted variables from text: %o', extractedVariables);
+ log('Available generator keys: %o', Object.keys(variableGenerators));
+
+ // Debug: check if text contains {{username}} pattern
+ if (result.includes('username') || result.includes('{{')) {
+ const matches = result.match(/{{[^}]*}}/g);
+ log('All {{...}} patterns found in text: %o', matches);
+ }
+
const availableVariables = Object.fromEntries(
extractedVariables
- .map((key) => [key, variableGenerators[key]?.()])
+ .map((key) => {
+ const generator = variableGenerators[key];
+ const value = generator?.();
+ log('Variable "%s": generator=%s, value=%s', key, !!generator, value);
+ return [key, value];
+ })
.filter(([, value]) => value !== undefined),
);
+ log('Available variables after filtering: %o', availableVariables);
+
// Only perform replacement when there are available variables
if (Object.keys(availableVariables).length === 0) break;
@@ -188,11 +205,22 @@ export class PlaceholderVariablesProcessor extends BaseProcessor {
log(
`Starting placeholder variables processing with ${Object.keys(this.config.variableGenerators).length} generators`,
);
+ log('Generator keys: %o', Object.keys(this.config.variableGenerators));
// Process placeholder variables for each message
for (let i = 0; i < clonedContext.messages.length; i++) {
const message = clonedContext.messages[i];
+ log(
+ 'Processing message %d: role=%s, contentType=%s, contentPreview=%s',
+ i,
+ message.role,
+ typeof message.content,
+ typeof message.content === 'string'
+ ? message.content.slice(0, 200)
+ : JSON.stringify(message.content).slice(0, 200),
+ );
+
try {
const originalMessage = JSON.stringify(message);
const processedMessage = this.processMessagePlaceholders(message, depth);
@@ -201,6 +229,8 @@ export class PlaceholderVariablesProcessor extends BaseProcessor {
clonedContext.messages[i] = processedMessage;
processedCount++;
log(`Processed placeholders in message ${message.id}, role: ${message.role}`);
+ } else {
+ log(`No placeholders found/replaced in message ${message.id}, role: ${message.role}`);
}
} catch (error) {
log.extend('error')(`Error processing placeholders in message ${message.id}: ${error}`);
diff --git a/packages/context-engine/src/providers/GroupAgentBuilderContextInjector.ts b/packages/context-engine/src/providers/GroupAgentBuilderContextInjector.ts
index 3c1ed7ef9ad..6e3dd425173 100644
--- a/packages/context-engine/src/providers/GroupAgentBuilderContextInjector.ts
+++ b/packages/context-engine/src/providers/GroupAgentBuilderContextInjector.ts
@@ -163,7 +163,7 @@ const defaultFormatGroupContext = (context: GroupAgentBuilderContext): string =>
}
if (context.supervisorConfig.plugins && context.supervisorConfig.plugins.length > 0) {
supervisorFields.push(
- ` <enabled_plugins>${context.supervisorConfig.plugins.join(', ')}</enabled_plugins>`,
+ ` <enabled_skills>${context.supervisorConfig.plugins.join(', ')}</enabled_skills>`,
);
}
diff --git a/packages/context-engine/src/providers/KnowledgeInjector.ts b/packages/context-engine/src/providers/KnowledgeInjector.ts
index 9517439ba41..7255ab5a9ac 100644
--- a/packages/context-engine/src/providers/KnowledgeInjector.ts
+++ b/packages/context-engine/src/providers/KnowledgeInjector.ts
@@ -2,7 +2,7 @@ import { promptAgentKnowledge } from '@lobechat/prompts';
import type { FileContent, KnowledgeBaseInfo } from '@lobechat/prompts';
import debug from 'debug';
-import { BaseProvider } from '../base/BaseProvider';
+import { BaseFirstUserContentProvider } from '../base/BaseFirstUserContentProvider';
import type { PipelineContext, ProcessorOptions } from '../types';
const log = debug('context-engine:provider:KnowledgeInjector');
@@ -17,8 +17,9 @@ export interface KnowledgeInjectorConfig {
/**
* Knowledge Injector
* Responsible for injecting agent's knowledge (files and knowledge bases) into context
+ * before the first user message
*/
-export class KnowledgeInjector extends BaseProvider {
+export class KnowledgeInjector extends BaseFirstUserContentProvider {
readonly name = 'KnowledgeInjector';
constructor(
@@ -28,51 +29,39 @@ export class KnowledgeInjector extends BaseProvider {
super(options);
}
- protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
- const clonedContext = this.cloneContext(context);
-
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ protected buildContent(_context: PipelineContext): string | null {
const fileContents = this.config.fileContents || [];
const knowledgeBases = this.config.knowledgeBases || [];
// Generate unified knowledge prompt
const formattedContent = promptAgentKnowledge({ fileContents, knowledgeBases });
- // Skip injection if no knowledge at all
if (!formattedContent) {
log('No knowledge to inject');
- return this.markAsExecuted(clonedContext);
+ return null;
}
- // Find the first user message index
- const firstUserIndex = clonedContext.messages.findIndex((msg) => msg.role === 'user');
-
- if (firstUserIndex === -1) {
- log('No user messages found, skipping injection');
- return this.markAsExecuted(clonedContext);
- }
+ log(
+ `Knowledge prepared: ${fileContents.length} file(s), ${knowledgeBases.length} knowledge base(s)`,
+ );
- // Insert a new user message with knowledge before the first user message
- // Mark it as application-level system injection
- const knowledgeMessage = {
- content: formattedContent,
- createdAt: Date.now(),
- id: `knowledge-${Date.now()}`,
- meta: { injectType: 'knowledge', systemInjection: true },
- role: 'user' as const,
- updatedAt: Date.now(),
- };
+ return formattedContent;
+ }
- clonedContext.messages.splice(firstUserIndex, 0, knowledgeMessage);
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ const result = await super.doProcess(context);
// Update metadata
- clonedContext.metadata.knowledgeInjected = true;
- clonedContext.metadata.filesCount = fileContents.length;
- clonedContext.metadata.knowledgeBasesCount = knowledgeBases.length;
+ const fileContents = this.config.fileContents || [];
+ const knowledgeBases = this.config.knowledgeBases || [];
- log(
- `Agent knowledge injected as new user message: ${fileContents.length} file(s), ${knowledgeBases.length} knowledge base(s)`,
- );
+ if (fileContents.length > 0 || knowledgeBases.length > 0) {
+ result.metadata.knowledgeInjected = true;
+ result.metadata.filesCount = fileContents.length;
+ result.metadata.knowledgeBasesCount = knowledgeBases.length;
+ }
- return this.markAsExecuted(clonedContext);
+ return result;
}
}
diff --git a/packages/context-engine/src/providers/UserMemoryInjector.ts b/packages/context-engine/src/providers/UserMemoryInjector.ts
index 6fc534f8422..ce350b77128 100644
--- a/packages/context-engine/src/providers/UserMemoryInjector.ts
+++ b/packages/context-engine/src/providers/UserMemoryInjector.ts
@@ -1,20 +1,22 @@
-import { u } from 'unist-builder';
-import { toXml } from 'xast-util-to-xml';
-import type { Child } from 'xastscript';
-import { x } from 'xastscript';
+import { promptUserMemory } from '@lobechat/prompts';
+import type { UserMemoryData } from '@lobechat/prompts';
+import debug from 'debug';
-import { BaseProvider } from '../base/BaseProvider';
-import type { UserMemoryData } from '../engine/messages/types';
+import { BaseFirstUserContentProvider } from '../base/BaseFirstUserContentProvider';
import type { PipelineContext, ProcessorOptions } from '../types';
+const log = debug('context-engine:provider:UserMemoryInjector');
+
export interface UserMemoryInjectorConfig {
- /** When the memories were fetched */
- fetchedAt?: number;
/** User memories data */
memories?: UserMemoryData;
}
-export class UserMemoryInjector extends BaseProvider {
+/**
+ * User Memory Injector
+ * Responsible for injecting user memories into context before the first user message
+ */
+export class UserMemoryInjector extends BaseFirstUserContentProvider {
readonly name = 'UserMemoryInjector';
constructor(
@@ -24,72 +26,38 @@ export class UserMemoryInjector extends BaseProvider {
super(options);
}
- protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ protected buildContent(_context: PipelineContext): string | null {
const { memories } = this.config;
- if (!memories) return context;
+ if (!memories) return null;
+
+ const content = promptUserMemory({ memories });
+ if (!content) {
+ log('No user memories to inject');
+ return null;
+ }
+
+ const identitiesCount = memories.identities?.length || 0;
const contextsCount = memories.contexts?.length || 0;
const experiencesCount = memories.experiences?.length || 0;
const preferencesCount = memories.preferences?.length || 0;
- if (contextsCount + experiencesCount + preferencesCount === 0) return context;
- const userMemoriesChildren: Child[] = [];
- if (memories.contexts) {
- memories.contexts.forEach((ctx) => {
- userMemoriesChildren.push(
- x('user_memories_context', { id: ctx.id || '' }, [
- x('context_title', ctx.title || ''),
- x('context_description', ctx.description || ''),
- ]),
- );
- });
- }
- if (memories.experiences) {
- memories.experiences.forEach((experience) => {
- userMemoriesChildren.push(
- x('user_memories_experience', { id: experience.id || '' }, [
- x('experience_situation', experience.situation || ''),
- x('experience_key_learning', experience.keyLearning || ''),
- ]),
- );
- });
- }
- if (memories.preferences) {
- memories.preferences.forEach((preference) => {
- userMemoriesChildren.push(
- x('user_memories_preference', { id: preference.id || '' }, [
- x('preference_conclusion_directives', preference.conclusionDirectives || ''),
- ]),
- );
- });
- }
+ log(
+ `User memories prepared: ${identitiesCount} identity(ies), ${contextsCount} context(s), ${experiencesCount} experience(s), ${preferencesCount} preference(s)`,
+ );
+
+ return content;
+ }
- const memoryMessage = {
- content: toXml(
- u('root', [
- x(
- 'user_memories',
- {
- contexts: contextsCount.toString(),
- experiences: experiencesCount.toString(),
- memory_fetched_at: new Date(this.config.fetchedAt || Date.now()).toISOString(),
- preferences: preferencesCount.toString(),
- },
- ...userMemoriesChildren,
- ),
- ]),
- ),
- createdAt: Date.now(),
- id: `user-memory-${Date.now()}`,
- meta: { source: 'userMemory' },
- role: 'system' as const,
- updatedAt: Date.now(),
- };
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ const result = await super.doProcess(context);
- const clonedContext = this.cloneContext(context);
- clonedContext.messages.unshift(memoryMessage);
- clonedContext.metadata.userMemoryInjected = true;
+ // Update metadata
+ if (this.config.memories) {
+ result.metadata.userMemoryInjected = true;
+ }
- return this.markAsExecuted(clonedContext);
+ return result;
}
}
diff --git a/packages/context-engine/src/providers/__tests__/KnowledgeInjector.test.ts b/packages/context-engine/src/providers/__tests__/KnowledgeInjector.test.ts
new file mode 100644
index 00000000000..f4232cc5a0e
--- /dev/null
+++ b/packages/context-engine/src/providers/__tests__/KnowledgeInjector.test.ts
@@ -0,0 +1,251 @@
+import { describe, expect, it } from 'vitest';
+
+import type { PipelineContext } from '../../types';
+import { KnowledgeInjector } from '../KnowledgeInjector';
+
+describe('KnowledgeInjector', () => {
+ const createContext = (messages: any[] = []): PipelineContext => ({
+ initialState: {
+ messages: [],
+ model: 'gpt-4',
+ provider: 'openai',
+ },
+ isAborted: false,
+ messages,
+ metadata: {
+ maxTokens: 4096,
+ model: 'gpt-4',
+ },
+ });
+
+ describe('basic injection', () => {
+ it('should inject knowledge before the first user message', async () => {
+ const provider = new KnowledgeInjector({
+ fileContents: [{ content: 'File content here', fileId: 'file-1', filename: 'test.md' }],
+ knowledgeBases: [],
+ });
+
+ const context = createContext([
+ { content: 'System prompt', id: 'sys-1', role: 'system' },
+ { content: 'Hello', id: 'user-1', role: 'user' },
+ ]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages).toHaveLength(3);
+ expect(result.messages[0].role).toBe('system');
+ expect(result.messages[1].role).toBe('user');
+ expect(result.messages[1].meta?.systemInjection).toBe(true);
+ expect(result.messages[1].content).toMatchSnapshot();
+ expect(result.messages[2].content).toBe('Hello');
+ expect(result.metadata.knowledgeInjected).toBe(true);
+ });
+
+ it('should skip injection when no files or knowledge bases', async () => {
+ const provider = new KnowledgeInjector({
+ fileContents: [],
+ knowledgeBases: [],
+ });
+
+ const context = createContext([{ content: 'Hello', id: 'user-1', role: 'user' }]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages).toHaveLength(1);
+ expect(result.messages[0].content).toBe('Hello');
+ expect(result.metadata.knowledgeInjected).toBeUndefined();
+ });
+
+ it('should skip injection when config is empty', async () => {
+ const provider = new KnowledgeInjector({});
+
+ const context = createContext([{ content: 'Hello', id: 'user-1', role: 'user' }]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages).toHaveLength(1);
+ expect(result.messages[0].content).toBe('Hello');
+ });
+
+ it('should skip injection when no user messages exist', async () => {
+ const provider = new KnowledgeInjector({
+ fileContents: [{ content: 'Content', fileId: 'file-1', filename: 'file.md' }],
+ });
+
+ const context = createContext([{ content: 'System prompt', id: 'sys-1', role: 'system' }]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages).toHaveLength(1);
+ expect(result.messages[0].role).toBe('system');
+ });
+ });
+
+ describe('file contents', () => {
+ it('should inject multiple file contents', async () => {
+ const provider = new KnowledgeInjector({
+ fileContents: [
+ { content: 'Content of file 1', fileId: 'file-1', filename: 'file1.md' },
+ { content: 'Content of file 2', fileId: 'file-2', filename: 'file2.ts' },
+ ],
+ });
+
+ const context = createContext([{ content: 'Hello', id: 'user-1', role: 'user' }]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages[0].content).toMatchSnapshot();
+ expect(result.metadata.filesCount).toBe(2);
+ });
+ });
+
+ describe('knowledge bases', () => {
+ it('should inject knowledge bases', async () => {
+ const provider = new KnowledgeInjector({
+ knowledgeBases: [
+ { description: 'Description 1', id: 'kb-1', name: 'KB 1' },
+ { description: 'Description 2', id: 'kb-2', name: 'KB 2' },
+ ],
+ });
+
+ const context = createContext([{ content: 'Hello', id: 'user-1', role: 'user' }]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages[0].content).toMatchSnapshot();
+ expect(result.metadata.knowledgeBasesCount).toBe(2);
+ });
+ });
+
+ describe('mixed content', () => {
+ it('should inject both files and knowledge bases', async () => {
+ const provider = new KnowledgeInjector({
+ fileContents: [{ content: 'File content', fileId: 'file-1', filename: 'readme.md' }],
+ knowledgeBases: [{ description: 'API docs', id: 'kb-1', name: 'API Reference' }],
+ });
+
+ const context = createContext([{ content: 'Hello', id: 'user-1', role: 'user' }]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages[0].content).toMatchSnapshot();
+ expect(result.metadata.filesCount).toBe(1);
+ expect(result.metadata.knowledgeBasesCount).toBe(1);
+ });
+ });
+
+ describe('integration with BaseFirstUserContentProvider', () => {
+ it('should append to existing system injection message', async () => {
+ const provider = new KnowledgeInjector({
+ fileContents: [{ content: 'File content', fileId: 'file-1', filename: 'test.md' }],
+ });
+
+ const context = createContext([
+ { content: 'System prompt', id: 'sys-1', role: 'system' },
+ {
+ content: 'Existing injection content',
+ id: 'inject-1',
+ meta: { systemInjection: true },
+ role: 'user',
+ },
+ { content: 'Hello', id: 'user-1', role: 'user' },
+ ]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages).toHaveLength(3);
+ expect(result.messages[1].content).toMatchSnapshot();
+ });
+
+ it('should work when user message is first', async () => {
+ const provider = new KnowledgeInjector({
+ fileContents: [{ content: 'Content', fileId: 'file-1', filename: 'file.md' }],
+ });
+
+ const context = createContext([
+ { content: 'Hello', id: 'user-1', role: 'user' },
+ { content: 'Response', id: 'asst-1', role: 'assistant' },
+ ]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages).toHaveLength(3);
+ expect(result.messages[0].meta?.systemInjection).toBe(true);
+ expect(result.messages[0].content).toMatchSnapshot();
+ expect(result.messages[1].content).toBe('Hello');
+ });
+ });
+
+ describe('metadata', () => {
+ it('should set correct metadata counts', async () => {
+ const provider = new KnowledgeInjector({
+ fileContents: [
+ { content: 'Content 1', fileId: 'file-1', filename: 'file1.md' },
+ { content: 'Content 2', fileId: 'file-2', filename: 'file2.md' },
+ { content: 'Content 3', fileId: 'file-3', filename: 'file3.md' },
+ ],
+ knowledgeBases: [
+ { description: 'KB 1', id: 'kb-1', name: 'KB1' },
+ { description: 'KB 2', id: 'kb-2', name: 'KB2' },
+ ],
+ });
+
+ const context = createContext([{ content: 'Hello', id: 'user-1', role: 'user' }]);
+
+ const result = await provider.process(context);
+
+ expect(result.metadata.knowledgeInjected).toBe(true);
+ expect(result.metadata.filesCount).toBe(3);
+ expect(result.metadata.knowledgeBasesCount).toBe(2);
+ });
+
+ it('should not set metadata when no content is injected', async () => {
+ const provider = new KnowledgeInjector({
+ fileContents: [],
+ knowledgeBases: [],
+ });
+
+ const context = createContext([{ content: 'Hello', id: 'user-1', role: 'user' }]);
+
+ const result = await provider.process(context);
+
+ expect(result.metadata.knowledgeInjected).toBeUndefined();
+ expect(result.metadata.filesCount).toBeUndefined();
+ expect(result.metadata.knowledgeBasesCount).toBeUndefined();
+ });
+ });
+
+ describe('edge cases', () => {
+ it('should handle empty message array', async () => {
+ const provider = new KnowledgeInjector({
+ fileContents: [{ content: 'Content', fileId: 'file-1', filename: 'file.md' }],
+ });
+
+ const context = createContext([]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages).toHaveLength(0);
+ });
+
+ it('should handle conversation with multiple user messages', async () => {
+ const provider = new KnowledgeInjector({
+ fileContents: [{ content: 'Content', fileId: 'file-1', filename: 'file.md' }],
+ });
+
+ const context = createContext([
+ { content: 'First question', id: 'user-1', role: 'user' },
+ { content: 'First response', id: 'asst-1', role: 'assistant' },
+ { content: 'Second question', id: 'user-2', role: 'user' },
+ { content: 'Second response', id: 'asst-2', role: 'assistant' },
+ ]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages).toHaveLength(5);
+ // Injection should be before the first user message
+ expect(result.messages[0].meta?.systemInjection).toBe(true);
+ expect(result.messages[1].content).toBe('First question');
+ });
+ });
+});
diff --git a/packages/context-engine/src/providers/__tests__/UserMemoryInjector.test.ts b/packages/context-engine/src/providers/__tests__/UserMemoryInjector.test.ts
new file mode 100644
index 00000000000..dc2d4f1fc76
--- /dev/null
+++ b/packages/context-engine/src/providers/__tests__/UserMemoryInjector.test.ts
@@ -0,0 +1,277 @@
+import { describe, expect, it } from 'vitest';
+
+import type { PipelineContext } from '../../types';
+import { UserMemoryInjector } from '../UserMemoryInjector';
+
+describe('UserMemoryInjector', () => {
+ const createContext = (messages: any[] = []): PipelineContext => ({
+ initialState: {
+ messages: [],
+ model: 'gpt-4',
+ provider: 'openai',
+ },
+ isAborted: false,
+ messages,
+ metadata: {
+ maxTokens: 4096,
+ model: 'gpt-4',
+ },
+ });
+
+ describe('basic injection', () => {
+ it('should inject user memories before the first user message', async () => {
+ const provider = new UserMemoryInjector({
+ memories: {
+ contexts: [
+ { description: 'Test context description', id: 'ctx-1', title: 'Test Context' },
+ ],
+ experiences: [],
+ preferences: [],
+ },
+ });
+
+ const context = createContext([
+ { content: 'System prompt', id: 'sys-1', role: 'system' },
+ { content: 'Hello', id: 'user-1', role: 'user' },
+ ]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages).toHaveLength(3);
+ expect(result.messages[0].role).toBe('system');
+ expect(result.messages[1].role).toBe('user');
+ expect(result.messages[1].meta?.systemInjection).toBe(true);
+ expect(result.messages[1].content).toMatchSnapshot();
+ expect(result.messages[2].content).toBe('Hello');
+ expect(result.metadata.userMemoryInjected).toBe(true);
+ });
+
+ it('should skip injection when memories is undefined', async () => {
+ const provider = new UserMemoryInjector({});
+
+ const context = createContext([{ content: 'Hello', id: 'user-1', role: 'user' }]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages).toHaveLength(1);
+ expect(result.messages[0].content).toBe('Hello');
+ });
+
+ it('should skip injection when all memory arrays are empty', async () => {
+ const provider = new UserMemoryInjector({
+ memories: {
+ contexts: [],
+ experiences: [],
+ preferences: [],
+ },
+ });
+
+ const context = createContext([{ content: 'Hello', id: 'user-1', role: 'user' }]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages).toHaveLength(1);
+ expect(result.messages[0].content).toBe('Hello');
+ });
+
+ it('should skip injection when no user messages exist', async () => {
+ const provider = new UserMemoryInjector({
+ memories: {
+ contexts: [{ description: 'Test', id: 'ctx-1', title: 'Test' }],
+ experiences: [],
+ preferences: [],
+ },
+ });
+
+ const context = createContext([{ content: 'System prompt', id: 'sys-1', role: 'system' }]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages).toHaveLength(1);
+ expect(result.messages[0].role).toBe('system');
+ });
+ });
+
+ describe('memory types', () => {
+ it('should inject contexts correctly', async () => {
+ const provider = new UserMemoryInjector({
+ memories: {
+ contexts: [
+ { description: 'Context 1 description', id: 'ctx-1', title: 'Context 1' },
+ { description: 'Context 2 description', id: 'ctx-2', title: 'Context 2' },
+ ],
+ experiences: [],
+ preferences: [],
+ },
+ });
+
+ const context = createContext([{ content: 'Hello', id: 'user-1', role: 'user' }]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages[0].content).toMatchSnapshot();
+ });
+
+ it('should inject experiences correctly', async () => {
+ const provider = new UserMemoryInjector({
+ memories: {
+ contexts: [],
+ experiences: [
+ { id: 'exp-1', keyLearning: 'Learning 1', situation: 'Situation 1' },
+ { id: 'exp-2', keyLearning: 'Learning 2', situation: 'Situation 2' },
+ ],
+ preferences: [],
+ },
+ });
+
+ const context = createContext([{ content: 'Hello', id: 'user-1', role: 'user' }]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages[0].content).toMatchSnapshot();
+ });
+
+ it('should inject preferences correctly', async () => {
+ const provider = new UserMemoryInjector({
+ memories: {
+ contexts: [],
+ experiences: [],
+ preferences: [
+ { conclusionDirectives: 'Prefer TypeScript', id: 'pref-1' },
+ { conclusionDirectives: 'Use dark mode', id: 'pref-2' },
+ ],
+ },
+ });
+
+ const context = createContext([{ content: 'Hello', id: 'user-1', role: 'user' }]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages[0].content).toMatchSnapshot();
+ });
+
+ it('should inject all memory types together', async () => {
+ const provider = new UserMemoryInjector({
+ memories: {
+ contexts: [{ description: 'Context desc', id: 'ctx-1', title: 'Context' }],
+ experiences: [{ id: 'exp-1', keyLearning: 'Learning', situation: 'Situation' }],
+ preferences: [{ conclusionDirectives: 'Preference', id: 'pref-1' }],
+ },
+ });
+
+ const context = createContext([{ content: 'Hello', id: 'user-1', role: 'user' }]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages[0].content).toMatchSnapshot();
+ });
+ });
+
+ describe('XML format', () => {
+ it('should handle null or undefined values gracefully', async () => {
+ const provider = new UserMemoryInjector({
+ memories: {
+ contexts: [{ description: null, id: undefined, title: null }],
+ experiences: [{ id: undefined, keyLearning: null, situation: null }],
+ preferences: [{ conclusionDirectives: null, id: undefined }],
+ },
+ });
+
+ const context = createContext([{ content: 'Hello', id: 'user-1', role: 'user' }]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages[0].content).toMatchSnapshot();
+ });
+ });
+
+ describe('integration with BaseFirstUserContentProvider', () => {
+ it('should append to existing system injection message', async () => {
+ const provider = new UserMemoryInjector({
+ memories: {
+ contexts: [{ description: 'Test', id: 'ctx-1', title: 'Test' }],
+ experiences: [],
+ preferences: [],
+ },
+ });
+
+ const context = createContext([
+ { content: 'System prompt', id: 'sys-1', role: 'system' },
+ {
+ content: 'Existing injection content',
+ id: 'inject-1',
+ meta: { systemInjection: true },
+ role: 'user',
+ },
+ { content: 'Hello', id: 'user-1', role: 'user' },
+ ]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages).toHaveLength(3);
+ expect(result.messages[1].content).toMatchSnapshot();
+ });
+
+ it('should work with multimodal messages', async () => {
+ const provider = new UserMemoryInjector({
+ memories: {
+ contexts: [{ description: 'Test', id: 'ctx-1', title: 'Test' }],
+ experiences: [],
+ preferences: [],
+ },
+ });
+
+ const context = createContext([
+ {
+ content: [
+ { text: 'Hello with image', type: 'text' },
+ { image_url: { url: 'http://example.com/img.png' }, type: 'image_url' },
+ ],
+ id: 'user-1',
+ role: 'user',
+ },
+ ]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages).toHaveLength(2);
+ expect(result.messages[0].meta?.systemInjection).toBe(true);
+ expect(result.messages[0].content).toMatchSnapshot();
+ });
+ });
+
+ describe('metadata', () => {
+ it('should set userMemoryInjected to true when memories exist', async () => {
+ const provider = new UserMemoryInjector({
+ memories: {
+ contexts: [{ description: 'Test', id: 'ctx-1', title: 'Test' }],
+ experiences: [],
+ preferences: [],
+ },
+ });
+
+ const context = createContext([{ content: 'Hello', id: 'user-1', role: 'user' }]);
+
+ const result = await provider.process(context);
+
+ expect(result.metadata.userMemoryInjected).toBe(true);
+ });
+
+ it('should set userMemoryInjected when config has memories even if empty', async () => {
+ const provider = new UserMemoryInjector({
+ memories: {
+ contexts: [],
+ experiences: [],
+ preferences: [],
+ },
+ });
+
+ const context = createContext([{ content: 'Hello', id: 'user-1', role: 'user' }]);
+
+ const result = await provider.process(context);
+
+ // memories exists in config, so metadata is set
+ expect(result.metadata.userMemoryInjected).toBe(true);
+ });
+ });
+});
diff --git a/packages/context-engine/src/providers/__tests__/__snapshots__/KnowledgeInjector.test.ts.snap b/packages/context-engine/src/providers/__tests__/__snapshots__/KnowledgeInjector.test.ts.snap
new file mode 100644
index 00000000000..fe12ed71d7c
--- /dev/null
+++ b/packages/context-engine/src/providers/__tests__/__snapshots__/KnowledgeInjector.test.ts.snap
@@ -0,0 +1,74 @@
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+
+exports[`KnowledgeInjector > basic injection > should inject knowledge before the first user message 1`] = `
+"<agent_knowledge>
+<instruction>The following files are available. Refer to their content directly to answer questions. No knowledge bases are associated.</instruction>
+<files totalCount="1">
+<file id="file-1" name="test.md">
+File content here
+</file>
+</files>
+</agent_knowledge>"
+`;
+
+exports[`KnowledgeInjector > file contents > should inject multiple file contents 1`] = `
+"<agent_knowledge>
+<instruction>The following files are available. Refer to their content directly to answer questions. No knowledge bases are associated.</instruction>
+<files totalCount="2">
+<file id="file-1" name="file1.md">
+Content of file 1
+</file>
+<file id="file-2" name="file2.ts">
+Content of file 2
+</file>
+</files>
+</agent_knowledge>"
+`;
+
+exports[`KnowledgeInjector > integration with BaseFirstUserContentProvider > should append to existing system injection message 1`] = `
+"Existing injection content
+
+<agent_knowledge>
+<instruction>The following files are available. Refer to their content directly to answer questions. No knowledge bases are associated.</instruction>
+<files totalCount="1">
+<file id="file-1" name="test.md">
+File content
+</file>
+</files>
+</agent_knowledge>"
+`;
+
+exports[`KnowledgeInjector > integration with BaseFirstUserContentProvider > should work when user message is first 1`] = `
+"<agent_knowledge>
+<instruction>The following files are available. Refer to their content directly to answer questions. No knowledge bases are associated.</instruction>
+<files totalCount="1">
+<file id="file-1" name="file.md">
+Content
+</file>
+</files>
+</agent_knowledge>"
+`;
+
+exports[`KnowledgeInjector > knowledge bases > should inject knowledge bases 1`] = `
+"<agent_knowledge>
+<instruction>The following knowledge bases are available for semantic search. Use the searchKnowledgeBase tool to find relevant information.</instruction>
+<knowledge_bases totalCount="2">
+<knowledge_base id="kb-1" name="KB 1" description="Description 1" />
+<knowledge_base id="kb-2" name="KB 2" description="Description 2" />
+</knowledge_bases>
+</agent_knowledge>"
+`;
+
+exports[`KnowledgeInjector > mixed content > should inject both files and knowledge bases 1`] = `
+"<agent_knowledge>
+<instruction>The following files and knowledge bases are available. For files, refer to their content directly. For knowledge bases, use the searchKnowledgeBase tool to find relevant information.</instruction>
+<files totalCount="1">
+<file id="file-1" name="readme.md">
+File content
+</file>
+</files>
+<knowledge_bases totalCount="1">
+<knowledge_base id="kb-1" name="API Reference" description="API docs" />
+</knowledge_bases>
+</agent_knowledge>"
+`;
diff --git a/packages/context-engine/src/providers/__tests__/__snapshots__/UserMemoryInjector.test.ts.snap b/packages/context-engine/src/providers/__tests__/__snapshots__/UserMemoryInjector.test.ts.snap
new file mode 100644
index 00000000000..b14f142f1af
--- /dev/null
+++ b/packages/context-engine/src/providers/__tests__/__snapshots__/UserMemoryInjector.test.ts.snap
@@ -0,0 +1,86 @@
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+
+exports[`UserMemoryInjector > XML format > should handle null or undefined values gracefully 1`] = `"Hello"`;
+
+exports[`UserMemoryInjector > basic injection > should inject user memories before the first user message 1`] = `
+"<user_memory>
+<instruction>The following are memories about this user retrieved from previous conversations. Use this information to personalize your responses and maintain continuity.</instruction>
+<contexts count="1">
+ <context id="ctx-1" title="Test Context">Test context description</context>
+</contexts>
+</user_memory>"
+`;
+
+exports[`UserMemoryInjector > integration with BaseFirstUserContentProvider > should append to existing system injection message 1`] = `
+"Existing injection content
+
+<user_memory>
+<instruction>The following are memories about this user retrieved from previous conversations. Use this information to personalize your responses and maintain continuity.</instruction>
+<contexts count="1">
+ <context id="ctx-1" title="Test">Test</context>
+</contexts>
+</user_memory>"
+`;
+
+exports[`UserMemoryInjector > integration with BaseFirstUserContentProvider > should work with multimodal messages 1`] = `
+"<user_memory>
+<instruction>The following are memories about this user retrieved from previous conversations. Use this information to personalize your responses and maintain continuity.</instruction>
+<contexts count="1">
+ <context id="ctx-1" title="Test">Test</context>
+</contexts>
+</user_memory>"
+`;
+
+exports[`UserMemoryInjector > memory types > should inject all memory types together 1`] = `
+"<user_memory>
+<instruction>The following are memories about this user retrieved from previous conversations. Use this information to personalize your responses and maintain continuity.</instruction>
+<contexts count="1">
+ <context id="ctx-1" title="Context">Context desc</context>
+</contexts>
+<experiences count="1">
+ <experience id="exp-1">
+ <situation>Situation</situation>
+ <key_learning>Learning</key_learning>
+ </experience>
+</experiences>
+<preferences count="1">
+ <preference id="pref-1">Preference</preference>
+</preferences>
+</user_memory>"
+`;
+
+exports[`UserMemoryInjector > memory types > should inject contexts correctly 1`] = `
+"<user_memory>
+<instruction>The following are memories about this user retrieved from previous conversations. Use this information to personalize your responses and maintain continuity.</instruction>
+<contexts count="2">
+ <context id="ctx-1" title="Context 1">Context 1 description</context>
+ <context id="ctx-2" title="Context 2">Context 2 description</context>
+</contexts>
+</user_memory>"
+`;
+
+exports[`UserMemoryInjector > memory types > should inject experiences correctly 1`] = `
+"<user_memory>
+<instruction>The following are memories about this user retrieved from previous conversations. Use this information to personalize your responses and maintain continuity.</instruction>
+<experiences count="2">
+ <experience id="exp-1">
+ <situation>Situation 1</situation>
+ <key_learning>Learning 1</key_learning>
+ </experience>
+ <experience id="exp-2">
+ <situation>Situation 2</situation>
+ <key_learning>Learning 2</key_learning>
+ </experience>
+</experiences>
+</user_memory>"
+`;
+
+exports[`UserMemoryInjector > memory types > should inject preferences correctly 1`] = `
+"<user_memory>
+<instruction>The following are memories about this user retrieved from previous conversations. Use this information to personalize your responses and maintain continuity.</instruction>
+<preferences count="2">
+ <preference id="pref-1">Prefer TypeScript</preference>
+ <preference id="pref-2">Use dark mode</preference>
+</preferences>
+</user_memory>"
+`;
diff --git a/packages/database/src/models/__tests__/userMemoryIdentity.test.ts b/packages/database/src/models/__tests__/userMemoryIdentity.test.ts
new file mode 100644
index 00000000000..252bdca2319
--- /dev/null
+++ b/packages/database/src/models/__tests__/userMemoryIdentity.test.ts
@@ -0,0 +1,341 @@
+// @vitest-environment node
+import { RelationshipEnum } from '@lobechat/types';
+import { eq } from 'drizzle-orm';
+import { nanoid } from 'nanoid';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { idGenerator } from '@/database/utils/idGenerator';
+
+import { userMemoriesIdentities, users } from '../../schemas';
+import { LobeChatDatabase } from '../../type';
+import { UserMemoryIdentityModel } from '../userMemory/identity';
+import { getTestDB } from './_util';
+
+// Helper to generate unique identity IDs
+const genIdentityId = () => `mem_${nanoid(12)}`;
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = idGenerator('user');
+const userId2 = idGenerator('user');
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: userId2 }]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(users).where(eq(users.id, userId));
+ await serverDB.delete(users).where(eq(users.id, userId2));
+});
+
+describe('UserMemoryIdentityModel', () => {
+ describe('queryForInjection', () => {
+ it('should return only self identities (relationship === self)', async () => {
+ const model = new UserMemoryIdentityModel(serverDB, userId);
+
+ // Create identities with different relationships
+ const now = new Date();
+ await serverDB.insert(userMemoriesIdentities).values([
+ {
+ id: genIdentityId(),
+ userId,
+ description: 'I am a software engineer',
+ relationship: RelationshipEnum.Self,
+ role: 'Software Engineer',
+ type: 'professional',
+ capturedAt: new Date(now.getTime() - 1000),
+ },
+ {
+ id: genIdentityId(),
+ userId,
+ description: 'My father is a teacher',
+ relationship: RelationshipEnum.Father,
+ role: 'Teacher',
+ type: 'personal',
+ capturedAt: new Date(now.getTime() - 2000),
+ },
+ {
+ id: genIdentityId(),
+ userId,
+ description: 'I live in Shanghai',
+ relationship: RelationshipEnum.Self,
+ role: null,
+ type: 'demographic',
+ capturedAt: new Date(now.getTime() - 3000),
+ },
+ ]);
+
+ const result = await model.queryForInjection();
+
+ // Should only return self identities
+ expect(result).toHaveLength(2);
+ expect(result.every((r) => r.description?.includes('I '))).toBe(true);
+ expect(result.some((r) => r.description?.includes('father'))).toBe(false);
+ });
+
+ it('should return identities with null relationship (treated as self)', async () => {
+ const model = new UserMemoryIdentityModel(serverDB, userId);
+
+ const now = new Date();
+ await serverDB.insert(userMemoriesIdentities).values([
+ {
+ id: genIdentityId(),
+ userId,
+ description: 'Identity with null relationship',
+ relationship: null,
+ role: 'Developer',
+ type: 'professional',
+ capturedAt: new Date(now.getTime() - 1000),
+ },
+ {
+ id: genIdentityId(),
+ userId,
+ description: 'Identity with self relationship',
+ relationship: RelationshipEnum.Self,
+ role: 'Designer',
+ type: 'professional',
+ capturedAt: new Date(now.getTime() - 2000),
+ },
+ ]);
+
+ const result = await model.queryForInjection();
+
+ // Should return both null and self relationships
+ expect(result).toHaveLength(2);
+ });
+
+ it('should exclude non-self relationships (friend, colleague, etc.)', async () => {
+ const model = new UserMemoryIdentityModel(serverDB, userId);
+
+ const now = new Date();
+ await serverDB.insert(userMemoriesIdentities).values([
+ {
+ id: genIdentityId(),
+ userId,
+ description: 'My friend likes coding',
+ relationship: RelationshipEnum.Friend,
+ type: 'personal',
+ capturedAt: new Date(now.getTime() - 1000),
+ },
+ {
+ id: genIdentityId(),
+ userId,
+ description: 'My colleague works on AI',
+ relationship: RelationshipEnum.Colleague,
+ type: 'professional',
+ capturedAt: new Date(now.getTime() - 2000),
+ },
+ {
+ id: genIdentityId(),
+ userId,
+ description: 'My mother is a doctor',
+ relationship: RelationshipEnum.Mother,
+ type: 'personal',
+ capturedAt: new Date(now.getTime() - 3000),
+ },
+ ]);
+
+ const result = await model.queryForInjection();
+
+ // Should return empty since none are self
+ expect(result).toHaveLength(0);
+ });
+
+ it('should respect the limit parameter', async () => {
+ const model = new UserMemoryIdentityModel(serverDB, userId);
+
+ // Create 5 self identities
+ const now = new Date();
+ const identities = Array.from({ length: 5 }, (_, i) => ({
+ id: genIdentityId(),
+ userId,
+ description: `Self identity ${i + 1}`,
+ relationship: RelationshipEnum.Self,
+ type: 'personal',
+ capturedAt: new Date(now.getTime() - i * 1000),
+ }));
+
+ await serverDB.insert(userMemoriesIdentities).values(identities);
+
+ const result = await model.queryForInjection(3);
+
+ expect(result).toHaveLength(3);
+ });
+
+ it('should order by capturedAt descending (most recent first)', async () => {
+ const model = new UserMemoryIdentityModel(serverDB, userId);
+
+ const now = new Date();
+ await serverDB.insert(userMemoriesIdentities).values([
+ {
+ id: genIdentityId(),
+ userId,
+ description: 'Oldest identity',
+ relationship: RelationshipEnum.Self,
+ type: 'personal',
+ capturedAt: new Date(now.getTime() - 3000),
+ },
+ {
+ id: genIdentityId(),
+ userId,
+ description: 'Newest identity',
+ relationship: RelationshipEnum.Self,
+ type: 'personal',
+ capturedAt: new Date(now.getTime() - 1000),
+ },
+ {
+ id: genIdentityId(),
+ userId,
+ description: 'Middle identity',
+ relationship: RelationshipEnum.Self,
+ type: 'personal',
+ capturedAt: new Date(now.getTime() - 2000),
+ },
+ ]);
+
+ const result = await model.queryForInjection();
+
+ expect(result).toHaveLength(3);
+ expect(result[0].description).toBe('Newest identity');
+ expect(result[1].description).toBe('Middle identity');
+ expect(result[2].description).toBe('Oldest identity');
+ });
+
+ it('should only return identities for the current user', async () => {
+ const model1 = new UserMemoryIdentityModel(serverDB, userId);
+ const model2 = new UserMemoryIdentityModel(serverDB, userId2);
+
+ const now = new Date();
+ await serverDB.insert(userMemoriesIdentities).values([
+ {
+ id: genIdentityId(),
+ userId,
+ description: 'User 1 identity',
+ relationship: RelationshipEnum.Self,
+ type: 'personal',
+ capturedAt: new Date(now.getTime() - 1000),
+ },
+ {
+ id: genIdentityId(),
+ userId: userId2,
+ description: 'User 2 identity',
+ relationship: RelationshipEnum.Self,
+ type: 'personal',
+ capturedAt: new Date(now.getTime() - 2000),
+ },
+ ]);
+
+ const result1 = await model1.queryForInjection();
+ const result2 = await model2.queryForInjection();
+
+ expect(result1).toHaveLength(1);
+ expect(result1[0].description).toBe('User 1 identity');
+
+ expect(result2).toHaveLength(1);
+ expect(result2[0].description).toBe('User 2 identity');
+ });
+
+ it('should return correct fields for injection', async () => {
+ const model = new UserMemoryIdentityModel(serverDB, userId);
+
+ const now = new Date();
+ await serverDB.insert(userMemoriesIdentities).values({
+ id: genIdentityId(),
+ userId,
+ description: 'Test description',
+ relationship: RelationshipEnum.Self,
+ role: 'Test Role',
+ type: 'professional',
+ capturedAt: now,
+ });
+
+ const result = await model.queryForInjection();
+
+ expect(result).toHaveLength(1);
+ const identity = result[0];
+
+ // Check that required fields are present
+ expect(identity).toHaveProperty('id');
+ expect(identity).toHaveProperty('description');
+ expect(identity).toHaveProperty('role');
+ expect(identity).toHaveProperty('type');
+ expect(identity).toHaveProperty('createdAt');
+ expect(identity).toHaveProperty('updatedAt');
+ expect(identity).toHaveProperty('capturedAt');
+
+ // Check values
+ expect(identity.description).toBe('Test description');
+ expect(identity.role).toBe('Test Role');
+ expect(identity.type).toBe('professional');
+ });
+
+ it('should return empty array when no self identities exist', async () => {
+ const model = new UserMemoryIdentityModel(serverDB, userId);
+
+ // No identities inserted
+ const result = await model.queryForInjection();
+
+ expect(result).toHaveLength(0);
+ });
+
+ it('should handle mixed relationships correctly', async () => {
+ const model = new UserMemoryIdentityModel(serverDB, userId);
+
+ const now = new Date();
+ await serverDB.insert(userMemoriesIdentities).values([
+ {
+ id: genIdentityId(),
+ userId,
+ description: 'Self 1',
+ relationship: RelationshipEnum.Self,
+ type: 'personal',
+ capturedAt: new Date(now.getTime() - 1000),
+ },
+ {
+ id: genIdentityId(),
+ userId,
+ description: 'Friend',
+ relationship: RelationshipEnum.Friend,
+ type: 'personal',
+ capturedAt: new Date(now.getTime() - 2000),
+ },
+ {
+ id: genIdentityId(),
+ userId,
+ description: 'Null relationship',
+ relationship: null,
+ type: 'personal',
+ capturedAt: new Date(now.getTime() - 3000),
+ },
+ {
+ id: genIdentityId(),
+ userId,
+ description: 'Spouse',
+ relationship: RelationshipEnum.Spouse,
+ type: 'personal',
+ capturedAt: new Date(now.getTime() - 4000),
+ },
+ {
+ id: genIdentityId(),
+ userId,
+ description: 'Self 2',
+ relationship: RelationshipEnum.Self,
+ type: 'demographic',
+ capturedAt: new Date(now.getTime() - 5000),
+ },
+ ]);
+
+ const result = await model.queryForInjection();
+
+ // Should only return Self 1, Null relationship, and Self 2
+ expect(result).toHaveLength(3);
+ const descriptions = result.map((r) => r.description);
+ expect(descriptions).toContain('Self 1');
+ expect(descriptions).toContain('Null relationship');
+ expect(descriptions).toContain('Self 2');
+ expect(descriptions).not.toContain('Friend');
+ expect(descriptions).not.toContain('Spouse');
+ });
+ });
+});
diff --git a/packages/database/src/models/userMemory/identity.ts b/packages/database/src/models/userMemory/identity.ts
index 0a75b267f02..1eabfed5844 100644
--- a/packages/database/src/models/userMemory/identity.ts
+++ b/packages/database/src/models/userMemory/identity.ts
@@ -1,4 +1,5 @@
-import { and, desc, eq } from 'drizzle-orm';
+import { RelationshipEnum } from '@lobechat/types';
+import { and, desc, eq, isNull, or } from 'drizzle-orm';
import {
NewUserMemoryIdentity,
@@ -78,4 +79,35 @@ export class UserMemoryIdentityModel {
and(eq(userMemoriesIdentities.id, id), eq(userMemoriesIdentities.userId, this.userId)),
);
};
+
+ /**
+ * Query identities for chat context injection
+ * Only returns user's own identities (relationship === 'self' or null/undefined)
+ * Limited to most recent entries for performance
+ */
+ queryForInjection = async (limit = 50) => {
+ return this.db
+ .select({
+ capturedAt: userMemoriesIdentities.capturedAt,
+ createdAt: userMemoriesIdentities.createdAt,
+ description: userMemoriesIdentities.description,
+ id: userMemoriesIdentities.id,
+ role: userMemoriesIdentities.role,
+ type: userMemoriesIdentities.type,
+ updatedAt: userMemoriesIdentities.updatedAt,
+ })
+ .from(userMemoriesIdentities)
+ .where(
+ and(
+ eq(userMemoriesIdentities.userId, this.userId),
+ // Only include self identities (relationship is 'self' or null/not set)
+ or(
+ eq(userMemoriesIdentities.relationship, RelationshipEnum.Self),
+ isNull(userMemoriesIdentities.relationship),
+ ),
+ ),
+ )
+ .orderBy(desc(userMemoriesIdentities.capturedAt))
+ .limit(limit);
+ };
}
diff --git a/packages/database/src/repositories/userMemory/UserMemoryTopicRepository.ts b/packages/database/src/repositories/userMemory/UserMemoryTopicRepository.ts
new file mode 100644
index 00000000000..1fa8911986d
--- /dev/null
+++ b/packages/database/src/repositories/userMemory/UserMemoryTopicRepository.ts
@@ -0,0 +1,63 @@
+import { and, asc, eq } from 'drizzle-orm';
+
+import { messages } from '../../schemas';
+import { LobeChatDatabase } from '../../type';
+
+/**
+ * Maximum character length for the query string used in memory search
+ */
+const MAX_QUERY_LENGTH = 7000;
+
+/**
+ * Repository for user memory operations related to topics
+ */
+export class UserMemoryTopicRepository {
+ private userId: string;
+ private db: LobeChatDatabase;
+
+ constructor(db: LobeChatDatabase, userId: string) {
+ this.userId = userId;
+ this.db = db;
+ }
+
+ /**
+ * Get concatenated user message content for a topic, truncated to max length
+ * This is used for memory retrieval based on conversation context
+ *
+ * @param topicId - The topic ID to get messages from
+ * @returns Concatenated user message content (first 7000 chars) or null if no messages
+ */
+ async getUserMessagesQueryForTopic(topicId: string): Promise<string | null> {
+ // Query user messages for this topic, ordered by creation time
+ const userMessages = await this.db
+ .select({
+ content: messages.content,
+ })
+ .from(messages)
+ .where(
+ and(
+ eq(messages.userId, this.userId),
+ eq(messages.topicId, topicId),
+ eq(messages.role, 'user'),
+ ),
+ )
+ .orderBy(asc(messages.createdAt));
+
+ if (userMessages.length === 0) {
+ return null;
+ }
+
+ // Concatenate all user message content
+ const concatenatedContent = userMessages
+ .map((msg) => msg.content)
+ .filter((content): content is string => !!content)
+ .join('\n');
+
+ if (!concatenatedContent) {
+ return null;
+ }
+
+ // Truncate to max length
+ return concatenatedContent.slice(0, MAX_QUERY_LENGTH);
+ }
+}
diff --git a/packages/database/src/repositories/userMemory/__tests__/UserMemoryTopicRepository.test.ts b/packages/database/src/repositories/userMemory/__tests__/UserMemoryTopicRepository.test.ts
new file mode 100644
index 00000000000..492bf6d66f7
--- /dev/null
+++ b/packages/database/src/repositories/userMemory/__tests__/UserMemoryTopicRepository.test.ts
@@ -0,0 +1,189 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../models/__tests__/_util';
+import { messages } from '../../../schemas/message';
+import { topics } from '../../../schemas/topic';
+import { users } from '../../../schemas/user';
+import { LobeChatDatabase } from '../../../type';
+import { UserMemoryTopicRepository } from '../UserMemoryTopicRepository';
+
+const userId = 'user-memory-topic-test-user';
+const topicId = 'test-topic-1';
+
+let repo: UserMemoryTopicRepository;
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+beforeEach(async () => {
+ // Clean up
+ await serverDB.delete(messages);
+ await serverDB.delete(topics);
+ await serverDB.delete(users);
+
+ // Create test user
+ await serverDB.insert(users).values({ id: userId });
+
+ // Create test topic
+ await serverDB.insert(topics).values({ id: topicId, userId });
+
+ // Initialize repo
+ repo = new UserMemoryTopicRepository(serverDB, userId);
+});
+
+describe('UserMemoryTopicRepository', () => {
+ describe('getUserMessagesQueryForTopic', () => {
+ it('should return null when no user messages exist', async () => {
+ const result = await repo.getUserMessagesQueryForTopic(topicId);
+ expect(result).toBeNull();
+ });
+
+ it('should return null when only assistant messages exist', async () => {
+ await serverDB.insert(messages).values([
+ { id: 'msg-1', content: 'Hello!', role: 'assistant', topicId, userId },
+ { id: 'msg-2', content: 'How can I help?', role: 'assistant', topicId, userId },
+ ]);
+
+ const result = await repo.getUserMessagesQueryForTopic(topicId);
+ expect(result).toBeNull();
+ });
+
+ it('should return concatenated user message content', async () => {
+ await serverDB.insert(messages).values([
+ { id: 'msg-1', content: 'Hello', role: 'user', topicId, userId },
+ { id: 'msg-2', content: 'Hi there!', role: 'assistant', topicId, userId },
+ { id: 'msg-3', content: 'How are you?', role: 'user', topicId, userId },
+ ]);
+
+ const result = await repo.getUserMessagesQueryForTopic(topicId);
+ expect(result).toBe('Hello\nHow are you?');
+ });
+
+ it('should order messages by createdAt', async () => {
+ await serverDB.insert(messages).values([
+ {
+ id: 'msg-3',
+ content: 'Third message',
+ role: 'user',
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-03'),
+ },
+ {
+ id: 'msg-1',
+ content: 'First message',
+ role: 'user',
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01'),
+ },
+ {
+ id: 'msg-2',
+ content: 'Second message',
+ role: 'user',
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-02'),
+ },
+ ]);
+
+ const result = await repo.getUserMessagesQueryForTopic(topicId);
+ expect(result).toBe('First message\nSecond message\nThird message');
+ });
+
+ it('should truncate result to 7000 characters', async () => {
+ // Create a message with content longer than 7000 chars
+ const longContent = 'A'.repeat(8000);
+ await serverDB
+ .insert(messages)
+ .values([{ id: 'msg-1', content: longContent, role: 'user', topicId, userId }]);
+
+ const result = await repo.getUserMessagesQueryForTopic(topicId);
+ expect(result).toHaveLength(7000);
+ expect(result).toBe('A'.repeat(7000));
+ });
+
+ it('should truncate concatenated content to 7000 characters', async () => {
+ // Create multiple messages that together exceed 7000 chars
+ const content1 = 'B'.repeat(4000);
+ const content2 = 'C'.repeat(4000);
+ await serverDB.insert(messages).values([
+ {
+ id: 'msg-1',
+ content: content1,
+ role: 'user',
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-01'),
+ },
+ {
+ id: 'msg-2',
+ content: content2,
+ role: 'user',
+ topicId,
+ userId,
+ createdAt: new Date('2024-01-02'),
+ },
+ ]);
+
+ const result = await repo.getUserMessagesQueryForTopic(topicId);
+ expect(result).toHaveLength(7000);
+ // Should be content1 + newline + first part of content2
+ expect(result!.startsWith('B'.repeat(4000))).toBe(true);
+ });
+
+ it('should filter messages by topic', async () => {
+ const otherTopicId = 'other-topic';
+ await serverDB.insert(topics).values({ id: otherTopicId, userId });
+
+ await serverDB.insert(messages).values([
+ { id: 'msg-1', content: 'Topic 1 message', role: 'user', topicId, userId },
+ {
+ id: 'msg-2',
+ content: 'Other topic message',
+ role: 'user',
+ topicId: otherTopicId,
+ userId,
+ },
+ ]);
+
+ const result = await repo.getUserMessagesQueryForTopic(topicId);
+ expect(result).toBe('Topic 1 message');
+ });
+
+ it('should filter messages by user', async () => {
+ const otherUserId = 'other-user';
+ await serverDB.insert(users).values({ id: otherUserId });
+
+ await serverDB.insert(messages).values([
+ { id: 'msg-1', content: 'My message', role: 'user', topicId, userId },
+ { id: 'msg-2', content: 'Other user message', role: 'user', topicId, userId: otherUserId },
+ ]);
+
+ const result = await repo.getUserMessagesQueryForTopic(topicId);
+ expect(result).toBe('My message');
+ });
+
+ it('should skip messages with null or empty content', async () => {
+ await serverDB.insert(messages).values([
+ { id: 'msg-1', content: 'Valid message', role: 'user', topicId, userId },
+ { id: 'msg-2', content: null, role: 'user', topicId, userId },
+ { id: 'msg-3', content: '', role: 'user', topicId, userId },
+ { id: 'msg-4', content: 'Another valid', role: 'user', topicId, userId },
+ ]);
+
+ const result = await repo.getUserMessagesQueryForTopic(topicId);
+ expect(result).toBe('Valid message\nAnother valid');
+ });
+
+ it('should return null when all user messages have empty content', async () => {
+ await serverDB.insert(messages).values([
+ { id: 'msg-1', content: null, role: 'user', topicId, userId },
+ { id: 'msg-2', content: '', role: 'user', topicId, userId },
+ ]);
+
+ const result = await repo.getUserMessagesQueryForTopic(topicId);
+ expect(result).toBeNull();
+ });
+ });
+});
diff --git a/packages/database/src/repositories/userMemory/index.ts b/packages/database/src/repositories/userMemory/index.ts
index 2cd16e135b4..735185a5b2a 100644
--- a/packages/database/src/repositories/userMemory/index.ts
+++ b/packages/database/src/repositories/userMemory/index.ts
@@ -5,6 +5,8 @@ import {
UserMemoryPreferencesWithoutVectors,
} from '../../schemas';
+export { UserMemoryTopicRepository } from './UserMemoryTopicRepository';
+
export interface MemorySource {
agentId: string | null;
id: string;
diff --git a/packages/prompts/src/prompts/index.ts b/packages/prompts/src/prompts/index.ts
index eb62c0e6a35..43fcf40faad 100644
--- a/packages/prompts/src/prompts/index.ts
+++ b/packages/prompts/src/prompts/index.ts
@@ -9,3 +9,4 @@ export * from './messagesToText';
export * from './plugin';
export * from './search';
export * from './systemRole';
+export * from './userMemory';
diff --git a/packages/prompts/src/prompts/userMemory/__snapshots__/index.test.ts.snap b/packages/prompts/src/prompts/userMemory/__snapshots__/index.test.ts.snap
new file mode 100644
index 00000000000..c5676d7a6e8
--- /dev/null
+++ b/packages/prompts/src/prompts/userMemory/__snapshots__/index.test.ts.snap
@@ -0,0 +1,318 @@
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+
+exports[`promptUserMemory > contexts only > should format multiple contexts 1`] = `
+"<user_memory>
+<instruction>The following are memories about this user retrieved from previous conversations. Use this information to personalize your responses and maintain continuity.</instruction>
+<contexts count="3">
+ <context id="ctx-1" title="Language Preference">User prefers TypeScript over JavaScript</context>
+ <context id="ctx-2" title="Current Project">User is building a SaaS product</context>
+ <context id="ctx-3" title="Location">User is based in San Francisco timezone</context>
+</contexts>
+</user_memory>"
+`;
+
+exports[`promptUserMemory > contexts only > should format single context 1`] = `
+"<user_memory>
+<instruction>The following are memories about this user retrieved from previous conversations. Use this information to personalize your responses and maintain continuity.</instruction>
+<contexts count="1">
+ <context id="ctx-1" title="Professional Background">User is a software engineer working on web applications</context>
+</contexts>
+</user_memory>"
+`;
+
+exports[`promptUserMemory > contexts only > should handle context with null/undefined values 1`] = `
+"<user_memory>
+<instruction>The following are memories about this user retrieved from previous conversations. Use this information to personalize your responses and maintain continuity.</instruction>
+<contexts count="1">
+ <context id="ctx-1" title=""></context>
+</contexts>
+</user_memory>"
+`;
+
+exports[`promptUserMemory > contexts only > should handle context without id 1`] = `
+"<user_memory>
+<instruction>The following are memories about this user retrieved from previous conversations. Use this information to personalize your responses and maintain continuity.</instruction>
+<contexts count="1">
+ <context id="" title="Some Title">Some context description</context>
+</contexts>
+</user_memory>"
+`;
+
+exports[`promptUserMemory > edge cases > should handle multiline content 1`] = `
+"<user_memory>
+<instruction>The following are memories about this user retrieved from previous conversations. Use this information to personalize your responses and maintain continuity.</instruction>
+<contexts count="1">
+ <context id="ctx-1" title="Multi-line Context">Line 1: First point
+Line 2: Second point
+Line 3: Third point</context>
+</contexts>
+</user_memory>"
+`;
+
+exports[`promptUserMemory > edge cases > should handle special characters in content 1`] = `
+"<user_memory>
+<instruction>The following are memories about this user retrieved from previous conversations. Use this information to personalize your responses and maintain continuity.</instruction>
+<contexts count="1">
+ <context id="ctx-1" title="Tech Stack & Tools">Uses <React/> & Vue.js frameworks with "strict" mode</context>
+</contexts>
+</user_memory>"
+`;
+
+exports[`promptUserMemory > edge cases > should handle unicode characters 1`] = `
+"<user_memory>
+<instruction>The following are memories about this user retrieved from previous conversations. Use this information to personalize your responses and maintain continuity.</instruction>
+<contexts count="1">
+ <context id="ctx-1" title="语言偏好 🌍">用户偏好中文回复 🚀 with émojis and spëcial chàracters</context>
+</contexts>
+</user_memory>"
+`;
+
+exports[`promptUserMemory > edge cases > should handle very long content 1`] = `
+"<user_memory>
+<instruction>The following are memories about this user retrieved from previous conversations. Use this information to personalize your responses and maintain continuity.</instruction>
+<contexts count="1">
+ <context id="ctx-1" title="Long Content Test">AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA</context>
+</contexts>
+</user_memory>"
+`;
+
+exports[`promptUserMemory > experiences only > should format multiple experiences 1`] = `
+"<user_memory>
+<instruction>The following are memories about this user retrieved from previous conversations. Use this information to personalize your responses and maintain continuity.</instruction>
+<experiences count="2">
+ <experience id="exp-1">
+ <situation>Debugging a memory leak in Node.js</situation>
+ <key_learning>User likes step-by-step debugging guidance</key_learning>
+ </experience>
+ <experience id="exp-2">
+ <situation>Discussing database schema design</situation>
+ <key_learning>User appreciates alternative approaches being mentioned</key_learning>
+ </experience>
+</experiences>
+</user_memory>"
+`;
+
+exports[`promptUserMemory > experiences only > should format single experience 1`] = `
+"<user_memory>
+<instruction>The following are memories about this user retrieved from previous conversations. Use this information to personalize your responses and maintain continuity.</instruction>
+<experiences count="1">
+ <experience id="exp-1">
+ <situation>User asked about React hooks implementation</situation>
+ <key_learning>User prefers concise explanations with code examples</key_learning>
+ </experience>
+</experiences>
+</user_memory>"
+`;
+
+exports[`promptUserMemory > experiences only > should handle experience with null/undefined values 1`] = `
+"<user_memory>
+<instruction>The following are memories about this user retrieved from previous conversations. Use this information to personalize your responses and maintain continuity.</instruction>
+<experiences count="1">
+ <experience id="exp-1">
+ <situation></situation>
+ <key_learning></key_learning>
+ </experience>
+</experiences>
+</user_memory>"
+`;
+
+exports[`promptUserMemory > identities only > should format identities grouped by type 1`] = `
+"<user_memory>
+<instruction>The following are memories about this user retrieved from previous conversations. Use this information to personalize your responses and maintain continuity.</instruction>
+<identities count="3">
+ <personal count="1">
+ <identity role="Father">User is a father of two children</identity>
+ </personal>
+ <professional count="1">
+ <identity role="Software Engineer">User is a senior software engineer</identity>
+ </professional>
+ <demographic count="1">
+ <identity>User is based in Shanghai</identity>
+ </demographic>
+</identities>
+</user_memory>"
+`;
+
+exports[`promptUserMemory > identities only > should format single type identities (demographic only) 1`] = `
+"<user_memory>
+<instruction>The following are memories about this user retrieved from previous conversations. Use this information to personalize your responses and maintain continuity.</instruction>
+<identities count="2">
+ <demographic count="2">
+ <identity>User is 35 years old</identity>
+ <identity>User speaks Mandarin and English</identity>
+ </demographic>
+</identities>
+</user_memory>"
+`;
+
+exports[`promptUserMemory > identities only > should format single type identities (personal only) 1`] = `
+"<user_memory>
+<instruction>The following are memories about this user retrieved from previous conversations. Use this information to personalize your responses and maintain continuity.</instruction>
+<identities count="2">
+ <personal count="2">
+ <identity>User is married</identity>
+ <identity>User has a pet dog</identity>
+ </personal>
+</identities>
+</user_memory>"
+`;
+
+exports[`promptUserMemory > identities only > should format single type identities (professional only) 1`] = `
+"<user_memory>
+<instruction>The following are memories about this user retrieved from previous conversations. Use this information to personalize your responses and maintain continuity.</instruction>
+<identities count="1">
+ <professional count="1">
+ <identity role="CTO">User works at a tech startup</identity>
+ </professional>
+</identities>
+</user_memory>"
+`;
+
+exports[`promptUserMemory > identities only > should handle identity with null values 1`] = `
+"<user_memory>
+<instruction>The following are memories about this user retrieved from previous conversations. Use this information to personalize your responses and maintain continuity.</instruction>
+<identities count="1">
+ <personal count="1">
+ <identity></identity>
+ </personal>
+</identities>
+</user_memory>"
+`;
+
+exports[`promptUserMemory > identities only > should handle identity without role 1`] = `
+"<user_memory>
+<instruction>The following are memories about this user retrieved from previous conversations. Use this information to personalize your responses and maintain continuity.</instruction>
+<identities count="1">
+ <personal count="1">
+ <identity>User enjoys hiking</identity>
+ </personal>
+</identities>
+</user_memory>"
+`;
+
+exports[`promptUserMemory > mixed memory types > should format all memory types together 1`] = `
+"<user_memory>
+<instruction>The following are memories about this user retrieved from previous conversations. Use this information to personalize your responses and maintain continuity.</instruction>
+<identities count="1">
+ <professional count="1">
+ <identity role="Tech Lead">User is a tech lead at a startup</identity>
+ </professional>
+</identities>
+<contexts count="1">
+ <context id="ctx-1" title="Experience Level">Senior developer with 10 years experience</context>
+</contexts>
+<experiences count="1">
+ <experience id="exp-1">
+ <situation>System design conversation</situation>
+ <key_learning>Prefers detailed architectural discussions</key_learning>
+ </experience>
+</experiences>
+<preferences count="1">
+ <preference id="pref-1">Use design patterns when appropriate</preference>
+</preferences>
+</user_memory>"
+`;
+
+exports[`promptUserMemory > mixed memory types > should format all memory types with multiple identities 1`] = `
+"<user_memory>
+<instruction>The following are memories about this user retrieved from previous conversations. Use this information to personalize your responses and maintain continuity.</instruction>
+<identities count="3">
+ <personal count="1">
+ <identity role="Father">User is a father</identity>
+ </personal>
+ <professional count="1">
+ <identity role="Senior Engineer">User is a senior engineer</identity>
+ </professional>
+ <demographic count="1">
+ <identity>User lives in Beijing</identity>
+ </demographic>
+</identities>
+<contexts count="1">
+ <context id="ctx-1" title="Current Work">Working on AI products</context>
+</contexts>
+<experiences count="1">
+ <experience id="exp-1">
+ <situation>Code review session</situation>
+ <key_learning>Likes practical examples</key_learning>
+ </experience>
+</experiences>
+<preferences count="1">
+ <preference id="pref-1">Prefer concise responses</preference>
+</preferences>
+</user_memory>"
+`;
+
+exports[`promptUserMemory > mixed memory types > should format contexts and experiences without preferences 1`] = `
+"<user_memory>
+<instruction>The following are memories about this user retrieved from previous conversations. Use this information to personalize your responses and maintain continuity.</instruction>
+<contexts count="1">
+ <context id="ctx-1" title="Current Focus">Working on mobile app development</context>
+</contexts>
+<experiences count="1">
+ <experience id="exp-1">
+ <situation>Mobile development discussion</situation>
+ <key_learning>Likes React Native examples</key_learning>
+ </experience>
+</experiences>
+</user_memory>"
+`;
+
+exports[`promptUserMemory > mixed memory types > should format contexts and preferences without experiences 1`] = `
+"<user_memory>
+<instruction>The following are memories about this user retrieved from previous conversations. Use this information to personalize your responses and maintain continuity.</instruction>
+<contexts count="1">
+ <context id="ctx-1" title="Specialization">Backend developer specializing in APIs</context>
+</contexts>
+<preferences count="1">
+ <preference id="pref-1">Always include error handling in examples</preference>
+</preferences>
+</user_memory>"
+`;
+
+exports[`promptUserMemory > mixed memory types > should format experiences and preferences without contexts 1`] = `
+"<user_memory>
+<instruction>The following are memories about this user retrieved from previous conversations. Use this information to personalize your responses and maintain continuity.</instruction>
+<experiences count="1">
+ <experience id="exp-1">
+ <situation>Database query optimization</situation>
+ <key_learning>Appreciates performance optimization tips</key_learning>
+ </experience>
+</experiences>
+<preferences count="1">
+ <preference id="pref-1">Mention time complexity for algorithms</preference>
+</preferences>
+</user_memory>"
+`;
+
+exports[`promptUserMemory > preferences only > should filter out empty preferences and keep valid ones 1`] = `
+"<user_memory>
+<instruction>The following are memories about this user retrieved from previous conversations. Use this information to personalize your responses and maintain continuity.</instruction>
+<preferences count="1">
+ <preference id="pref-2">Valid preference</preference>
+</preferences>
+</user_memory>"
+`;
+
+exports[`promptUserMemory > preferences only > should format multiple preferences 1`] = `
+"<user_memory>
+<instruction>The following are memories about this user retrieved from previous conversations. Use this information to personalize your responses and maintain continuity.</instruction>
+<preferences count="3">
+ <preference id="pref-1">Prefer functional programming patterns</preference>
+ <preference id="pref-2">Use ESLint with Prettier for formatting</preference>
+ <preference id="pref-3">Write unit tests for all new features</preference>
+</preferences>
+</user_memory>"
+`;
+
+exports[`promptUserMemory > preferences only > should format single preference 1`] = `
+"<user_memory>
+<instruction>The following are memories about this user retrieved from previous conversations. Use this information to personalize your responses and maintain continuity.</instruction>
+<preferences count="1">
+ <preference id="pref-1">Always use TypeScript strict mode</preference>
+</preferences>
+</user_memory>"
+`;
+
+exports[`promptUserMemory > preferences only > should skip preference with empty conclusionDirectives 1`] = `""`;
+
+exports[`promptUserMemory > preferences only > should skip preference with null conclusionDirectives 1`] = `""`;
diff --git a/packages/prompts/src/prompts/userMemory/index.test.ts b/packages/prompts/src/prompts/userMemory/index.test.ts
new file mode 100644
index 00000000000..a2eace10bbe
--- /dev/null
+++ b/packages/prompts/src/prompts/userMemory/index.test.ts
@@ -0,0 +1,566 @@
+import { describe, expect, it } from 'vitest';
+
+import { promptUserMemory } from './index';
+
+describe('promptUserMemory', () => {
+ describe('empty cases', () => {
+ it('should return empty string when no memories at all', () => {
+ const result = promptUserMemory({
+ memories: {},
+ });
+ expect(result).toBe('');
+ });
+
+ it('should return empty string when all memory arrays are empty', () => {
+ const result = promptUserMemory({
+ memories: {
+ contexts: [],
+ experiences: [],
+ preferences: [],
+ },
+ });
+ expect(result).toBe('');
+ });
+ });
+
+ describe('contexts only', () => {
+ it('should format single context', () => {
+ const result = promptUserMemory({
+ memories: {
+ contexts: [
+ {
+ description: 'User is a software engineer working on web applications',
+ id: 'ctx-1',
+ title: 'Professional Background',
+ },
+ ],
+ },
+ });
+ expect(result).toMatchSnapshot();
+ });
+
+ it('should format multiple contexts', () => {
+ const result = promptUserMemory({
+ memories: {
+ contexts: [
+ {
+ description: 'User prefers TypeScript over JavaScript',
+ id: 'ctx-1',
+ title: 'Language Preference',
+ },
+ {
+ description: 'User is building a SaaS product',
+ id: 'ctx-2',
+ title: 'Current Project',
+ },
+ {
+ description: 'User is based in San Francisco timezone',
+ id: 'ctx-3',
+ title: 'Location',
+ },
+ ],
+ },
+ });
+ expect(result).toMatchSnapshot();
+ });
+
+ it('should handle context with null/undefined values', () => {
+ const result = promptUserMemory({
+ memories: {
+ contexts: [
+ {
+ description: null,
+ id: 'ctx-1',
+ title: null,
+ },
+ ],
+ },
+ });
+ expect(result).toMatchSnapshot();
+ });
+
+ it('should handle context without id', () => {
+ const result = promptUserMemory({
+ memories: {
+ contexts: [
+ {
+ description: 'Some context description',
+ title: 'Some Title',
+ },
+ ],
+ },
+ });
+ expect(result).toMatchSnapshot();
+ });
+ });
+
+ describe('experiences only', () => {
+ it('should format single experience', () => {
+ const result = promptUserMemory({
+ memories: {
+ experiences: [
+ {
+ id: 'exp-1',
+ keyLearning: 'User prefers concise explanations with code examples',
+ situation: 'User asked about React hooks implementation',
+ },
+ ],
+ },
+ });
+ expect(result).toMatchSnapshot();
+ });
+
+ it('should format multiple experiences', () => {
+ const result = promptUserMemory({
+ memories: {
+ experiences: [
+ {
+ id: 'exp-1',
+ keyLearning: 'User likes step-by-step debugging guidance',
+ situation: 'Debugging a memory leak in Node.js',
+ },
+ {
+ id: 'exp-2',
+ keyLearning: 'User appreciates alternative approaches being mentioned',
+ situation: 'Discussing database schema design',
+ },
+ ],
+ },
+ });
+ expect(result).toMatchSnapshot();
+ });
+
+ it('should handle experience with null/undefined values', () => {
+ const result = promptUserMemory({
+ memories: {
+ experiences: [
+ {
+ id: 'exp-1',
+ keyLearning: null,
+ situation: null,
+ },
+ ],
+ },
+ });
+ expect(result).toMatchSnapshot();
+ });
+ });
+
+ describe('preferences only', () => {
+ it('should format single preference', () => {
+ const result = promptUserMemory({
+ memories: {
+ preferences: [
+ {
+ conclusionDirectives: 'Always use TypeScript strict mode',
+ id: 'pref-1',
+ },
+ ],
+ },
+ });
+ expect(result).toMatchSnapshot();
+ });
+
+ it('should format multiple preferences', () => {
+ const result = promptUserMemory({
+ memories: {
+ preferences: [
+ {
+ conclusionDirectives: 'Prefer functional programming patterns',
+ id: 'pref-1',
+ },
+ {
+ conclusionDirectives: 'Use ESLint with Prettier for formatting',
+ id: 'pref-2',
+ },
+ {
+ conclusionDirectives: 'Write unit tests for all new features',
+ id: 'pref-3',
+ },
+ ],
+ },
+ });
+ expect(result).toMatchSnapshot();
+ });
+
+ it('should skip preference with null conclusionDirectives', () => {
+ const result = promptUserMemory({
+ memories: {
+ preferences: [
+ {
+ conclusionDirectives: null,
+ id: 'pref-1',
+ },
+ ],
+ },
+ });
+ expect(result).toMatchSnapshot();
+ });
+
+ it('should skip preference with empty conclusionDirectives', () => {
+ const result = promptUserMemory({
+ memories: {
+ preferences: [
+ {
+ conclusionDirectives: '',
+ id: 'pref-1',
+ },
+ ],
+ },
+ });
+ expect(result).toMatchSnapshot();
+ });
+
+ it('should filter out empty preferences and keep valid ones', () => {
+ const result = promptUserMemory({
+ memories: {
+ preferences: [
+ {
+ conclusionDirectives: null,
+ id: 'pref-1',
+ },
+ {
+ conclusionDirectives: 'Valid preference',
+ id: 'pref-2',
+ },
+ {
+ conclusionDirectives: '',
+ id: 'pref-3',
+ },
+ ],
+ },
+ });
+ expect(result).toMatchSnapshot();
+ });
+ });
+
+ describe('identities only', () => {
+ it('should format identities grouped by type', () => {
+ const result = promptUserMemory({
+ memories: {
+ identities: [
+ {
+ description: 'User is a father of two children',
+ id: 'id-1',
+ role: 'Father',
+ type: 'personal',
+ },
+ {
+ description: 'User is a senior software engineer',
+ id: 'id-2',
+ role: 'Software Engineer',
+ type: 'professional',
+ },
+ {
+ description: 'User is based in Shanghai',
+ id: 'id-3',
+ type: 'demographic',
+ },
+ ],
+ },
+ });
+ expect(result).toMatchSnapshot();
+ });
+
+ it('should format single type identities (personal only)', () => {
+ const result = promptUserMemory({
+ memories: {
+ identities: [
+ {
+ description: 'User is married',
+ id: 'id-1',
+ type: 'personal',
+ },
+ {
+ description: 'User has a pet dog',
+ id: 'id-2',
+ type: 'personal',
+ },
+ ],
+ },
+ });
+ expect(result).toMatchSnapshot();
+ });
+
+ it('should format single type identities (professional only)', () => {
+ const result = promptUserMemory({
+ memories: {
+ identities: [
+ {
+ description: 'User works at a tech startup',
+ id: 'id-1',
+ role: 'CTO',
+ type: 'professional',
+ },
+ ],
+ },
+ });
+ expect(result).toMatchSnapshot();
+ });
+
+ it('should format single type identities (demographic only)', () => {
+ const result = promptUserMemory({
+ memories: {
+ identities: [
+ {
+ description: 'User is 35 years old',
+ id: 'id-1',
+ type: 'demographic',
+ },
+ {
+ description: 'User speaks Mandarin and English',
+ id: 'id-2',
+ type: 'demographic',
+ },
+ ],
+ },
+ });
+ expect(result).toMatchSnapshot();
+ });
+
+ it('should handle identity without role', () => {
+ const result = promptUserMemory({
+ memories: {
+ identities: [
+ {
+ description: 'User enjoys hiking',
+ id: 'id-1',
+ type: 'personal',
+ },
+ ],
+ },
+ });
+ expect(result).toMatchSnapshot();
+ });
+
+ it('should handle identity with null values', () => {
+ const result = promptUserMemory({
+ memories: {
+ identities: [
+ {
+ description: null,
+ id: 'id-1',
+ role: null,
+ type: 'personal',
+ },
+ ],
+ },
+ });
+ expect(result).toMatchSnapshot();
+ });
+ });
+
+ describe('mixed memory types', () => {
+ it('should format all memory types together', () => {
+ const result = promptUserMemory({
+ memories: {
+ contexts: [
+ {
+ description: 'Senior developer with 10 years experience',
+ id: 'ctx-1',
+ title: 'Experience Level',
+ },
+ ],
+ experiences: [
+ {
+ id: 'exp-1',
+ keyLearning: 'Prefers detailed architectural discussions',
+ situation: 'System design conversation',
+ },
+ ],
+ identities: [
+ {
+ description: 'User is a tech lead at a startup',
+ id: 'id-1',
+ role: 'Tech Lead',
+ type: 'professional',
+ },
+ ],
+ preferences: [
+ {
+ conclusionDirectives: 'Use design patterns when appropriate',
+ id: 'pref-1',
+ },
+ ],
+ },
+ });
+ expect(result).toMatchSnapshot();
+ });
+
+ it('should format all memory types with multiple identities', () => {
+ const result = promptUserMemory({
+ memories: {
+ contexts: [
+ {
+ description: 'Working on AI products',
+ id: 'ctx-1',
+ title: 'Current Work',
+ },
+ ],
+ experiences: [
+ {
+ id: 'exp-1',
+ keyLearning: 'Likes practical examples',
+ situation: 'Code review session',
+ },
+ ],
+ identities: [
+ {
+ description: 'User is a father',
+ id: 'id-1',
+ role: 'Father',
+ type: 'personal',
+ },
+ {
+ description: 'User is a senior engineer',
+ id: 'id-2',
+ role: 'Senior Engineer',
+ type: 'professional',
+ },
+ {
+ description: 'User lives in Beijing',
+ id: 'id-3',
+ type: 'demographic',
+ },
+ ],
+ preferences: [
+ {
+ conclusionDirectives: 'Prefer concise responses',
+ id: 'pref-1',
+ },
+ ],
+ },
+ });
+ expect(result).toMatchSnapshot();
+ });
+
+ it('should format contexts and experiences without preferences', () => {
+ const result = promptUserMemory({
+ memories: {
+ contexts: [
+ {
+ description: 'Working on mobile app development',
+ id: 'ctx-1',
+ title: 'Current Focus',
+ },
+ ],
+ experiences: [
+ {
+ id: 'exp-1',
+ keyLearning: 'Likes React Native examples',
+ situation: 'Mobile development discussion',
+ },
+ ],
+ },
+ });
+ expect(result).toMatchSnapshot();
+ });
+
+ it('should format contexts and preferences without experiences', () => {
+ const result = promptUserMemory({
+ memories: {
+ contexts: [
+ {
+ description: 'Backend developer specializing in APIs',
+ id: 'ctx-1',
+ title: 'Specialization',
+ },
+ ],
+ preferences: [
+ {
+ conclusionDirectives: 'Always include error handling in examples',
+ id: 'pref-1',
+ },
+ ],
+ },
+ });
+ expect(result).toMatchSnapshot();
+ });
+
+ it('should format experiences and preferences without contexts', () => {
+ const result = promptUserMemory({
+ memories: {
+ experiences: [
+ {
+ id: 'exp-1',
+ keyLearning: 'Appreciates performance optimization tips',
+ situation: 'Database query optimization',
+ },
+ ],
+ preferences: [
+ {
+ conclusionDirectives: 'Mention time complexity for algorithms',
+ id: 'pref-1',
+ },
+ ],
+ },
+ });
+ expect(result).toMatchSnapshot();
+ });
+ });
+
+ describe('edge cases', () => {
+ it('should handle special characters in content', () => {
+ const result = promptUserMemory({
+ memories: {
+ contexts: [
+ {
+ description: 'Uses <React/> & Vue.js frameworks with "strict" mode',
+ id: 'ctx-1',
+ title: 'Tech Stack & Tools',
+ },
+ ],
+ },
+ });
+ expect(result).toMatchSnapshot();
+ });
+
+ it('should handle multiline content', () => {
+ const result = promptUserMemory({
+ memories: {
+ contexts: [
+ {
+ description: `Line 1: First point
+Line 2: Second point
+Line 3: Third point`,
+ id: 'ctx-1',
+ title: 'Multi-line Context',
+ },
+ ],
+ },
+ });
+ expect(result).toMatchSnapshot();
+ });
+
+ it('should handle very long content', () => {
+ const longDescription = 'A'.repeat(500);
+ const result = promptUserMemory({
+ memories: {
+ contexts: [
+ {
+ description: longDescription,
+ id: 'ctx-1',
+ title: 'Long Content Test',
+ },
+ ],
+ },
+ });
+ expect(result).toMatchSnapshot();
+ });
+
+ it('should handle unicode characters', () => {
+ const result = promptUserMemory({
+ memories: {
+ contexts: [
+ {
+ description: '用户偏好中文回复 🚀 with émojis and spëcial chàracters',
+ id: 'ctx-1',
+ title: '语言偏好 🌍',
+ },
+ ],
+ },
+ });
+ expect(result).toMatchSnapshot();
+ });
+ });
+});
diff --git a/packages/prompts/src/prompts/userMemory/index.ts b/packages/prompts/src/prompts/userMemory/index.ts
new file mode 100644
index 00000000000..65b0d6371ea
--- /dev/null
+++ b/packages/prompts/src/prompts/userMemory/index.ts
@@ -0,0 +1,192 @@
+/**
+ * User memory item interfaces
+ */
+export interface UserMemoryContextItem {
+ description?: string | null;
+ id?: string;
+ title?: string | null;
+}
+
+export interface UserMemoryExperienceItem {
+ id?: string;
+ keyLearning?: string | null;
+ situation?: string | null;
+}
+
+export interface UserMemoryPreferenceItem {
+ conclusionDirectives?: string | null;
+ id?: string;
+}
+
+export type IdentityType = 'demographic' | 'personal' | 'professional';
+
+export interface UserMemoryIdentityItem {
+ description?: string | null;
+ id?: string;
+ role?: string | null;
+ type?: IdentityType | string | null;
+}
+
+export interface UserMemoryData {
+ contexts?: UserMemoryContextItem[];
+ experiences?: UserMemoryExperienceItem[];
+ identities?: UserMemoryIdentityItem[];
+ preferences?: UserMemoryPreferenceItem[];
+}
+
+export interface PromptUserMemoryOptions {
+ /** User memories data */
+ memories: UserMemoryData;
+}
+
+/**
+ * Check if a context item has meaningful content
+ */
+const isValidContextItem = (item: UserMemoryContextItem): boolean => {
+ return !!(item.id || item.title || item.description);
+};
+
+/**
+ * Formats a single context memory item
+ * title as attribute, description as children
+ */
+const formatContextItem = (item: UserMemoryContextItem): string => {
+ return ` <context id="${item.id || ''}" title="${item.title || ''}">${item.description || ''}</context>`;
+};
+
+/**
+ * Check if an experience item has meaningful content
+ */
+const isValidExperienceItem = (item: UserMemoryExperienceItem): boolean => {
+ return !!(item.id || item.situation || item.keyLearning);
+};
+
+/**
+ * Formats a single experience memory item
+ */
+const formatExperienceItem = (item: UserMemoryExperienceItem): string => {
+ return ` <experience id="${item.id || ''}">
+ <situation>${item.situation || ''}</situation>
+ <key_learning>${item.keyLearning || ''}</key_learning>
+ </experience>`;
+};
+
+/**
+ * Check if a preference item has meaningful content
+ */
+const isValidPreferenceItem = (item: UserMemoryPreferenceItem): boolean => {
+ return !!item.conclusionDirectives;
+};
+
+/**
+ * Formats a single preference memory item
+ */
+const formatPreferenceItem = (item: UserMemoryPreferenceItem): string => {
+ return ` <preference id="${item.id || ''}">${item.conclusionDirectives}</preference>`;
+};
+
+/**
+ * Check if an identity item has meaningful content
+ */
+const isValidIdentityItem = (item: UserMemoryIdentityItem): boolean => {
+ return !!(item.id || item.description || item.role || item.type);
+};
+
+/**
+ * Formats a single identity memory item
+ */
+const formatIdentityItem = (item: UserMemoryIdentityItem): string => {
+ const roleAttr = item.role ? ` role="${item.role}"` : '';
+ return ` <identity${roleAttr}>${item.description || ''}</identity>`;
+};
+
+/**
+ * Format identities grouped by type as XML
+ * Types: personal (角色), professional (职业), demographic (属性)
+ */
+const formatIdentitiesSection = (identities: UserMemoryIdentityItem[]): string => {
+ const personal = identities.filter((i) => i.type === 'personal');
+ const professional = identities.filter((i) => i.type === 'professional');
+ const demographic = identities.filter((i) => i.type === 'demographic');
+
+ return [
+ personal.length > 0 &&
+ ` <personal count="${personal.length}">\n${personal.map(formatIdentityItem).join('\n')}\n </personal>`,
+ professional.length > 0 &&
+ ` <professional count="${professional.length}">\n${professional.map(formatIdentityItem).join('\n')}\n </professional>`,
+ demographic.length > 0 &&
+ ` <demographic count="${demographic.length}">\n${demographic.map(formatIdentityItem).join('\n')}\n </demographic>`,
+ ]
+ .filter(Boolean)
+ .join('\n');
+};
+
+/**
+ * Format user memories as unified XML prompt
+ *
+ * The memories are organized into four categories:
+ * - identities: User's identity information (who the user is)
+ * - contexts: Background information about the user's situation
+ * - experiences: Past interactions and learnings
+ * - preferences: User's stated preferences and directives
+ */
+export const promptUserMemory = ({ memories }: PromptUserMemoryOptions): string => {
+ // Filter out empty/invalid items
+ const identities = (memories.identities || []).filter(isValidIdentityItem);
+ const contexts = (memories.contexts || []).filter(isValidContextItem);
+ const experiences = (memories.experiences || []).filter(isValidExperienceItem);
+ const preferences = (memories.preferences || []).filter(isValidPreferenceItem);
+
+ const hasIdentities = identities.length > 0;
+ const hasContexts = contexts.length > 0;
+ const hasExperiences = experiences.length > 0;
+ const hasPreferences = preferences.length > 0;
+
+ // If no memories at all, return empty
+ if (!hasIdentities && !hasContexts && !hasExperiences && !hasPreferences) {
+ return '';
+ }
+
+ const contentParts: string[] = [];
+
+ // Add instruction
+ contentParts.push(
+ '<instruction>The following are memories about this user retrieved from previous conversations. Use this information to personalize your responses and maintain continuity.</instruction>',
+ );
+
+ // Add identities section (user's identity information, grouped by type)
+ if (hasIdentities) {
+ const identitiesXml = formatIdentitiesSection(identities);
+ contentParts.push(`<identities count="${identities.length}">
+${identitiesXml}
+</identities>`);
+ }
+
+ // Add contexts section
+ if (hasContexts) {
+ const contextsXml = contexts.map((item) => formatContextItem(item)).join('\n');
+ contentParts.push(`<contexts count="${contexts.length}">
+${contextsXml}
+</contexts>`);
+ }
+
+ // Add experiences section
+ if (hasExperiences) {
+ const experiencesXml = experiences.map((item) => formatExperienceItem(item)).join('\n');
+ contentParts.push(`<experiences count="${experiences.length}">
+${experiencesXml}
+</experiences>`);
+ }
+
+ // Add preferences section
+ if (hasPreferences) {
+ const preferencesXml = preferences.map((item) => formatPreferenceItem(item)).join('\n');
+ contentParts.push(`<preferences count="${preferences.length}">
+${preferencesXml}
+</preferences>`);
+ }
+
+ return `<user_memory>
+${contentParts.join('\n')}
+</user_memory>`;
+};
diff --git a/packages/utils/src/client/parserPlaceholder.ts b/packages/utils/src/client/parserPlaceholder.ts
index a906283323d..bb4fa69fe4e 100644
--- a/packages/utils/src/client/parserPlaceholder.ts
+++ b/packages/utils/src/client/parserPlaceholder.ts
@@ -6,6 +6,7 @@ import { useUserStore } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';
import { uuid } from '../uuid';
+import { globalAgentContextManager } from './GlobalAgentContextManager';
const placeholderVariablesRegex = /{{(.*?)}}/g;
@@ -125,6 +126,30 @@ export const VARIABLE_GENERATORS = {
*/
model: () => agentSelectors.currentAgentModel(useAgentStore.getState()),
provider: () => agentSelectors.currentAgentModelProvider(useAgentStore.getState()),
+
+ /**
+ * Desktop app path-related template variables (only available in Electron)
+ *
+ * | Value | Example |
+ * |-------|---------|
+ * | `{{homePath}}` | /Users/username |
+ * | `{{desktopPath}}` | /Users/username/Desktop |
+ * | `{{documentsPath}}` | /Users/username/Documents |
+ * | `{{downloadsPath}}` | /Users/username/Downloads |
+ * | `{{musicPath}}` | /Users/username/Music |
+ * | `{{picturesPath}}` | /Users/username/Pictures |
+ * | `{{videosPath}}` | /Users/username/Videos |
+ * | `{{userDataPath}}` | /Users/username/Library/Application Support/LobeChat |
+ *
+ */
+ homePath: () => globalAgentContextManager.getContext().homePath ?? '',
+ desktopPath: () => globalAgentContextManager.getContext().desktopPath ?? '',
+ documentsPath: () => globalAgentContextManager.getContext().documentsPath ?? '',
+ downloadsPath: () => globalAgentContextManager.getContext().downloadsPath ?? '',
+ musicPath: () => globalAgentContextManager.getContext().musicPath ?? '',
+ picturesPath: () => globalAgentContextManager.getContext().picturesPath ?? '',
+ videosPath: () => globalAgentContextManager.getContext().videosPath ?? '',
+ userDataPath: () => globalAgentContextManager.getContext().userDataPath ?? '',
} as Record<string, () => string>;
/**
diff --git a/src/features/CommandMenu/components/CommandItem.tsx b/src/features/CommandMenu/components/CommandItem.tsx
index 1d17263e27b..5b2849a61f2 100644
--- a/src/features/CommandMenu/components/CommandItem.tsx
+++ b/src/features/CommandMenu/components/CommandItem.tsx
@@ -45,6 +45,7 @@ const CommandItem = memo<CommandItemProps>((props) => {
}
if (props.variant === 'detailed') {
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
const { icon, title, description, trailingLabel, unpinned: _unpinned, ...itemProps } = props;
return (
<Command.Item {...itemProps}>
@@ -61,6 +62,7 @@ const CommandItem = memo<CommandItemProps>((props) => {
}
// Simple variant (default)
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
const { icon, children, unpinned: _unpinned, ...itemProps } = props;
// Clone the icon element and add the icon className if it's a valid React element
diff --git a/src/features/CommandMenu/index.tsx b/src/features/CommandMenu/index.tsx
index 36ad3248a22..30c27a46938 100644
--- a/src/features/CommandMenu/index.tsx
+++ b/src/features/CommandMenu/index.tsx
@@ -24,17 +24,10 @@ import { useCommandMenu } from './useCommandMenu';
const CommandMenuContent = memo(() => {
const { t } = useTranslation('common');
const { styles } = useStyles();
- const {
- closeCommandMenu,
- handleBack,
- hasSearch,
- isSearching,
- searchQuery,
- searchResults,
- } = useCommandMenu();
-
- const { viewMode, setPages, page, pages, search, setTypeFilter, typeFilter } =
- useCommandMenuContext();
+ const { closeCommandMenu, handleBack, hasSearch, isSearching, searchQuery, searchResults } =
+ useCommandMenu();
+
+ const { setPages, page, pages, search, setTypeFilter, typeFilter } = useCommandMenuContext();
return (
<div className={styles.overlay} onClick={closeCommandMenu}>
diff --git a/src/features/Conversation/ChatList/index.tsx b/src/features/Conversation/ChatList/index.tsx
index c914465b3fb..9c01028e93c 100644
--- a/src/features/Conversation/ChatList/index.tsx
+++ b/src/features/Conversation/ChatList/index.tsx
@@ -2,6 +2,7 @@
import { type ReactNode, memo, useCallback } from 'react';
+import { useFetchTopicMemories } from '@/hooks/useFetchMemoryForTopic';
import { useFetchNotebookDocuments } from '@/hooks/useFetchNotebookDocuments';
import WideScreenContainer from '../../WideScreenContainer';
@@ -37,6 +38,7 @@ const ChatList = memo<ChatListProps>(({ welcome, itemContent }) => {
// Fetch notebook documents when topic is selected
useFetchNotebookDocuments(context.topicId!);
+ useFetchTopicMemories(context.topicId!);
// Use selectors for data
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Render/CustomRender.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Render/CustomRender.tsx
index 8fffb5868b2..8aeff0d873b 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Render/CustomRender.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Render/CustomRender.tsx
@@ -65,19 +65,6 @@ const CustomRender = memo<CustomRenderProps>(
// Show plugin custom UI if applicable
if (showPluginRender) {
- console.log(
- <PluginRender
- arguments={plugin?.arguments}
- content={content}
- identifier={plugin?.identifier}
- loading={false}
- messageId={messageId}
- payload={plugin}
- pluginState={pluginState}
- toolCallId={toolCallId}
- type={plugin?.type}
- />,
- );
return (
<Flexbox gap={12} id={toolCallId} width={'100%'}>
<PluginRender
diff --git a/src/hooks/useFetchMemoryForTopic.ts b/src/hooks/useFetchMemoryForTopic.ts
new file mode 100644
index 00000000000..9b0248b7f11
--- /dev/null
+++ b/src/hooks/useFetchMemoryForTopic.ts
@@ -0,0 +1,7 @@
+import { useUserMemoryStore } from '@/store/userMemory';
+
+export const useFetchTopicMemories = (topicId?: string) => {
+ const useFetchMemoriesForTopic = useUserMemoryStore((s) => s.useFetchMemoriesForTopic);
+
+ useFetchMemoriesForTopic(topicId);
+};
diff --git a/src/layout/AuthProvider/MarketAuth/MarketAuthConfirmModal.tsx b/src/layout/AuthProvider/MarketAuth/MarketAuthConfirmModal.tsx
index 7710b7c4e02..5a5352e11fa 100644
--- a/src/layout/AuthProvider/MarketAuth/MarketAuthConfirmModal.tsx
+++ b/src/layout/AuthProvider/MarketAuth/MarketAuthConfirmModal.tsx
@@ -55,6 +55,7 @@ const MarketAuthConfirmModal = memo<MarketAuthConfirmModalProps>(
paddings={{
desktop: 24,
}}
+ // size={440}
title={null}
width={440}
>
diff --git a/src/layout/GlobalProvider/StoreInitialization.tsx b/src/layout/GlobalProvider/StoreInitialization.tsx
index 82b657ea1c8..83d8c3bf1a3 100644
--- a/src/layout/GlobalProvider/StoreInitialization.tsx
+++ b/src/layout/GlobalProvider/StoreInitialization.tsx
@@ -16,6 +16,7 @@ import { useServerConfigStore } from '@/store/serverConfig';
import { serverConfigSelectors } from '@/store/serverConfig/selectors';
import { useUserStore } from '@/store/user';
import { authSelectors, onboardingSelectors } from '@/store/user/selectors';
+import { useUserMemoryStore } from '@/store/userMemory';
const StoreInitialization = memo(() => {
// prefetch error ns to avoid don't show error content correctly
@@ -34,6 +35,7 @@ const StoreInitialization = memo(() => {
const useInitBuiltinAgent = useAgentStore((s) => s.useInitBuiltinAgent);
const useInitAiProviderKeyVaults = useAiInfraStore((s) => s.useFetchAiProviderRuntimeState);
+ const useInitIdentities = useUserMemoryStore((s) => s.useInitIdentities);
// init the system preference
useInitSystemStatus();
@@ -65,6 +67,9 @@ const StoreInitialization = memo(() => {
// init user provider key vaults
useInitAiProviderKeyVaults(isLoginOnInit, isSyncActive);
+ // init user memory identities (for chat context injection)
+ useInitIdentities(isLoginOnInit);
+
// init user state
useInitUserState(isLoginOnInit, serverConfig, {
onSuccess: (state) => {
diff --git a/src/locales/default/plugin.ts b/src/locales/default/plugin.ts
index b42c7860cea..6e3076fab48 100644
--- a/src/locales/default/plugin.ts
+++ b/src/locales/default/plugin.ts
@@ -92,6 +92,14 @@ export default {
'builtins.lobe-page-agent.apiName.updateNode': '更新节点',
'builtins.lobe-page-agent.apiName.wrapNodes': '包装节点',
'builtins.lobe-page-agent.title': '文档',
+ 'builtins.lobe-user-memory.apiName.addContextMemory': '添加情境记忆',
+ 'builtins.lobe-user-memory.apiName.addExperienceMemory': '添加经验记忆',
+ 'builtins.lobe-user-memory.apiName.addIdentityMemory': '添加身份记忆',
+ 'builtins.lobe-user-memory.apiName.addPreferenceMemory': '添加偏好记忆',
+ 'builtins.lobe-user-memory.apiName.removeIdentityMemory': '删除身份记忆',
+ 'builtins.lobe-user-memory.apiName.searchUserMemory': '搜索记忆',
+ 'builtins.lobe-user-memory.apiName.updateIdentityMemory': '更新身份记忆',
+ 'builtins.lobe-user-memory.title': '记忆',
'builtins.lobe-web-browsing.apiName.crawlMultiPages': '读取多个页面内容',
'builtins.lobe-web-browsing.apiName.crawlSinglePage': '读取页面内容',
'builtins.lobe-web-browsing.apiName.search': '搜索页面',
diff --git a/src/server/routers/lambda/userMemories.ts b/src/server/routers/lambda/userMemories.ts
index 70e7ea1e6d1..8e335eed573 100644
--- a/src/server/routers/lambda/userMemories.ts
+++ b/src/server/routers/lambda/userMemories.ts
@@ -1,4 +1,5 @@
import {
+ DEFAULT_SEARCH_USER_MEMORY_TOP_K,
DEFAULT_USER_MEMORY_EMBEDDING_DIMENSIONS,
DEFAULT_USER_MEMORY_EMBEDDING_MODEL_ITEM,
} from '@lobechat/const';
@@ -10,6 +11,7 @@ import {
RemoveIdentityActionSchema,
UpdateIdentityActionSchema,
} from '@lobechat/memory-user-memory';
+import { LayersEnum, SearchMemoryResult, searchMemorySchema } from '@lobechat/types';
import { type SQL, and, asc, eq, gte, lte } from 'drizzle-orm';
import { ModelProvider } from 'model-bank';
import pMap from 'p-map';
@@ -18,8 +20,10 @@ import { z } from 'zod';
import {
IdentityEntryBasePayload,
IdentityEntryPayload,
+ UserMemoryIdentityModel,
UserMemoryModel,
} from '@/database/models/userMemory';
+import { UserMemoryTopicRepository } from '@/database/repositories/userMemory';
import {
userMemories,
userMemoriesContexts,
@@ -32,8 +36,6 @@ import { keyVaults, serverDatabase } from '@/libs/trpc/lambda/middleware';
import { getServerDefaultFilesConfig } from '@/server/globalConfig';
import { initModelRuntimeWithUserPayload } from '@/server/modules/ModelRuntime';
import { ClientSecretPayload } from '@/types/auth';
-import { SearchMemoryResult, searchMemorySchema } from '@/types/userMemory';
-import { LayersEnum } from '@/types/userMemory/shared';
const EMPTY_SEARCH_RESULT: SearchMemoryResult = {
contexts: [],
@@ -215,6 +217,19 @@ export const userMemoriesRouter = router({
}
}),
+ queryIdentitiesForInjection: authedProcedure
+ .use(serverDatabase)
+ .input(z.object({ limit: z.coerce.number().int().min(1).max(100).optional() }).optional())
+ .query(async ({ ctx, input }) => {
+ try {
+ const identityModel = new UserMemoryIdentityModel(ctx.serverDB, ctx.userId);
+ return await identityModel.queryForInjection(input?.limit ?? 50);
+ } catch (error) {
+ console.error('Failed to query identities for injection:', error);
+ return [];
+ }
+ }),
+
queryIdentityRoles: memoryProcedure
.input(
z
@@ -679,6 +694,37 @@ export const userMemoriesRouter = router({
}
}),
+ /**
+ * Retrieve memories for a specific topic
+ * Uses concatenated user messages (first 7000 chars) as the search query
+ */
+ retrieveMemoryForTopic: memoryProcedure
+ .input(z.object({ topicId: z.string() }))
+ .query(async ({ ctx, input }) => {
+ try {
+ // Get concatenated user messages for this topic
+ const userMemoryTopicRepo = new UserMemoryTopicRepository(ctx.serverDB, ctx.userId);
+ const query = await userMemoryTopicRepo.getUserMessagesQueryForTopic(input.topicId);
+
+ if (!query) {
+ // No user messages available, return empty result
+ return EMPTY_SEARCH_RESULT;
+ }
+
+ // Search memories using concatenated user messages
+ const searchParams = {
+ query,
+ topK: DEFAULT_SEARCH_USER_MEMORY_TOP_K,
+ };
+
+ const result = await searchUserMemories(ctx, searchParams);
+ return result;
+ } catch (error) {
+ console.error('Failed to retrieve memory for topic:', error);
+ return EMPTY_SEARCH_RESULT;
+ }
+ }),
+
searchMemory: memoryProcedure.input(searchMemorySchema).query(async ({ input, ctx }) => {
try {
return await searchUserMemories(ctx, input);
diff --git a/src/services/chat/index.ts b/src/services/chat/index.ts
index f0fb7f60ac4..25a23232620 100644
--- a/src/services/chat/index.ts
+++ b/src/services/chat/index.ts
@@ -48,7 +48,6 @@ import {
initializeWithClientStore,
resolveAgentConfig,
resolveModelExtendParams,
- resolveUserMemories,
} from './mecha';
import { FetchOptions } from './types';
@@ -131,14 +130,7 @@ class ChatService {
// =================== 1.1 process user memories =================== //
- const isMemoryPluginEnabled =
- pluginIds.includes(MemoryManifest.identifier) ||
- enabledToolIds.includes(MemoryManifest.identifier);
-
- const userMemories = await resolveUserMemories({
- isMemoryPluginEnabled,
- messages,
- });
+ const isMemoryPluginEnabled = enabledToolIds.includes(MemoryManifest.identifier);
// =================== 1.2 build agent builder context =================== //
@@ -213,6 +205,7 @@ class ChatService {
agentId: targetAgentId,
enableHistoryCount:
chatConfigByIdSelectors.getEnableHistoryCountById(targetAgentId)(getAgentStoreState()),
+ enableUserMemories: isMemoryPluginEnabled,
groupId,
historyCount:
chatConfigByIdSelectors.getHistoryCountById(targetAgentId)(getAgentStoreState()) + 2,
@@ -223,7 +216,6 @@ class ChatService {
sessionId: options?.trace?.sessionId,
systemRole: agentConfig.systemRole,
tools: enabledToolIds,
- userMemories,
});
// ============ 3. process extend params ============ //
diff --git a/src/services/chat/mecha/contextEngineering.test.ts b/src/services/chat/mecha/contextEngineering.test.ts
index 21ac30dcbb8..8b4d484e5d8 100644
--- a/src/services/chat/mecha/contextEngineering.test.ts
+++ b/src/services/chat/mecha/contextEngineering.test.ts
@@ -5,7 +5,7 @@ import * as isCanUseFCModule from '@/helpers/isCanUseFC';
import * as helpers from '../helper';
import { contextEngineering } from './contextEngineering';
-import type { UserMemoriesResult } from './memoryManager';
+import * as memoryManager from './memoryManager';
// Mock VARIABLE_GENERATORS
vi.mock('@/utils/client/parserPlaceholder', () => ({
@@ -448,46 +448,47 @@ describe('contextEngineering', () => {
},
];
- const userMemories: UserMemoriesResult = {
- fetchedAt: Date.now(),
- memories: {
- contexts: [
- {
- accessedAt: new Date('2024-01-01T00:00:00.000Z'),
- associatedObjects: [],
- associatedSubjects: [],
- createdAt: new Date('2024-01-01T00:00:00.000Z'),
- currentStatus: 'active',
- description: 'Weekly syncs for LobeHub',
- id: 'ctx-1',
- metadata: {},
- scoreImpact: 0.8,
- scoreUrgency: 0.5,
- tags: ['project'],
- title: 'LobeHub',
- type: 'project',
- updatedAt: new Date('2024-01-02T00:00:00.000Z'),
- userMemoryIds: ['mem-1'],
- },
- ],
- experiences: [],
- preferences: [],
- },
- };
+ // Mock topic memories and global identities separately
+ vi.spyOn(memoryManager, 'resolveTopicMemories').mockResolvedValue({
+ contexts: [
+ {
+ accessedAt: new Date('2024-01-01T00:00:00.000Z'),
+ associatedObjects: [],
+ associatedSubjects: [],
+ createdAt: new Date('2024-01-01T00:00:00.000Z'),
+ currentStatus: 'active',
+ description: 'Weekly syncs for LobeHub',
+ id: 'ctx-1',
+ metadata: {},
+ scoreImpact: 0.8,
+ scoreUrgency: 0.5,
+ tags: ['project'],
+ title: 'LobeHub',
+ type: 'project',
+ updatedAt: new Date('2024-01-02T00:00:00.000Z'),
+ userMemoryIds: ['mem-1'],
+ },
+ ],
+ experiences: [],
+ preferences: [],
+ });
+ vi.spyOn(memoryManager, 'resolveGlobalIdentities').mockReturnValue([]);
const result = await contextEngineering({
- userMemories,
+ enableUserMemories: true,
messages,
model: 'gpt-4',
provider: 'openai',
});
expect(result[0].role).toBe('system');
+ // Check the memory context is injected (memory_fetched_at is optional now)
+ expect(result[0].content).toContain('<user_memories');
+ expect(result[0].content).toContain('contexts="1"');
+ expect(result[0].content).toContain('experiences="0"');
+ expect(result[0].content).toContain('preferences="0"');
expect(result[0].content).toContain(
- '<user_memories contexts="1" experiences="0" memory_fetched_at="',
- );
- expect(result[0].content).toContain(
- '" preferences="0"><user_memories_context id="ctx-1"><context_title>LobeHub</context_title><context_description>Weekly syncs for LobeHub</context_description></user_memories_context></user_memories>',
+ '<user_memories_context id="ctx-1"><context_title>LobeHub</context_title><context_description>Weekly syncs for LobeHub</context_description></user_memories_context>',
);
expect(result[0].content).toContain('<context_title>LobeHub</context_title>');
expect(result[1].content).toBe(
diff --git a/src/services/chat/mecha/contextEngineering.ts b/src/services/chat/mecha/contextEngineering.ts
index 4579eecea6b..dacc10c5380 100644
--- a/src/services/chat/mecha/contextEngineering.ts
+++ b/src/services/chat/mecha/contextEngineering.ts
@@ -23,7 +23,11 @@ import { getToolStoreState } from '@/store/tool';
import { builtinToolSelectors, klavisStoreSelectors, toolSelectors } from '@/store/tool/selectors';
import { isCanUseVideo, isCanUseVision } from '../helper';
-import type { UserMemoriesResult } from './memoryManager';
+import {
+ combineUserMemoryData,
+ resolveGlobalIdentities,
+ resolveTopicMemories,
+} from './memoryManager';
const log = debug('context-engine:contextEngineering');
@@ -33,6 +37,7 @@ interface ContextEngineeringContext {
/** The agent ID that will respond (for group context injection) */
agentId?: string;
enableHistoryCount?: boolean;
+ enableUserMemories?: boolean;
/** Group ID for multi-agent scenarios */
groupId?: string;
historyCount?: number;
@@ -44,7 +49,6 @@ interface ContextEngineeringContext {
sessionId?: string;
systemRole?: string;
tools?: string[];
- userMemories?: UserMemoriesResult;
}
// REVIEW:可能这里可以约束一下 identity,preference,exp 的 重新排序或者裁切过的上下文进来而不是全部丢进来
@@ -55,7 +59,7 @@ export const contextEngineering = async ({
provider,
systemRole,
inputTemplate,
- userMemories,
+ enableUserMemories,
enableHistoryCount,
historyCount,
historySummary,
@@ -220,6 +224,16 @@ export const contextEngineering = async ({
.filter((kb) => kb.enabled)
.map((kb) => ({ description: kb.description, id: kb.id, name: kb.name }));
+ // Resolve user memories: topic memories and global identities are independent layers
+ let userMemoryData;
+ if (enableUserMemories) {
+ const [topicMemories, globalIdentities] = await Promise.all([
+ resolveTopicMemories(),
+ Promise.resolve(resolveGlobalIdentities()),
+ ]);
+ userMemoryData = combineUserMemoryData(topicMemories, globalIdentities);
+ }
+
// Create MessagesEngine with injected dependencies
/* eslint-disable sort-keys-fix/sort-keys-fix */
const engine = new MessagesEngine({
@@ -261,13 +275,13 @@ export const contextEngineering = async ({
},
// User memory configuration
- userMemory: userMemories
- ? {
- enabled: !!userMemories.memories,
- fetchedAt: userMemories.fetchedAt,
- memories: userMemories.memories,
- }
- : undefined,
+ userMemory:
+ enableUserMemories && userMemoryData
+ ? {
+ enabled: true,
+ memories: userMemoryData,
+ }
+ : undefined,
// Variable generators
variableGenerators: VARIABLE_GENERATORS,
diff --git a/src/services/chat/mecha/index.ts b/src/services/chat/mecha/index.ts
index 74cf1b6ecb1..90b67015a5e 100644
--- a/src/services/chat/mecha/index.ts
+++ b/src/services/chat/mecha/index.ts
@@ -21,5 +21,9 @@ export type { ModelExtendParams, ModelParamsContext } from './modelParamsResolve
export { resolveModelExtendParams } from './modelParamsResolver';
// Memory management
-export type { MemoryResolverContext, UserMemoriesResult } from './memoryManager';
-export { resolveUserMemories } from './memoryManager';
+export type { TopicMemoryResolverContext } from './memoryManager';
+export {
+ combineUserMemoryData,
+ resolveGlobalIdentities,
+ resolveTopicMemories,
+} from './memoryManager';
diff --git a/src/services/chat/mecha/memoryManager.ts b/src/services/chat/mecha/memoryManager.ts
index 799df6d6fde..b61c49acfaf 100644
--- a/src/services/chat/mecha/memoryManager.ts
+++ b/src/services/chat/mecha/memoryManager.ts
@@ -1,128 +1,105 @@
-import { UIChatMessage } from '@lobechat/types';
+import type { UserMemoryData, UserMemoryIdentityItem } from '@lobechat/context-engine';
import type { RetrieveMemoryResult } from '@lobechat/types';
+import { mutate } from '@/libs/swr';
import { userMemoryService } from '@/services/userMemory';
import { getChatStoreState } from '@/store/chat';
-import { topicSelectors } from '@/store/chat/selectors';
-import { getSessionStoreState } from '@/store/session';
-import { sessionSelectors } from '@/store/session/selectors';
-import {
- getUserMemoryStoreState,
- useUserMemoryStore,
- userMemorySelectors,
-} from '@/store/userMemory';
-import { userMemoryCacheKey } from '@/store/userMemory/utils/cacheKey';
-import { createMemorySearchParams } from '@/store/userMemory/utils/searchParams';
+import { getUserMemoryStoreState, useUserMemoryStore } from '@/store/userMemory';
+import { agentMemorySelectors, identitySelectors } from '@/store/userMemory/selectors';
+
+const EMPTY_MEMORIES: RetrieveMemoryResult = {
+ contexts: [],
+ experiences: [],
+ preferences: [],
+};
/**
- * User memories with fetch metadata
+ * Resolves global identities from user memory store
+ * Returns identities that apply across all topics
*/
-export interface UserMemoriesResult {
- fetchedAt: number;
- memories: RetrieveMemoryResult;
-}
+export const resolveGlobalIdentities = (): UserMemoryIdentityItem[] => {
+ const memoryState = getUserMemoryStoreState();
+ const globalIdentities = identitySelectors.globalIdentities(memoryState);
+
+ return globalIdentities.map((identity) => ({
+ capturedAt: identity.capturedAt,
+ description: identity.description,
+ id: identity.id,
+ role: identity.role,
+ type: identity.type,
+ }));
+};
/**
- * Context for resolving user memories
+ * Context for resolving topic memories
*/
-export interface MemoryResolverContext {
- /** Whether memory plugin is enabled */
- isMemoryPluginEnabled: boolean;
- /** Chat messages for context extraction */
- messages: UIChatMessage[];
+export interface TopicMemoryResolverContext {
+ /** Topic ID to retrieve memories for (optional, will use active topic if not provided) */
+ topicId?: string;
}
-const EMPTY_MEMORIES: RetrieveMemoryResult = {
- contexts: [],
- experiences: [],
- preferences: [],
-};
-
/**
- * Resolves user memories for context injection
+ * Resolves topic-based memories (contexts, experiences, preferences)
*
* This function handles:
- * 1. Checking if memories are already cached
- * 2. Building memory context from messages and session
+ * 1. Getting the topic ID from context or active topic
+ * 2. Checking if memories are already cached for the topic
* 3. Fetching memories from the service if not cached
- * 4. Caching the fetched memories for future use
+ * 4. Caching the fetched memories by topic ID
*/
-export const resolveUserMemories = async (
- ctx: MemoryResolverContext,
-): Promise<UserMemoriesResult | undefined> => {
- const { isMemoryPluginEnabled, messages } = ctx;
-
- // Check if already have cached memories
- let userMemories =
- userMemorySelectors.activeUserMemories(isMemoryPluginEnabled)(getUserMemoryStoreState());
-
- if (userMemories) {
- return userMemories;
- }
-
- // If memory plugin not enabled, return undefined
- if (!isMemoryPluginEnabled) {
- return undefined;
+export const resolveTopicMemories = async (
+ ctx?: TopicMemoryResolverContext,
+): Promise<RetrieveMemoryResult> => {
+ // Get topic ID from context or active topic
+ const topicId = ctx?.topicId ?? getChatStoreState().activeTopicId;
+
+ // If no topic ID, return empty memories
+ if (!topicId) {
+ return EMPTY_MEMORIES;
}
- // Build memory context from messages and session
- const chatStoreState = getChatStoreState();
- const sessionStoreState = getSessionStoreState();
-
- const historyMessages = messages.slice(0, -1);
- const latestHistoryMessage = [...historyMessages]
- .reverse()
- .find((item) => typeof item?.content === 'string' && item.content.trim().length > 0);
- const pendingMessage = messages.at(-1);
-
- const memoryContext = {
- latestMessageContent: latestHistoryMessage?.content,
- pendingMessageContent: pendingMessage?.content,
- session: sessionSelectors.currentSession(sessionStoreState),
- topic: topicSelectors.currentActiveTopic(chatStoreState),
- };
-
- // Set active memory context in store
- useUserMemoryStore.getState().setActiveMemoryContext(memoryContext);
-
- const updatedMemoryState = getUserMemoryStoreState();
- const memoryParams = updatedMemoryState.activeParams ?? createMemorySearchParams(memoryContext);
-
- if (!memoryParams) {
- return undefined;
- }
+ const userMemoryStoreState = getUserMemoryStoreState();
- const key = userMemoryCacheKey(memoryParams);
- const cachedMemories = updatedMemoryState.memoryMap[key];
+ // Check if already have cached memories for this topic
+ const cachedMemories = agentMemorySelectors.topicMemories(topicId)(userMemoryStoreState);
- // Return cached memories if available
if (cachedMemories) {
- const cachedAt = updatedMemoryState.memoryFetchedAtMap[key] ?? Date.now();
- return {
- fetchedAt: cachedAt,
- memories: cachedMemories,
- };
+ return cachedMemories;
}
- // Fetch memories from service
- const result = await userMemoryService.retrieveMemory(memoryParams);
- const memories = result ?? EMPTY_MEMORIES;
- const fetchedAt = Date.now();
-
- // Cache the fetched memories
- useUserMemoryStore.setState((state) => ({
- memoryFetchedAtMap: {
- ...state.memoryFetchedAtMap,
- [key]: fetchedAt,
- },
- memoryMap: {
- ...state.memoryMap,
- [key]: memories,
- },
- }));
-
- return {
- fetchedAt,
- memories,
- };
+ // Fetch memories for this topic
+ try {
+ const result = await userMemoryService.retrieveMemoryForTopic(topicId);
+ const memories = result ?? EMPTY_MEMORIES;
+
+ // Cache the fetched memories by topic ID
+ useUserMemoryStore.setState((state) => ({
+ topicMemoriesMap: {
+ ...state.topicMemoriesMap,
+ [topicId]: memories,
+ },
+ }));
+
+ // Also trigger SWR mutate to keep in sync
+ await mutate(['useFetchMemoriesForTopic', topicId]);
+
+ return memories;
+ } catch (error) {
+ console.error('Failed to retrieve memories for topic:', error);
+ return EMPTY_MEMORIES;
+ }
};
+
+/**
+ * Combines topic memories and global identities into UserMemoryData
+ * This is a utility for assembling the final memory data structure
+ */
+export const combineUserMemoryData = (
+ topicMemories: RetrieveMemoryResult,
+ identities: UserMemoryIdentityItem[],
+): UserMemoryData => ({
+ contexts: topicMemories.contexts,
+ experiences: topicMemories.experiences,
+ identities,
+ preferences: topicMemories.preferences,
+});
diff --git a/src/services/userMemory.ts b/src/services/userMemory.ts
deleted file mode 100644
index 311c5de8c87..00000000000
--- a/src/services/userMemory.ts
+++ /dev/null
@@ -1,97 +0,0 @@
-import type {
- AddIdentityActionSchema,
- ContextMemoryItemSchema,
- ExperienceMemoryItemSchema,
- PreferenceMemoryItemSchema,
- RemoveIdentityActionSchema,
- UpdateIdentityActionSchema,
-} from '@lobechat/memory-user-memory/schemas';
-import { z } from 'zod';
-
-import { lambdaClient } from '@/libs/trpc/client';
-import {
- AddContextMemoryResult,
- AddExperienceMemoryResult,
- AddIdentityMemoryResult,
- AddPreferenceMemoryResult,
- LayersEnum,
- RemoveIdentityMemoryResult,
- SearchMemoryParams,
- SearchMemoryResult,
- TypesEnum,
- UpdateIdentityMemoryResult,
-} from '@/types/userMemory';
-
-class UserMemoryService {
- addContextMemory = async (
- params: z.infer<typeof ContextMemoryItemSchema>,
- ): Promise<AddContextMemoryResult> => {
- return lambdaClient.userMemories.toolAddContextMemory.mutate(params);
- };
-
- addExperienceMemory = async (
- params: z.infer<typeof ExperienceMemoryItemSchema>,
- ): Promise<AddExperienceMemoryResult> => {
- return lambdaClient.userMemories.toolAddExperienceMemory.mutate(params);
- };
-
- addIdentityMemory = async (
- params: z.infer<typeof AddIdentityActionSchema>,
- ): Promise<AddIdentityMemoryResult> => {
- return lambdaClient.userMemories.toolAddIdentityMemory.mutate(params);
- };
-
- addPreferenceMemory = async (
- params: z.infer<typeof PreferenceMemoryItemSchema>,
- ): Promise<AddPreferenceMemoryResult> => {
- return lambdaClient.userMemories.toolAddPreferenceMemory.mutate(params);
- };
-
- removeIdentityMemory = async (
- params: z.infer<typeof RemoveIdentityActionSchema>,
- ): Promise<RemoveIdentityMemoryResult> => {
- return lambdaClient.userMemories.toolRemoveIdentityMemory.mutate(params);
- };
-
- getMemoryDetail = async (params: { id: string; layer: LayersEnum }) => {
- return lambdaClient.userMemories.getMemoryDetail.query(params);
- };
-
- retrieveMemory = async (params: SearchMemoryParams): Promise<SearchMemoryResult> => {
- return lambdaClient.userMemories.toolSearchMemory.query(params);
- };
-
- searchMemory = async (params: SearchMemoryParams): Promise<SearchMemoryResult> => {
- return lambdaClient.userMemories.toolSearchMemory.query(params);
- };
-
- queryTags = async (params?: { layers?: LayersEnum[]; page?: number; size?: number }) => {
- return lambdaClient.userMemories.queryTags.query(params);
- };
-
- queryIdentityRoles = async (params?: { page?: number; size?: number }) => {
- return lambdaClient.userMemories.queryIdentityRoles.query(params);
- };
-
- queryMemories = async (params?: {
- categories?: string[];
- layer?: LayersEnum;
- order?: 'asc' | 'desc';
- page?: number;
- pageSize?: number;
- q?: string;
- sort?: 'scoreConfidence' | 'scoreImpact' | 'scorePriority' | 'scoreUrgency';
- tags?: string[];
- types?: TypesEnum[];
- }) => {
- return lambdaClient.userMemories.queryMemories.query(params);
- };
-
- updateIdentityMemory = async (
- params: z.infer<typeof UpdateIdentityActionSchema>,
- ): Promise<UpdateIdentityMemoryResult> => {
- return lambdaClient.userMemories.toolUpdateIdentityMemory.mutate(params);
- };
-}
-
-export const userMemoryService = new UserMemoryService();
diff --git a/src/services/userMemory/crud.ts b/src/services/userMemory/crud.ts
new file mode 100644
index 00000000000..aa4f5fe49c9
--- /dev/null
+++ b/src/services/userMemory/crud.ts
@@ -0,0 +1,76 @@
+import { NewUserMemoryIdentity } from '@lobechat/types';
+
+import { lambdaClient } from '@/libs/trpc/client';
+
+class MemoryCRUDService {
+ // ============ Identity CRUD ============
+
+ createIdentity = async (data: NewUserMemoryIdentity) => {
+ return lambdaClient.userMemory.createIdentity.mutate(data);
+ };
+
+ deleteIdentity = async (id: string) => {
+ return lambdaClient.userMemory.deleteIdentity.mutate({ id });
+ };
+
+ getIdentities = async () => {
+ return lambdaClient.userMemory.getIdentities.query();
+ };
+
+ updateIdentity = async (id: string, data: Partial<NewUserMemoryIdentity>) => {
+ return lambdaClient.userMemory.updateIdentity.mutate({ data, id });
+ };
+
+ // ============ Context CRUD ============
+
+ deleteContext = async (id: string) => {
+ return lambdaClient.userMemory.deleteContext.mutate({ id });
+ };
+
+ getContexts = async () => {
+ return lambdaClient.userMemory.getContexts.query();
+ };
+
+ updateContext = async (
+ id: string,
+ data: { currentStatus?: string; description?: string; title?: string },
+ ) => {
+ return lambdaClient.userMemory.updateContext.mutate({ data, id });
+ };
+
+ // ============ Experience CRUD ============
+
+ deleteExperience = async (id: string) => {
+ return lambdaClient.userMemory.deleteExperience.mutate({ id });
+ };
+
+ getExperiences = async () => {
+ return lambdaClient.userMemory.getExperiences.query();
+ };
+
+ updateExperience = async (
+ id: string,
+ data: { action?: string; keyLearning?: string; situation?: string },
+ ) => {
+ return lambdaClient.userMemory.updateExperience.mutate({ data, id });
+ };
+
+ // ============ Preference CRUD ============
+
+ deletePreference = async (id: string) => {
+ return lambdaClient.userMemory.deletePreference.mutate({ id });
+ };
+
+ getPreferences = async () => {
+ return lambdaClient.userMemory.getPreferences.query();
+ };
+
+ updatePreference = async (
+ id: string,
+ data: { conclusionDirectives?: string; suggestions?: string },
+ ) => {
+ return lambdaClient.userMemory.updatePreference.mutate({ data, id });
+ };
+}
+
+export const memoryCRUDService = new MemoryCRUDService();
diff --git a/src/services/userMemory/index.ts b/src/services/userMemory/index.ts
index e8a893c39ea..1bd0e26c55c 100644
--- a/src/services/userMemory/index.ts
+++ b/src/services/userMemory/index.ts
@@ -1,79 +1,114 @@
-import { NewUserMemoryIdentity } from '@lobechat/types';
+import type {
+ AddIdentityActionSchema,
+ ContextMemoryItemSchema,
+ ExperienceMemoryItemSchema,
+ PreferenceMemoryItemSchema,
+ RemoveIdentityActionSchema,
+ UpdateIdentityActionSchema,
+} from '@lobechat/memory-user-memory/schemas';
+import {
+ AddContextMemoryResult,
+ AddExperienceMemoryResult,
+ AddIdentityMemoryResult,
+ AddPreferenceMemoryResult,
+ LayersEnum,
+ RemoveIdentityMemoryResult,
+ SearchMemoryParams,
+ SearchMemoryResult,
+ TypesEnum,
+ UpdateIdentityMemoryResult,
+} from '@lobechat/types';
+import { z } from 'zod';
import { lambdaClient } from '@/libs/trpc/client';
-class MemoryCRUDService {
- // ============ Identity CRUD ============
-
- createIdentity = async (data: NewUserMemoryIdentity) => {
- return lambdaClient.userMemory.createIdentity.mutate(data);
+class UserMemoryService {
+ addContextMemory = async (
+ params: z.infer<typeof ContextMemoryItemSchema>,
+ ): Promise<AddContextMemoryResult> => {
+ return lambdaClient.userMemories.toolAddContextMemory.mutate(params);
};
- deleteIdentity = async (id: string) => {
- return lambdaClient.userMemory.deleteIdentity.mutate({ id });
+ addExperienceMemory = async (
+ params: z.infer<typeof ExperienceMemoryItemSchema>,
+ ): Promise<AddExperienceMemoryResult> => {
+ return lambdaClient.userMemories.toolAddExperienceMemory.mutate(params);
};
- getIdentities = async () => {
- return lambdaClient.userMemory.getIdentities.query();
+ addIdentityMemory = async (
+ params: z.infer<typeof AddIdentityActionSchema>,
+ ): Promise<AddIdentityMemoryResult> => {
+ return lambdaClient.userMemories.toolAddIdentityMemory.mutate(params);
};
- updateIdentity = async (id: string, data: Partial<NewUserMemoryIdentity>) => {
- return lambdaClient.userMemory.updateIdentity.mutate({ data, id });
+ addPreferenceMemory = async (
+ params: z.infer<typeof PreferenceMemoryItemSchema>,
+ ): Promise<AddPreferenceMemoryResult> => {
+ return lambdaClient.userMemories.toolAddPreferenceMemory.mutate(params);
};
- // ============ Context CRUD ============
-
- deleteContext = async (id: string) => {
- return lambdaClient.userMemory.deleteContext.mutate({ id });
+ removeIdentityMemory = async (
+ params: z.infer<typeof RemoveIdentityActionSchema>,
+ ): Promise<RemoveIdentityMemoryResult> => {
+ return lambdaClient.userMemories.toolRemoveIdentityMemory.mutate(params);
};
- getContexts = async () => {
- return lambdaClient.userMemory.getContexts.query();
+ getMemoryDetail = async (params: { id: string; layer: LayersEnum }) => {
+ return lambdaClient.userMemories.getMemoryDetail.query(params);
};
- updateContext = async (
- id: string,
- data: { currentStatus?: string; description?: string; title?: string },
- ) => {
- return lambdaClient.userMemory.updateContext.mutate({ data, id });
+ retrieveMemory = async (params: SearchMemoryParams): Promise<SearchMemoryResult> => {
+ return lambdaClient.userMemories.toolSearchMemory.query(params);
};
- // ============ Experience CRUD ============
-
- deleteExperience = async (id: string) => {
- return lambdaClient.userMemory.deleteExperience.mutate({ id });
+ /**
+ * Retrieve memories for a specific topic
+ * Uses the topic's historySummary as the search query
+ */
+ retrieveMemoryForTopic = async (topicId: string): Promise<SearchMemoryResult> => {
+ return lambdaClient.userMemories.retrieveMemoryForTopic.query({ topicId });
};
- getExperiences = async () => {
- return lambdaClient.userMemory.getExperiences.query();
+ searchMemory = async (params: SearchMemoryParams): Promise<SearchMemoryResult> => {
+ return lambdaClient.userMemories.toolSearchMemory.query(params);
};
- updateExperience = async (
- id: string,
- data: { action?: string; keyLearning?: string; situation?: string },
- ) => {
- return lambdaClient.userMemory.updateExperience.mutate({ data, id });
+ queryTags = async (params?: { layers?: LayersEnum[]; page?: number; size?: number }) => {
+ return lambdaClient.userMemories.queryTags.query(params);
};
- // ============ Preference CRUD ============
+ queryIdentityRoles = async (params?: { page?: number; size?: number }) => {
+ return lambdaClient.userMemories.queryIdentityRoles.query(params);
+ };
- deletePreference = async (id: string) => {
- return lambdaClient.userMemory.deletePreference.mutate({ id });
+ /**
+ * Query identities for chat context injection
+ * Only returns user's own identities (relationship === 'self' or null)
+ */
+ queryIdentitiesForInjection = async (params?: { limit?: number }) => {
+ return lambdaClient.userMemories.queryIdentitiesForInjection.query(params);
};
- getPreferences = async () => {
- return lambdaClient.userMemory.getPreferences.query();
+ queryMemories = async (params?: {
+ categories?: string[];
+ layer?: LayersEnum;
+ order?: 'asc' | 'desc';
+ page?: number;
+ pageSize?: number;
+ q?: string;
+ sort?: 'scoreConfidence' | 'scoreImpact' | 'scorePriority' | 'scoreUrgency';
+ tags?: string[];
+ types?: TypesEnum[];
+ }) => {
+ return lambdaClient.userMemories.queryMemories.query(params);
};
- updatePreference = async (
- id: string,
- data: { conclusionDirectives?: string; suggestions?: string },
- ) => {
- return lambdaClient.userMemory.updatePreference.mutate({ data, id });
+ updateIdentityMemory = async (
+ params: z.infer<typeof UpdateIdentityActionSchema>,
+ ): Promise<UpdateIdentityMemoryResult> => {
+ return lambdaClient.userMemories.toolUpdateIdentityMemory.mutate(params);
};
}
-export const memoryCRUDService = new MemoryCRUDService();
-
-// Backward compatibility alias
-export const memoryService = memoryCRUDService;
+export const userMemoryService = new UserMemoryService();
+export { memoryCRUDService } from './crud';
diff --git a/src/store/tool/selectors/tool.ts b/src/store/tool/selectors/tool.ts
index 308a3c20e28..d920bfd940f 100644
--- a/src/store/tool/selectors/tool.ts
+++ b/src/store/tool/selectors/tool.ts
@@ -5,8 +5,6 @@ import { LobeChatPluginManifest } from '@lobehub/chat-plugin-sdk';
import { MetaData } from '@/types/meta';
import { LobeToolMeta } from '@/types/tool/tool';
-import { globalAgentContextManager } from '@/utils/client/GlobalAgentContextManager';
-import { hydrationPrompt } from '@/utils/promptTemplate';
import { pluginHelpers } from '../helpers';
import { ToolStoreState } from '../initialState';
@@ -27,14 +25,6 @@ const enabledSystemRoles =
const meta = manifest.meta || {};
const title = pluginHelpers.getPluginTitle(meta) || manifest.identifier;
- let systemRole = manifest.systemRole || pluginHelpers.getPluginDesc(meta);
-
- // Use the global context manager to fill the template
- if (systemRole) {
- const context = globalAgentContextManager.getContext();
-
- systemRole = hydrationPrompt(systemRole, context);
- }
return {
apis: manifest.api.map((m) => ({
@@ -43,7 +33,7 @@ const enabledSystemRoles =
})),
identifier: manifest.identifier,
name: title,
- systemRole,
+ systemRole: manifest.systemRole,
};
});
diff --git a/src/store/user/slices/auth/selectors.ts b/src/store/user/slices/auth/selectors.ts
index 23131f15443..812651a1a10 100644
--- a/src/store/user/slices/auth/selectors.ts
+++ b/src/store/user/slices/auth/selectors.ts
@@ -26,6 +26,7 @@ const username = (s: UserStore) => {
if (isDesktop) {
return s.user?.username;
}
+
return DEFAULT_USERNAME;
}
@@ -35,7 +36,7 @@ const username = (s: UserStore) => {
};
export const userProfileSelectors = {
- displayUserName: (s: UserStore): string => username(s) || s.user?.email || '',
+ displayUserName: (s: UserStore): string => s.user?.fullName || username(s) || s.user?.email || '',
email: (s: UserStore): string => s.user?.email || '',
fullName: (s: UserStore): string => s.user?.fullName || '',
interests: (s: UserStore): string[] => s.user?.interests || [],
diff --git a/src/store/userMemory/initialState.ts b/src/store/userMemory/initialState.ts
index 9f3674fe8c1..d6a1b869c99 100644
--- a/src/store/userMemory/initialState.ts
+++ b/src/store/userMemory/initialState.ts
@@ -1,12 +1,15 @@
+import type { RetrieveMemoryParams, RetrieveMemoryResult } from '@lobechat/types';
+
import {
DisplayContextMemory,
DisplayExperienceMemory,
- DisplayIdentityMemory,
DisplayPreferenceMemory,
} from '@/database/repositories/userMemory';
-import type { RetrieveMemoryParams, RetrieveMemoryResult, TypesEnum } from '@/types/userMemory';
-export interface UserMemoryStoreState {
+import { type AgentMemorySliceState, agentMemoryInitialState } from './slices/agent';
+import { type IdentitySliceState, identityInitialState } from './slices/identity';
+
+export interface UserMemoryStoreState extends AgentMemorySliceState, IdentitySliceState {
activeParams?: RetrieveMemoryParams;
activeParamsKey?: string;
contexts: DisplayContextMemory[];
@@ -28,14 +31,6 @@ export interface UserMemoryStoreState {
experiencesSearchLoading?: boolean;
experiencesSort?: 'scoreConfidence';
experiencesTotal: number;
- identities: DisplayIdentityMemory[];
- identitiesHasMore: boolean;
- identitiesInit: boolean;
- identitiesPage: number;
- identitiesQuery?: string;
- identitiesSearchLoading?: boolean;
- identitiesTotal: number;
- identitiesTypes?: TypesEnum[];
memoryFetchedAtMap: Record<string, number>;
memoryMap: Record<string, RetrieveMemoryResult>;
preferences: DisplayPreferenceMemory[];
@@ -52,6 +47,8 @@ export interface UserMemoryStoreState {
}
export const initialState: UserMemoryStoreState = {
+ ...agentMemoryInitialState,
+ ...identityInitialState,
activeParams: undefined,
activeParamsKey: undefined,
contexts: [],
@@ -71,13 +68,6 @@ export const initialState: UserMemoryStoreState = {
experiencesQuery: undefined,
experiencesSort: undefined,
experiencesTotal: 0,
- identities: [],
- identitiesHasMore: true,
- identitiesInit: false,
- identitiesPage: 1,
- identitiesQuery: undefined,
- identitiesTotal: 0,
- identitiesTypes: undefined,
memoryFetchedAtMap: {},
memoryMap: {},
preferences: [],
diff --git a/src/store/userMemory/selectors.ts b/src/store/userMemory/selectors.ts
index 7865d2d6576..9e875962d45 100644
--- a/src/store/userMemory/selectors.ts
+++ b/src/store/userMemory/selectors.ts
@@ -1,4 +1,4 @@
-import type { RetrieveMemoryParams, RetrieveMemoryResult } from '@/types/userMemory';
+import type { RetrieveMemoryParams, RetrieveMemoryResult } from '@lobechat/types';
import type { UserMemoryStoreState } from './initialState';
import { userMemoryCacheKey } from './utils/cacheKey';
@@ -57,3 +57,6 @@ export const userMemorySelectors = {
return state.memoryFetchedAtMap[key];
},
};
+
+export { agentMemorySelectors } from './slices/agent/selectors';
+export { identitySelectors } from './slices/identity/selectors';
diff --git a/src/store/userMemory/slices/agent/action.ts b/src/store/userMemory/slices/agent/action.ts
new file mode 100644
index 00000000000..24ca58f6572
--- /dev/null
+++ b/src/store/userMemory/slices/agent/action.ts
@@ -0,0 +1,69 @@
+import { omit } from 'es-toolkit';
+import type { SWRResponse } from 'swr';
+import { StateCreator } from 'zustand/vanilla';
+
+import { useClientDataSWRWithSync } from '@/libs/swr';
+import { userMemoryService } from '@/services/userMemory';
+import type { RetrieveMemoryResult } from '@/types/userMemory';
+import { setNamespace } from '@/utils/storeDebug';
+
+import { UserMemoryStore } from '../../store';
+
+const n = setNamespace('userMemory/agent');
+
+export interface AgentMemoryAction {
+ /**
+ * Clear memories for a specific topic (e.g., when topic is deleted)
+ */
+ clearTopicMemories: (topicId: string) => void;
+
+ /**
+ * Fetch and cache memories for a specific topic
+ * Uses SWR for caching and revalidation
+ */
+ useFetchMemoriesForTopic: (topicId?: string) => SWRResponse<RetrieveMemoryResult>;
+}
+
+export const createAgentMemorySlice: StateCreator<
+ UserMemoryStore,
+ [['zustand/devtools', never]],
+ [],
+ AgentMemoryAction
+> = (set, get) => ({
+ clearTopicMemories: (topicId) => {
+ set(
+ { topicMemoriesMap: omit(get().topicMemoriesMap, [topicId]) },
+ false,
+ n('clearTopicMemories', { topicId }),
+ );
+ },
+
+ useFetchMemoriesForTopic: (topicId) =>
+ useClientDataSWRWithSync<RetrieveMemoryResult>(
+ topicId ? ['useFetchMemoriesForTopic', topicId] : null,
+ async () => {
+ // Retrieve memories using topic's context
+ // The backend will use topic info to build the query
+ return await userMemoryService.retrieveMemoryForTopic(topicId!);
+ },
+ {
+ onData: (data) => {
+ if (!topicId || !data) return;
+
+ set(
+ (state) => ({
+ topicMemoriesMap: { ...state.topicMemoriesMap, [topicId]: data },
+ }),
+ false,
+ n('useFetchMemoriesForTopic/success', {
+ contextsCount: data.contexts?.length ?? 0,
+ experiencesCount: data.experiences?.length ?? 0,
+ preferencesCount: data.preferences?.length ?? 0,
+ topicId,
+ }),
+ );
+ },
+ revalidateOnFocus: false,
+ },
+ ),
+});
diff --git a/src/store/userMemory/slices/agent/index.ts b/src/store/userMemory/slices/agent/index.ts
new file mode 100644
index 00000000000..cec69d139dd
--- /dev/null
+++ b/src/store/userMemory/slices/agent/index.ts
@@ -0,0 +1,3 @@
+export { type AgentMemoryAction, createAgentMemorySlice } from './action';
+export { agentMemoryInitialState, type AgentMemorySliceState } from './initialState';
+export { agentMemorySelectors } from './selectors';
diff --git a/src/store/userMemory/slices/agent/initialState.ts b/src/store/userMemory/slices/agent/initialState.ts
new file mode 100644
index 00000000000..2b783721d9f
--- /dev/null
+++ b/src/store/userMemory/slices/agent/initialState.ts
@@ -0,0 +1,13 @@
+import type { RetrieveMemoryResult } from '@/types/userMemory';
+
+export interface AgentMemorySliceState {
+ /**
+ * Topic-based memory cache for agent context injection
+ * Key is topicId, value is the retrieved memories for that topic
+ */
+ topicMemoriesMap: Record<string, RetrieveMemoryResult>;
+}
+
+export const agentMemoryInitialState: AgentMemorySliceState = {
+ topicMemoriesMap: {},
+};
diff --git a/src/store/userMemory/slices/agent/selectors.ts b/src/store/userMemory/slices/agent/selectors.ts
new file mode 100644
index 00000000000..0ab0e2a15b0
--- /dev/null
+++ b/src/store/userMemory/slices/agent/selectors.ts
@@ -0,0 +1,27 @@
+import type { RetrieveMemoryResult } from '@/types/userMemory';
+
+import type { UserMemoryStoreState } from '../../initialState';
+
+export const agentMemorySelectors = {
+
+ /**
+ * Check if memories exist for a specific topic
+ */
+hasTopicMemories:
+ (topicId: string | undefined) =>
+ (state: UserMemoryStoreState): boolean => {
+ if (!topicId) return false;
+ return !!state.topicMemoriesMap[topicId];
+ },
+
+
+ /**
+ * Get memories for a specific topic
+ */
+topicMemories:
+ (topicId: string | undefined) =>
+ (state: UserMemoryStoreState): RetrieveMemoryResult | undefined => {
+ if (!topicId) return undefined;
+ return state.topicMemoriesMap[topicId];
+ },
+};
diff --git a/src/store/userMemory/slices/base/action.ts b/src/store/userMemory/slices/base/action.ts
index fd2fe5b8c42..4da61c41400 100644
--- a/src/store/userMemory/slices/base/action.ts
+++ b/src/store/userMemory/slices/base/action.ts
@@ -3,13 +3,14 @@ import type { SWRResponse } from 'swr';
import useSWR from 'swr';
import { StateCreator } from 'zustand/vanilla';
-import { mutate, useClientDataSWR } from '@/libs/swr';
+import { mutate, useClientDataSWR, useClientDataSWRWithSync } from '@/libs/swr';
import { userMemoryService } from '@/services/userMemory';
import { LayersEnum } from '@/types/userMemory';
import type { RetrieveMemoryParams, RetrieveMemoryResult } from '@/types/userMemory';
import { setNamespace } from '@/utils/storeDebug';
import { UserMemoryStore } from '../../store';
+import type { IdentityForInjection } from '../../types';
import { userMemoryCacheKey } from '../../utils/cacheKey';
import { createMemorySearchParams } from '../../utils/searchParams';
@@ -33,6 +34,11 @@ export interface BaseAction {
enable: boolean,
params?: RetrieveMemoryParams,
) => SWRResponse<RetrieveMemoryResult>;
+ /**
+ * Initialize global identities at app startup
+ * Fetches up to 50 most recent identities for chat context injection
+ */
+ useInitIdentities: (isLogin: boolean) => SWRResponse<any>;
}
export const createBaseSlice: StateCreator<
@@ -83,7 +89,7 @@ export const createBaseSlice: StateCreator<
},
updateMemory: async (id, content, layer) => {
- const { memoryCRUDService } = await import('@/services/userMemory/index');
+ const { memoryCRUDService } = await import('@/services/userMemory');
const { resetContextsList, resetExperiencesList, resetIdentitiesList, resetPreferencesList } =
get();
@@ -246,4 +252,29 @@ export const createBaseSlice: StateCreator<
},
);
},
+
+ useInitIdentities: (isLogin) => {
+ return useClientDataSWRWithSync<IdentityForInjection[]>(
+ isLogin ? 'useInitIdentities' : null,
+ // Use dedicated API that filters for self identities only
+ () => userMemoryService.queryIdentitiesForInjection({ limit: 25 }),
+ {
+ onSuccess: (data) => {
+ if (!data) return;
+
+ const fetchedAt = Date.now();
+
+ set(
+ {
+ globalIdentities: data,
+ globalIdentitiesFetchedAt: fetchedAt,
+ globalIdentitiesInit: true,
+ },
+ false,
+ n('useInitIdentities/success', { count: data.length }),
+ );
+ },
+ },
+ );
+ },
});
diff --git a/src/store/userMemory/slices/home/action.ts b/src/store/userMemory/slices/home/action.ts
index 16e1a3ff42d..8a8e654651f 100644
--- a/src/store/userMemory/slices/home/action.ts
+++ b/src/store/userMemory/slices/home/action.ts
@@ -5,7 +5,7 @@ import { QueryIdentityRolesResult } from '@/database/models/userMemory';
import { useClientDataSWR } from '@/libs/swr';
import { userMemoryService } from '@/services/userMemory';
-import { UserMemoryStore } from '../../store';
+import type { UserMemoryStore } from '../../store';
const FETCH_TAGS_KEY = 'useFetchTags';
const n = (namespace: string) => namespace;
diff --git a/src/store/userMemory/slices/identity/action.ts b/src/store/userMemory/slices/identity/action.ts
index 3123b2cf828..eb71b7c286d 100644
--- a/src/store/userMemory/slices/identity/action.ts
+++ b/src/store/userMemory/slices/identity/action.ts
@@ -1,13 +1,16 @@
-import { NewUserMemoryIdentity, UpdateUserMemoryIdentity } from '@lobechat/types';
+import {
+ LayersEnum,
+ NewUserMemoryIdentity,
+ TypesEnum,
+ UpdateUserMemoryIdentity,
+} from '@lobechat/types';
import { uniqBy } from 'es-toolkit/compat';
import { produce } from 'immer';
import useSWR, { SWRResponse } from 'swr';
import { StateCreator } from 'zustand/vanilla';
import { AddIdentityEntryResult } from '@/database/models/userMemory';
-import { userMemoryService } from '@/services/userMemory';
-import { memoryCRUDService } from '@/services/userMemory/index';
-import { LayersEnum, TypesEnum } from '@/types/userMemory';
+import { memoryCRUDService, userMemoryService } from '@/services/userMemory';
import { setNamespace } from '@/utils/storeDebug';
import { UserMemoryStore } from '../../store';
@@ -99,15 +102,13 @@ export const createIdentitySlice: StateCreator<
return useSWR(
swrKey,
async () => {
- const result = await userMemoryService.queryMemories({
+ return await userMemoryService.queryMemories({
layer: LayersEnum.Identity,
page: params.page,
pageSize: params.pageSize,
q: params.q,
types: params.types,
});
-
- return result;
},
{
onSuccess(data: any) {
diff --git a/src/store/userMemory/slices/identity/index.ts b/src/store/userMemory/slices/identity/index.ts
index 13ab0b20523..2ed7573daef 100644
--- a/src/store/userMemory/slices/identity/index.ts
+++ b/src/store/userMemory/slices/identity/index.ts
@@ -1 +1,2 @@
export { createIdentitySlice, type IdentityAction } from './action';
+export { identityInitialState, type IdentitySliceState } from './initialState';
diff --git a/src/store/userMemory/slices/identity/initialState.ts b/src/store/userMemory/slices/identity/initialState.ts
new file mode 100644
index 00000000000..2440df51121
--- /dev/null
+++ b/src/store/userMemory/slices/identity/initialState.ts
@@ -0,0 +1,34 @@
+import { DisplayIdentityMemory } from '@/database/repositories/userMemory';
+import type { TypesEnum } from '@/types/userMemory';
+
+import type { IdentityForInjection } from '../../types';
+
+export interface IdentitySliceState {
+ /** Global identities fetched at app initialization for injection into chat context */
+ globalIdentities: IdentityForInjection[];
+ /** When global identities were fetched */
+ globalIdentitiesFetchedAt?: number;
+ /** Whether global identities have been initialized */
+ globalIdentitiesInit: boolean;
+ identities: DisplayIdentityMemory[];
+ identitiesHasMore: boolean;
+ identitiesInit: boolean;
+ identitiesPage: number;
+ identitiesQuery?: string;
+ identitiesSearchLoading?: boolean;
+ identitiesTotal: number;
+ identitiesTypes?: TypesEnum[];
+}
+
+export const identityInitialState: IdentitySliceState = {
+ globalIdentities: [],
+ globalIdentitiesFetchedAt: undefined,
+ globalIdentitiesInit: false,
+ identities: [],
+ identitiesHasMore: true,
+ identitiesInit: false,
+ identitiesPage: 1,
+ identitiesQuery: undefined,
+ identitiesTotal: 0,
+ identitiesTypes: undefined,
+};
diff --git a/src/store/userMemory/slices/identity/selectors.ts b/src/store/userMemory/slices/identity/selectors.ts
new file mode 100644
index 00000000000..12c3b1824fc
--- /dev/null
+++ b/src/store/userMemory/slices/identity/selectors.ts
@@ -0,0 +1,19 @@
+import type { UserMemoryStoreState } from '../../initialState';
+import type { IdentityForInjection } from '../../types';
+
+export const identitySelectors = {
+ /**
+ * Get global identities for chat context injection
+ */
+ globalIdentities: (state: UserMemoryStoreState): IdentityForInjection[] => state.globalIdentities,
+
+ /**
+ * Check if global identities have been initialized
+ */
+ globalIdentitiesInit: (state: UserMemoryStoreState): boolean => state.globalIdentitiesInit,
+
+ /**
+ * Check if there are any global identities
+ */
+ hasGlobalIdentities: (state: UserMemoryStoreState): boolean => state.globalIdentities.length > 0,
+};
diff --git a/src/store/userMemory/store.ts b/src/store/userMemory/store.ts
index eceadcae8dd..816d9b16f45 100644
--- a/src/store/userMemory/store.ts
+++ b/src/store/userMemory/store.ts
@@ -4,6 +4,7 @@ import { type StateCreator } from 'zustand/vanilla';
import { createDevtools } from '../middleware/createDevtools';
import { type UserMemoryStoreState, initialState } from './initialState';
+import { type AgentMemoryAction, createAgentMemorySlice } from './slices/agent';
import { type BaseAction, createBaseSlice } from './slices/base';
import { type ContextAction, createContextSlice } from './slices/context';
import { type ExperienceAction, createExperienceSlice } from './slices/experience';
@@ -12,6 +13,7 @@ import { type IdentityAction, createIdentitySlice } from './slices/identity';
import { type PreferenceAction, createPreferenceSlice } from './slices/preference';
export type UserMemoryStore = UserMemoryStoreState &
+ AgentMemoryAction &
BaseAction &
ContextAction &
ExperienceAction &
@@ -25,6 +27,7 @@ const createStore: StateCreator<UserMemoryStore, [['zustand/devtools', never]]>
store,
) => ({
...initialState,
+ ...createAgentMemorySlice(set, get, store),
...createBaseSlice(set, get, store),
...createContextSlice(set, get, store),
...createExperienceSlice(set, get, store),
diff --git a/src/store/userMemory/types.ts b/src/store/userMemory/types.ts
new file mode 100644
index 00000000000..1ce6e391a15
--- /dev/null
+++ b/src/store/userMemory/types.ts
@@ -0,0 +1,14 @@
+/**
+ * Identity data structure for chat context injection
+ * This is the subset of fields returned by queryIdentitiesForInjection API
+ */
+export interface IdentityForInjection {
+ /** When the identity was captured/observed */
+ capturedAt: Date;
+ createdAt: Date;
+ description: string | null;
+ id: string;
+ role: string | null;
+ type: string | null;
+ updatedAt: Date;
+}
diff --git a/src/tools/identifiers.ts b/src/tools/identifiers.ts
index 8f26e8d377a..a802aa7700d 100644
--- a/src/tools/identifiers.ts
+++ b/src/tools/identifiers.ts
@@ -3,6 +3,7 @@ import { GroupAgentBuilderManifest } from '@lobechat/builtin-tool-group-agent-bu
import { GroupManagementManifest } from '@lobechat/builtin-tool-group-management';
import { GTDManifest } from '@lobechat/builtin-tool-gtd';
import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
+import { MemoryManifest } from '@lobechat/builtin-tool-memory';
import { NotebookManifest } from '@lobechat/builtin-tool-notebook';
import { ArtifactsManifest } from './artifacts';
@@ -22,5 +23,6 @@ export const builtinToolIdentifiers: string[] = [
GroupAgentBuilderManifest.identifier,
GroupManagementManifest.identifier,
GTDManifest.identifier,
+ MemoryManifest.identifier,
NotebookManifest.identifier,
];