🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat: add the agent cron job (#11370)
Shinji-Li10e47d926fd4
diff --git a/packages/builtin-tool-notebook/src/client/Render/CreateDocument/DocumentCard.tsx b/packages/builtin-tool-notebook/src/client/Render/CreateDocument/DocumentCard.tsxindex e5989e700be..2acfd4a6fb9 100644--- a/packages/builtin-tool-notebook/src/client/Render/CreateDocument/DocumentCard.tsx+++ b/packages/builtin-tool-notebook/src/client/Render/CreateDocument/DocumentCard.tsx@@ -11,7 +11,6 @@ import { useChatStore } from '@/store/chat';import { NotebookDocument } from '../../../types';-const styles = createStaticStyles(({ css, cssVar }) => ({container: css`position: relative;@@ -26,7 +25,6 @@ const styles = createStaticStyles(({ css, cssVar }) => ({`,content: css`padding-inline: 16px;-font-size: 14px;`,expandButton: css`diff --git a/packages/database/migrations/meta/_journal.json b/packages/database/migrations/meta/_journal.jsonindex 2aff5e6dc96..e39437e880b 100644--- a/packages/database/migrations/meta/_journal.json+++ b/packages/database/migrations/meta/_journal.json@@ -479,4 +479,4 @@}],"version": "6"-}\ No newline at end of file+}diff --git a/packages/database/src/models/__tests__/topics/topic.create.test.ts b/packages/database/src/models/__tests__/topics/topic.create.test.tsindex 229a6faea98..f8fffa78d09 100644--- a/packages/database/src/models/__tests__/topics/topic.create.test.ts+++ b/packages/database/src/models/__tests__/topics/topic.create.test.ts@@ -1,10 +1,10 @@import { eq, inArray } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { getTestDB } from '../../../core/getTestDB';import { agents, messages, sessions, topics, users } from '../../../schemas';import { LobeChatDatabase } from '../../../type';import { CreateTopicParams, TopicModel } from '../../topic';-import { getTestDB } from '../../../core/getTestDB';const userId = 'topic-create-user';const userId2 = 'topic-create-user-2';@@ -68,11 +68,17 @@ describe('TopicModel - Create', () => {expect(dbTopic).toHaveLength(1);expect(dbTopic[0]).toEqual(createdTopic);- const associatedMessages = await serverDB.select().from(messages).where(inArray(messages.id, topicData.messages!));+ const associatedMessages = await serverDB+ .select()+ .from(messages)+ .where(inArray(messages.id, topicData.messages!));expect(associatedMessages).toHaveLength(2);expect(associatedMessages.every((msg) => msg.topicId === topicId)).toBe(true);- const unassociatedMessage = await serverDB.select().from(messages).where(eq(messages.id, 'message3'));+ const unassociatedMessage = await serverDB+ .select()+ .from(messages)+ .where(eq(messages.id, 'message3'));expect(unassociatedMessage[0].topicId).toBeNull();});@@ -169,8 +175,18 @@ describe('TopicModel - Create', () => {const createdTopics = await topicModel.batchCreate(topicParams);expect(createdTopics).toHaveLength(2);- expect(createdTopics[0]).toMatchObject({ title: 'Topic 1', favorite: true, sessionId, userId });- expect(createdTopics[1]).toMatchObject({ title: 'Topic 2', favorite: false, sessionId, userId });+ expect(createdTopics[0]).toMatchObject({+ title: 'Topic 1',+ favorite: true,+ sessionId,+ userId,+ });+ expect(createdTopics[1]).toMatchObject({+ title: 'Topic 2',+ favorite: false,+ sessionId,+ userId,+ });const items = await serverDB.select().from(topics);expect(items).toHaveLength(2);@@ -216,7 +232,15 @@ describe('TopicModel - Create', () => {expect(createdTopics[1].agentId).toBe('batch-agent-2');expect(createdTopics[1].sessionId).toBeNull();- const dbTopics = await serverDB.select().from(topics).where(inArray(topics.id, createdTopics.map((t) => t.id)));+ const dbTopics = await serverDB+ .select()+ .from(topics)+ .where(+ inArray(+ topics.id,+ createdTopics.map((t) => t.id),+ ),+ );expect(dbTopics).toHaveLength(2);expect(dbTopics.find((t) => t.id === createdTopics[0].id)?.agentId).toBe('batch-agent-1');expect(dbTopics.find((t) => t.id === createdTopics[1].id)?.agentId).toBe('batch-agent-2');@@ -236,7 +260,10 @@ describe('TopicModel - Create', () => {]);});- const { topic: duplicatedTopic, messages: duplicatedMessages } = await topicModel.duplicate(topicId, newTitle);+ const { topic: duplicatedTopic, messages: duplicatedMessages } = await topicModel.duplicate(+ topicId,+ newTitle,+ );expect(duplicatedTopic.id).not.toBe(topicId);expect(duplicatedTopic.title).toBe(newTitle);@@ -255,7 +282,9 @@ describe('TopicModel - Create', () => {it('should throw an error if the topic to duplicate does not exist', async () => {const topicId = 'nonexistent-topic';- await expect(topicModel.duplicate(topicId)).rejects.toThrow(`Topic with id ${topicId} not found`);+ await expect(topicModel.duplicate(topicId)).rejects.toThrow(+ `Topic with id ${topicId} not found`,+ );});});});diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.tsindex d398f09a50c..adb9b8b0b36 100644--- a/packages/database/src/models/topic.ts+++ b/packages/database/src/models/topic.ts@@ -27,8 +27,10 @@ export interface CreateTopicParams {favorite?: boolean;groupId?: string | null;messages?: string[];+ metadata?: ChatTopicMetadata;sessionId?: string | null;title?: string;+ trigger?: string | null;}interface QueryTopicParams {@@ -39,6 +41,10 @@ interface QueryTopicParams {*/containerId?: string | null;current?: number;+ /**+ * Exclude topics by trigger types (e.g. ['cron'])+ */+ excludeTriggers?: string[];/*** Group ID to filter topics by*/@@ -70,15 +76,24 @@ export class TopicModel {agentId,containerId,current = 0,+ excludeTriggers,pageSize = 9999,groupId,isInbox,}: QueryTopicParams = {}) => {const offset = current * pageSize;+ const excludeTriggerCondition =+ excludeTriggers && excludeTriggers.length > 0+ ? or(isNull(topics.trigger), not(inArray(topics.trigger, excludeTriggers)))+ : undefined;// If groupId is provided, query topics by groupId directlyif (groupId) {- const whereCondition = and(eq(topics.userId, this.userId), eq(topics.groupId, groupId));+ const whereCondition = and(+ eq(topics.userId, this.userId),+ eq(topics.groupId, groupId),+ excludeTriggerCondition,+ );const [items, totalResult] = await Promise.all([this.db@@ -155,21 +170,25 @@ export class TopicModel {updatedAt: topics.updatedAt,}).from(topics)- .where(and(eq(topics.userId, this.userId), agentCondition))+ .where(and(eq(topics.userId, this.userId), agentCondition, excludeTriggerCondition)).orderBy(desc(topics.favorite), desc(topics.updatedAt)).limit(pageSize).offset(offset),this.db.select({ count: count(topics.id) }).from(topics)- .where(and(eq(topics.userId, this.userId), agentCondition)),+ .where(and(eq(topics.userId, this.userId), agentCondition, excludeTriggerCondition)),]);return { items, total: totalResult[0].count };}// Fallback to containerId-based query (backward compatibility)- const whereCondition = and(eq(topics.userId, this.userId), this.matchContainer(containerId));+ const whereCondition = and(+ eq(topics.userId, this.userId),+ this.matchContainer(containerId),+ excludeTriggerCondition,+ );const [items, totalResult] = await Promise.all([this.db@@ -664,4 +683,52 @@ export class TopicModel {),});};++ /**+ * Get cron topics grouped by cronJob for a specific agent+ * Returns topics where trigger='cron' and metadata contains cronJobId+ */+ getCronTopicsGroupedByCronJob = async (agentId: string) => {+ const cronTopics = await this.db+ .select({+ createdAt: topics.createdAt,+ favorite: topics.favorite,+ historySummary: topics.historySummary,+ id: topics.id,+ metadata: topics.metadata,+ title: topics.title,+ trigger: topics.trigger,+ updatedAt: topics.updatedAt,+ })+ .from(topics)+ .where(+ and(+ eq(topics.userId, this.userId),+ eq(topics.agentId, agentId),+ eq(topics.trigger, 'cron'),+ // Check if metadata contains cronJobId+ sql`${topics.metadata}->>'cronJobId' IS NOT NULL`,+ ),+ )+ .orderBy(desc(topics.updatedAt));++ // Group topics by cronJobId+ const groupedTopics = new Map<string, typeof cronTopics>();++ cronTopics.forEach((topic) => {+ const cronJobId = topic.metadata?.cronJobId;+ if (cronJobId) {+ if (!groupedTopics.has(cronJobId)) {+ groupedTopics.set(cronJobId, []);+ }+ groupedTopics.get(cronJobId)!.push(topic);+ }+ });++ // Convert Map to array of grouped objects+ return Array.from(groupedTopics.entries()).map(([cronJobId, topicList]) => ({+ cronJobId,+ topics: topicList,+ }));+ };}diff --git a/packages/database/src/schemas/agentCronJob.ts b/packages/database/src/schemas/agentCronJob.tsindex 1b7c6bacdf5..0dcf33c4edf 100644--- a/packages/database/src/schemas/agentCronJob.ts+++ b/packages/database/src/schemas/agentCronJob.ts@@ -32,8 +32,7 @@ export const agentCronJobs = pgTable(agentId: text('agent_id').references(() => agents.id, { onDelete: 'cascade' }).notNull(),- groupId: text('group_id')- .references(() => chatGroups.id, { onDelete: 'cascade' }),+ groupId: text('group_id').references(() => chatGroups.id, { onDelete: 'cascade' }),userId: text('user_id').references(() => users.id, { onDelete: 'cascade' }).notNull(),diff --git a/packages/memory-user-memory/src/extractors/context.ts b/packages/memory-user-memory/src/extractors/context.tsindex 7aaed2d5162..834a9c49a85 100644--- a/packages/memory-user-memory/src/extractors/context.ts+++ b/packages/memory-user-memory/src/extractors/context.ts@@ -16,10 +16,7 @@ export class ContextExtractor extends BaseMemoryExtractor<ContextMemory> {}getSchema() {- return buildGenerateObjectSchema(- ContextMemorySchema,- { name: 'context_extraction' },- );+ return buildGenerateObjectSchema(ContextMemorySchema, { name: 'context_extraction' });}getResultSchema() {diff --git a/packages/memory-user-memory/src/extractors/experience.ts b/packages/memory-user-memory/src/extractors/experience.tsindex 9f038edb748..b3c69d73dd8 100644--- a/packages/memory-user-memory/src/extractors/experience.ts+++ b/packages/memory-user-memory/src/extractors/experience.ts@@ -1,10 +1,7 @@import { renderPlaceholderTemplate } from '@lobechat/context-engine';import { experiencePrompt } from '../prompts';-import {- ExperienceMemory,- ExperienceMemorySchema-} from '../schemas';+import { ExperienceMemory, ExperienceMemorySchema } from '../schemas';import { ExtractorTemplateProps } from '../types';import { buildGenerateObjectSchema } from '../utils/zod';import { BaseMemoryExtractor } from './base';@@ -19,10 +16,7 @@ export class ExperienceExtractor extends BaseMemoryExtractor<ExperienceMemory> {}getSchema() {- return buildGenerateObjectSchema(- ExperienceMemorySchema,- { name: 'experience_extraction' },- );+ return buildGenerateObjectSchema(ExperienceMemorySchema, { name: 'experience_extraction' });}getResultSchema() {diff --git a/packages/memory-user-memory/src/extractors/preference.ts b/packages/memory-user-memory/src/extractors/preference.tsindex bc86a596a7e..f7acd2fd928 100644--- a/packages/memory-user-memory/src/extractors/preference.ts+++ b/packages/memory-user-memory/src/extractors/preference.ts@@ -1,10 +1,7 @@import { renderPlaceholderTemplate } from '@lobechat/context-engine';-import {- PreferenceMemory,- PreferenceMemorySchema,-} from '../schemas';import { preferencePrompt } from '../prompts';+import { PreferenceMemory, PreferenceMemorySchema } from '../schemas';import { ExtractorTemplateProps } from '../types';import { buildGenerateObjectSchema } from '../utils/zod';import { BaseMemoryExtractor } from './base';@@ -19,10 +16,7 @@ export class PreferenceExtractor extends BaseMemoryExtractor<PreferenceMemory> {}getSchema() {- return buildGenerateObjectSchema(- PreferenceMemorySchema,- { name: 'preference_extraction' },- );+ return buildGenerateObjectSchema(PreferenceMemorySchema, { name: 'preference_extraction' });}getResultSchema() {diff --git a/packages/memory-user-memory/src/prompts/gatekeeper.ts b/packages/memory-user-memory/src/prompts/gatekeeper.tsindex cc09f6c251d..233ec208d98 100644--- a/packages/memory-user-memory/src/prompts/gatekeeper.ts+++ b/packages/memory-user-memory/src/prompts/gatekeeper.ts@@ -1,127 +1,127 @@export const gatekeeperPrompt = [- "You are a \"gate keeper\" that analyzes conversations between user and assistant to determine which memory layers contain extractable information worth storing.",- "",- "Your role is to efficiently filter conversations by identifying which of the five memory layers are present and valuable enough to extract.",- "",- "Bias toward sensitivity: when in doubt, prefer setting `shouldExtract: true` so downstream extractors can refine. Minor, incremental or clarifying updates should still be allowed to pass.",- "",- "## Memory Layer Definitions",- "",- "Evaluate the conversation for these memory layers:",- "",- "**Activity Layer** - Episodic events with clear timelines and participants:",- "",- "- Meetings, calls, errands, and appointments with start/end times",- "- Locations (physical or virtual) and timezones",- "- Status (planned, completed) and follow-up actions",- "- Narratives summarizing what happened and feedback/notes",- "",- "**Identity Layer** - Information about actors, relationships, and personal attributes:",- "",- "- Describing labels and demographics",- "- Current focusing and life priorities",- "- Relationships with other people",- "- Background and experience",- "- Roles in various contexts",- "- Identity should remain compact. Route lists of tools, stacks, or",- " implementation techniques to the preference layer unless they materially",+ 'You are a "gate keeper" that analyzes conversations between user and assistant to determine which memory layers contain extractable information worth storing.',+ '',+ 'Your role is to efficiently filter conversations by identifying which of the five memory layers are present and valuable enough to extract.',+ '',+ 'Bias toward sensitivity: when in doubt, prefer setting `shouldExtract: true` so downstream extractors can refine. Minor, incremental or clarifying updates should still be allowed to pass.',+ '',+ '## Memory Layer Definitions',+ '',+ 'Evaluate the conversation for these memory layers:',+ '',+ '**Activity Layer** - Episodic events with clear timelines and participants:',+ '',+ '- Meetings, calls, errands, and appointments with start/end times',+ '- Locations (physical or virtual) and timezones',+ '- Status (planned, completed) and follow-up actions',+ '- Narratives summarizing what happened and feedback/notes',+ '',+ '**Identity Layer** - Information about actors, relationships, and personal attributes:',+ '',+ '- Describing labels and demographics',+ '- Current focusing and life priorities',+ '- Relationships with other people',+ '- Background and experience',+ '- Roles in various contexts',+ '- Identity should remain compact. Route lists of tools, stacks, or',+ ' implementation techniques to the preference layer unless they materially'," change the user's biography.",- "",- "**Context Layer** - Only capture brand-new situational frameworks and ongoing situations that have not been recorded before:",- "",- "- Distinct situations, topics, research threads, sessions, or rounds that are clearly first-time mentions",- "- Ongoing projects and their status when the project itself is new, not just progress updates",- "- Long-term goals and objectives that are newly introduced",- "- Persistent relationships and dynamics that have not been logged previously",- "- Environmental factors and recurring situations only when they represent a new context",- "- Timelines and temporal context that establish a novel situation",- "- Impact and urgency assessments tied to a new context",- "- If the content overlaps with learnings or takeaways, treat it as Experience instead of Context",- "",- "**Preference Layer** - Durable user choices and behavioral directives that apply across multiple conversations:",- "",- "- Explicit long-term preferences with clear temporal markers (e.g., \"always\", \"never\", \"from now on\")",- "- Likes and dislikes stated as persistent traits (e.g., \"I prefer...\", \"I don't like...\")",- "- Workflow and approach preferences explicitly stated as ongoing (what to do, not how to implement)",- "- Communication style preferences explicitly stated as ongoing",- "- Response formatting preferences explicitly stated as ongoing",- "- Priority levels for preference resolution",- "- Capture recurring tool/stacks/technology usage as preferences rather than",- " duplicating them as identity facts.",- "",- "Note: Task-specific requirements, constraints for a single object/entity, or one-time instructions do NOT belong to this layer.",- "",- "**Experience Layer** - Learned insights and practical knowledge worth reusing and",- "sharing publicly:",- "",- "- Lessons learned and insights gained, especially surprising aha/yurika moments",- "- Practical tricks and techniques that solve tough or non-obvious problems",- "- Transferable knowledge and wisdom that would make a strong blog/knowledge-base",- " snippet",- "- Situation → Reasoning → Action → Outcome patterns",- "- Key learnings from experiences with self-assessed confidence/impact",- "- Skip routine or repetitive steps already well covered in retrieved memories",- "",- "## Gate Keeping Guidelines",- "",- "For each layer, consider:",- "",- "- **Relevance**: Does the conversation contain information for this layer?",- "- **Value**: Is the information substantial enough to be worth extracting?",- "- **Clarity**: Is the information clear and extractable (not vague or ambiguous)?",- "",- "Additionally, review the retrieved similar memories first (top {{ topK }} items below). If the conversation content is clearly and fully covered by existing memories with no meaningful nuance or update, set `shouldExtract: false`.",- "For the Experience layer, prefer `shouldExtract: true` only when the conversation adds a new takeaway, aha moment, or harder challenge resolution beyond what is already recorded.",- "For the Context layer specifically, favor `shouldExtract: false` unless the conversation introduces a genuinely new situation/topic/research/session that is not already represented in existing context memories or overlaps with Experience items.",- "Otherwise, favor `shouldExtract: true` for:",- "",- "- Novel facts OR even small clarifications/precision improvements to existing details",- "- Incremental changes to status/progress of an ongoing context",- "- A new preference OR a refinement that affects future behavior",- "- Distinct experiences/lessons, even if closely related to prior items",- "",- "Preference-specific filters (STRICT - when in doubt, set shouldExtract: false):",- "",- "CRITICAL: Distinguish between \"user's behavioral preferences\" vs. \"task requirements for a specific deliverable\":",- "",- "- If the instruction describes what the OUTPUT should be like (e.g., \"name should have natural vibe\", \"don't use surname\"), it's a task requirement, NOT a user preference.",- "- If the instruction describes how the ASSISTANT should behave across conversations (e.g., \"always explain before coding\", \"never use jargon\"), it's a preference.",- "",- "Specific exclusion rules:",- "",+ '',+ '**Context Layer** - Only capture brand-new situational frameworks and ongoing situations that have not been recorded before:',+ '',+ '- Distinct situations, topics, research threads, sessions, or rounds that are clearly first-time mentions',+ '- Ongoing projects and their status when the project itself is new, not just progress updates',+ '- Long-term goals and objectives that are newly introduced',+ '- Persistent relationships and dynamics that have not been logged previously',+ '- Environmental factors and recurring situations only when they represent a new context',+ '- Timelines and temporal context that establish a novel situation',+ '- Impact and urgency assessments tied to a new context',+ '- If the content overlaps with learnings or takeaways, treat it as Experience instead of Context',+ '',+ '**Preference Layer** - Durable user choices and behavioral directives that apply across multiple conversations:',+ '',+ '- Explicit long-term preferences with clear temporal markers (e.g., "always", "never", "from now on")',+ '- Likes and dislikes stated as persistent traits (e.g., "I prefer...", "I don\'t like...")',+ '- Workflow and approach preferences explicitly stated as ongoing (what to do, not how to implement)',+ '- Communication style preferences explicitly stated as ongoing',+ '- Response formatting preferences explicitly stated as ongoing',+ '- Priority levels for preference resolution',+ '- Capture recurring tool/stacks/technology usage as preferences rather than',+ ' duplicating them as identity facts.',+ '',+ 'Note: Task-specific requirements, constraints for a single object/entity, or one-time instructions do NOT belong to this layer.',+ '',+ '**Experience Layer** - Learned insights and practical knowledge worth reusing and',+ 'sharing publicly:',+ '',+ '- Lessons learned and insights gained, especially surprising aha/yurika moments',+ '- Practical tricks and techniques that solve tough or non-obvious problems',+ '- Transferable knowledge and wisdom that would make a strong blog/knowledge-base',+ ' snippet',+ '- Situation → Reasoning → Action → Outcome patterns',+ '- Key learnings from experiences with self-assessed confidence/impact',+ '- Skip routine or repetitive steps already well covered in retrieved memories',+ '',+ '## Gate Keeping Guidelines',+ '',+ 'For each layer, consider:',+ '',+ '- **Relevance**: Does the conversation contain information for this layer?',+ '- **Value**: Is the information substantial enough to be worth extracting?',+ '- **Clarity**: Is the information clear and extractable (not vague or ambiguous)?',+ '',+ 'Additionally, review the retrieved similar memories first (top {{ topK }} items below). If the conversation content is clearly and fully covered by existing memories with no meaningful nuance or update, set `shouldExtract: false`.',+ 'For the Experience layer, prefer `shouldExtract: true` only when the conversation adds a new takeaway, aha moment, or harder challenge resolution beyond what is already recorded.',+ 'For the Context layer specifically, favor `shouldExtract: false` unless the conversation introduces a genuinely new situation/topic/research/session that is not already represented in existing context memories or overlaps with Experience items.',+ 'Otherwise, favor `shouldExtract: true` for:',+ '',+ '- Novel facts OR even small clarifications/precision improvements to existing details',+ '- Incremental changes to status/progress of an ongoing context',+ '- A new preference OR a refinement that affects future behavior',+ '- Distinct experiences/lessons, even if closely related to prior items',+ '',+ 'Preference-specific filters (STRICT - when in doubt, set shouldExtract: false):',+ '',+ 'CRITICAL: Distinguish between "user\'s behavioral preferences" vs. "task requirements for a specific deliverable":',+ '',+ '- If the instruction describes what the OUTPUT should be like (e.g., "name should have natural vibe", "don\'t use surname"), it\'s a task requirement, NOT a user preference.',+ '- If the instruction describes how the ASSISTANT should behave across conversations (e.g., "always explain before coding", "never use jargon"), it\'s a preference.',+ '',+ 'Specific exclusion rules:',+ '',"- Do NOT treat the conversation's language as a preference unless the user explicitly states a persistent preference for language.",- "- Exclude one-off task instructions and implementation steps; these are not preferences.",- "- Exclude task-specific constraints, requirements, or clarifications (e.g., \"don't use surname Wang\", \"make it summer-themed\", \"natural vibe\") - these describe the current task deliverable, not user's persistent preferences.",- "- Exclude requirements or attributes for a specific object/entity being discussed (e.g., naming a cat, designing a logo) - these are task parameters, not user preferences.",- "- Exclude in-conversation clarifications or corrections (e.g., user first says X, then says \"no, not X\") - these refine the current task, not future behavior.",- "- Only extract when the user uses explicit preference markers like \"I always...\", \"I prefer...\", \"I never...\", \"from now on...\", \"please always...\" that clearly indicate cross-session intent.",- "- If the preference is about how to complete THIS specific task rather than how to behave in FUTURE tasks, exclude it.",- "- Ask yourself: \"Would this apply to a completely different conversation topic?\" If no, it's not a preference.",- "",- "Examples of what NOT to extract:",- "",- "- User asks for a cat name with \"natural vibe\" and \"born in summer\" → NOT a preference (task constraint)",- "- User says \"don't use surname Wang\" for naming → NOT a preference (task clarification)",- "- User wants a \"minimalist design\" for this logo → NOT a preference (task requirement)",- "",- "Examples of what TO extract:",- "",- "- \"I always prefer concise responses\" → IS a preference (cross-session directive)",- "- \"Never use technical jargon when explaining to me\" → IS a preference (persistent rule)",- "- \"From now on, please format code with comments\" → IS a preference (ongoing instruction)",- "",- "If uncertain about novelty, but information is relevant and clear, set `shouldExtract: true` and include a short reasoning.",- "",- "## Output Guidelines",- "",- "For each memory layer (activity, identity, context, preference, experience), provide:",- "",- "- `shouldExtract`: Boolean indicating whether extraction is recommended",- "- `reasoning`: Brief explanation of your decision (write in English)",- "",- "## Retrieved Memory (Top {{ topK }})",- "",- "Use the list below as context for deduplication and to determine whether extraction is necessary. Do not repeat these verbatim unless needed for comparison.",- "",- "{{ retrievedContext }}",+ '- Exclude one-off task instructions and implementation steps; these are not preferences.',+ '- Exclude task-specific constraints, requirements, or clarifications (e.g., "don\'t use surname Wang", "make it summer-themed", "natural vibe") - these describe the current task deliverable, not user\'s persistent preferences.',+ '- Exclude requirements or attributes for a specific object/entity being discussed (e.g., naming a cat, designing a logo) - these are task parameters, not user preferences.',+ '- Exclude in-conversation clarifications or corrections (e.g., user first says X, then says "no, not X") - these refine the current task, not future behavior.',+ '- Only extract when the user uses explicit preference markers like "I always...", "I prefer...", "I never...", "from now on...", "please always..." that clearly indicate cross-session intent.',+ '- If the preference is about how to complete THIS specific task rather than how to behave in FUTURE tasks, exclude it.',+ '- Ask yourself: "Would this apply to a completely different conversation topic?" If no, it\'s not a preference.',+ '',+ 'Examples of what NOT to extract:',+ '',+ '- User asks for a cat name with "natural vibe" and "born in summer" → NOT a preference (task constraint)',+ '- User says "don\'t use surname Wang" for naming → NOT a preference (task clarification)',+ '- User wants a "minimalist design" for this logo → NOT a preference (task requirement)',+ '',+ 'Examples of what TO extract:',+ '',+ '- "I always prefer concise responses" → IS a preference (cross-session directive)',+ '- "Never use technical jargon when explaining to me" → IS a preference (persistent rule)',+ '- "From now on, please format code with comments" → IS a preference (ongoing instruction)',+ '',+ 'If uncertain about novelty, but information is relevant and clear, set `shouldExtract: true` and include a short reasoning.',+ '',+ '## Output Guidelines',+ '',+ 'For each memory layer (activity, identity, context, preference, experience), provide:',+ '',+ '- `shouldExtract`: Boolean indicating whether extraction is recommended',+ '- `reasoning`: Brief explanation of your decision (write in English)',+ '',+ '## Retrieved Memory (Top {{ topK }})',+ '',+ 'Use the list below as context for deduplication and to determine whether extraction is necessary. Do not repeat these verbatim unless needed for comparison.',+ '',+ '{{ retrievedContext }}',].join('\n');diff --git a/packages/memory-user-memory/src/prompts/layers/context.ts b/packages/memory-user-memory/src/prompts/layers/context.tsindex d89bbe99d41..a32e6703d94 100644--- a/packages/memory-user-memory/src/prompts/layers/context.ts+++ b/packages/memory-user-memory/src/prompts/layers/context.ts@@ -1,155 +1,155 @@export const contextPrompt = [- "You are a focused memory extraction assistant specialized in the **context**",- "layer.",- "When extracting, ensure all the content is using {{ language }}.",- "",- "\\<user_context>",- "Current user: {{ username }}",- "Session date: {{ sessionDate }}",- "Available memory categories: {{ availableCategories }}",- "Target layer: context",- "\\</user_context>",- "",- "## Retrieved Memory (Top {{ topK }})",- "",- "Use the list below to de-duplicate and decide whether you need to extract",- "anything new. Do not copy these verbatim; treat them as comparison references.",- "",- "{{ retrievedContext }}",- "",- "## Your Task",- "",- "Extract **ALL** context layer information from the conversation.",- "Situational frameworks that span memories (projects,",- "relationships, goals, ongoing situations).",- "",- "**CRITICAL**: Return an **array** of memory items. One conversation",- "can contain context memories. Extract each as a separate item.",- "",- "Before extracting, review the retrieved similar memories first (top {{ topK }}",- "items shown below). Extract items that are NEW or MATERIALLY UPDATED",- "compared to retrieved entries. Avoid duplicates or near-duplicates.",- "Prefer manual merging rather than duplicating: if content is already",- "covered with no new detail, do not extract it again.",- "",- "## Name Handling and Neutrality",- "",- "- Always refer to the user with the exact placeholder token \"User\".",+ 'You are a focused memory extraction assistant specialized in the **context**',+ 'layer.',+ 'When extracting, ensure all the content is using {{ language }}.',+ '',+ '\\<user_context>',+ 'Current user: {{ username }}',+ 'Session date: {{ sessionDate }}',+ 'Available memory categories: {{ availableCategories }}',+ 'Target layer: context',+ '\\</user_context>',+ '',+ '## Retrieved Memory (Top {{ topK }})',+ '',+ 'Use the list below to de-duplicate and decide whether you need to extract',+ 'anything new. Do not copy these verbatim; treat them as comparison references.',+ '',+ '{{ retrievedContext }}',+ '',+ '## Your Task',+ '',+ 'Extract **ALL** context layer information from the conversation.',+ 'Situational frameworks that span memories (projects,',+ 'relationships, goals, ongoing situations).',+ '',+ '**CRITICAL**: Return an **array** of memory items. One conversation',+ 'can contain context memories. Extract each as a separate item.',+ '',+ 'Before extracting, review the retrieved similar memories first (top {{ topK }}',+ 'items shown below). Extract items that are NEW or MATERIALLY UPDATED',+ 'compared to retrieved entries. Avoid duplicates or near-duplicates.',+ 'Prefer manual merging rather than duplicating: if content is already',+ 'covered with no new detail, do not extract it again.',+ '',+ '## Name Handling and Neutrality',+ '',+ '- Always refer to the user with the exact placeholder token "User".'," Do not infer, invent, or translate the user's real name.",- "- Do not assign gendered terms or honorifics (e.g., \"先生 / 女士\", \"Mr./Ms.\").",- " Keep all references neutral during extraction.",- "",- "## Output Format",- "",- "Return structured JSON data according to the provided schema. A strict schema",- "validates the output and includes:",- "",- "- Basic fields: title, summary, details, memoryLayer, memoryType, memoryCategory",- "- Context-specific fields in withContext: title, description, extractedLabels,",- " associatedSubjects (array of object), associatedObjects (array of object),",- " currentStatus, type, scoreImpact, scoreUrgency.",- "- For associatedSubjects and associatedObjects, the following fields are possible",- " to have:",- " - name (string)",- " - type (string)",- " - extra (object in JSON string, valid JSON format)",- "",- "",- "## Memory Formatting Guidelines",- "",- "> CRITICAL REQUIREMENT: ALL MEMORY ITEMS MUST BE SELF-CONTAINED",- "",- "Every memory item you create must be standalone and understandable without",- "extra context:",- "",- "✓ **Required Elements:**",- "",- "- Use full names and specific subjects—NEVER use pronouns",- " (he/she/they/it/this/that)",- "- Include specific names, places, dates, and complete context",- "- Preserve the original language from user input—do not translate",- "- Capture relevant details, emotions, and outcomes",- "- Ensure each item is comprehensible independently",- "",- "✓ **Good Examples:**",- "",- "- \"{{ username }} attended an LGBTQ support group on 2024-03-15 where",- " {{ username }} heard inspiring transgender stories from community members and",- " felt happy, thankful, and accepted,",- " gaining courage to embrace {{ username }}'s true self.\"",- "- \"{{ username }} discussed future career plans with Melanie during their",- " counseling session, expressed keen interest in mental health work that",- " supports people with similar experiences, and received encouragement from",- " Melanie, who said {{ username }} would excel as a counselor due to",- " {{ username }}'s natural empathy and deep understanding.\"",- "",- "✗ **Bad Examples:**",- "",- "- \"She went to a support group\" → Missing: who, when, what happened, emotional",- " outcome",- "- \"They felt happy\" → Missing: who, context, cause of emotion",- "- \"The discussion was helpful\" → Missing: participants, topic, specific value",- " gained",- "- \"This made them realize something important\" → Vague pronouns and undefined",- " referents",- "",- "## Layer-Specific Extraction Guidance",- "",- "### Context Layer Focus",- "",- "Summarize enduring situations connecting related memories (projects, goals,",- "relationships). Name actors (associatedSubjects) and resources",- "(associatedObjects) explicitly for downstream reasoning. Track currentStatus to",- "signal lifecycle stage (\"exploring\", \"active\", \"on-hold\", \"completed\"). Update",- "existing contexts incrementally rather than duplicating entries. Provide",- "extractedLabels for thematic tagging; downstream systems handle embeddings.",- "Assess impact and urgency scores for prioritization.",- "",- "Examples of context information:",- "",- "- Ongoing project: \"{{ username }} is developing a mobile app for habit",- " tracking, in the design phase, with planned launch in Q2 2025\"",- "- Long-term goal: \"{{ username }} aims to transition from software engineering",- " to product management within the next 18 months\"",- "",- "## Memory Type Classifications",- "",- "Choose the appropriate memoryType:",- "",- "- **activity**: Detailed conversations, interactions, and events with full",- " contextual narrative",- "- **event**: Specific time-bound occurrences (dates, milestones, appointments,",- " meetings)",- "- **fact**: Factual data points and verifiable knowledge",- "- **preference**: User choices, likes, dislikes, and behavioral preferences",- "- **context**: Background information, situational details, environmental",- " factors",- "- **location**: Geographic information, places, and spatial context",- "- **people**: Information about individuals and their relationships",- "- **topic**: Subject matter, domains of interest, and knowledge areas",- "- **technology**: Tools, platforms, software, and technical systems",- "- **other**: Miscellaneous information not fitting other categories",- "",- "## Security Considerations",- "",- "**NEVER extract or store sensitive information:**",- "",- "- Passwords, PINs, or authentication credentials",- "- API keys, tokens, or secret keys",- "- Financial data (credit cards, bank accounts, SSN)",- "- Medical records or protected health information",- "- Private encryption keys or certificates",- "",- "---",- "",- "**Final Instructions:**",- "",- "1. Analyze the conversation for context layer information",- "2. Extract each distinct context memory as a separate item",- "3. Ensure all memories are self-contained (no pronouns, complete context)",- "4. Return a JSON array conforming to the schema above",- "5. Return `[]` if no context memories found",- "6. No matter what the language of the retrieved language is, always use {{ language }} for output",- "",- "Respond with valid JSON and no commentary.",+ '- Do not assign gendered terms or honorifics (e.g., "先生 / 女士", "Mr./Ms.").',+ ' Keep all references neutral during extraction.',+ '',+ '## Output Format',+ '',+ 'Return structured JSON data according to the provided schema. A strict schema',+ 'validates the output and includes:',+ '',+ '- Basic fields: title, summary, details, memoryLayer, memoryType, memoryCategory',+ '- Context-specific fields in withContext: title, description, extractedLabels,',+ ' associatedSubjects (array of object), associatedObjects (array of object),',+ ' currentStatus, type, scoreImpact, scoreUrgency.',+ '- For associatedSubjects and associatedObjects, the following fields are possible',+ ' to have:',+ ' - name (string)',+ ' - type (string)',+ ' - extra (object in JSON string, valid JSON format)',+ '',+ '',+ '## Memory Formatting Guidelines',+ '',+ '> CRITICAL REQUIREMENT: ALL MEMORY ITEMS MUST BE SELF-CONTAINED',+ '',+ 'Every memory item you create must be standalone and understandable without',+ 'extra context:',+ '',+ '✓ **Required Elements:**',+ '',+ '- Use full names and specific subjects—NEVER use pronouns',+ ' (he/she/they/it/this/that)',+ '- Include specific names, places, dates, and complete context',+ '- Preserve the original language from user input—do not translate',+ '- Capture relevant details, emotions, and outcomes',+ '- Ensure each item is comprehensible independently',+ '',+ '✓ **Good Examples:**',+ '',+ '- "{{ username }} attended an LGBTQ support group on 2024-03-15 where',+ ' {{ username }} heard inspiring transgender stories from community members and',+ ' felt happy, thankful, and accepted,',+ ' gaining courage to embrace {{ username }}\'s true self."',+ '- "{{ username }} discussed future career plans with Melanie during their',+ ' counseling session, expressed keen interest in mental health work that',+ ' supports people with similar experiences, and received encouragement from',+ ' Melanie, who said {{ username }} would excel as a counselor due to',+ ' {{ username }}\'s natural empathy and deep understanding."',+ '',+ '✗ **Bad Examples:**',+ '',+ '- "She went to a support group" → Missing: who, when, what happened, emotional',+ ' outcome',+ '- "They felt happy" → Missing: who, context, cause of emotion',+ '- "The discussion was helpful" → Missing: participants, topic, specific value',+ ' gained',+ '- "This made them realize something important" → Vague pronouns and undefined',+ ' referents',+ '',+ '## Layer-Specific Extraction Guidance',+ '',+ '### Context Layer Focus',+ '',+ 'Summarize enduring situations connecting related memories (projects, goals,',+ 'relationships). Name actors (associatedSubjects) and resources',+ '(associatedObjects) explicitly for downstream reasoning. Track currentStatus to',+ 'signal lifecycle stage ("exploring", "active", "on-hold", "completed"). Update',+ 'existing contexts incrementally rather than duplicating entries. Provide',+ 'extractedLabels for thematic tagging; downstream systems handle embeddings.',+ 'Assess impact and urgency scores for prioritization.',+ '',+ 'Examples of context information:',+ '',+ '- Ongoing project: "{{ username }} is developing a mobile app for habit',+ ' tracking, in the design phase, with planned launch in Q2 2025"',+ '- Long-term goal: "{{ username }} aims to transition from software engineering',+ ' to product management within the next 18 months"',+ '',+ '## Memory Type Classifications',+ '',+ 'Choose the appropriate memoryType:',+ '',+ '- **activity**: Detailed conversations, interactions, and events with full',+ ' contextual narrative',+ '- **event**: Specific time-bound occurrences (dates, milestones, appointments,',+ ' meetings)',+ '- **fact**: Factual data points and verifiable knowledge',+ '- **preference**: User choices, likes, dislikes, and behavioral preferences',+ '- **context**: Background information, situational details, environmental',+ ' factors',+ '- **location**: Geographic information, places, and spatial context',+ '- **people**: Information about individuals and their relationships',+ '- **topic**: Subject matter, domains of interest, and knowledge areas',+ '- **technology**: Tools, platforms, software, and technical systems',+ '- **other**: Miscellaneous information not fitting other categories',+ '',+ '## Security Considerations',+ '',+ '**NEVER extract or store sensitive information:**',+ '',+ '- Passwords, PINs, or authentication credentials',+ '- API keys, tokens, or secret keys',+ '- Financial data (credit cards, bank accounts, SSN)',+ '- Medical records or protected health information',+ '- Private encryption keys or certificates',+ '',+ '---',+ '',+ '**Final Instructions:**',+ '',+ '1. Analyze the conversation for context layer information',+ '2. Extract each distinct context memory as a separate item',+ '3. Ensure all memories are self-contained (no pronouns, complete context)',+ '4. Return a JSON array conforming to the schema above',+ '5. Return `[]` if no context memories found',+ '6. No matter what the language of the retrieved language is, always use {{ language }} for output',+ '',+ 'Respond with valid JSON and no commentary.',].join('\n');diff --git a/packages/memory-user-memory/src/prompts/layers/experience.ts b/packages/memory-user-memory/src/prompts/layers/experience.tsindex cb16dc83f2e..48fc93dc563 100644--- a/packages/memory-user-memory/src/prompts/layers/experience.ts+++ b/packages/memory-user-memory/src/prompts/layers/experience.ts@@ -1,162 +1,162 @@export const experiencePrompt = [- "You are a focused memory extraction assistant specialized in the **experience**",- "layer. You capture standout, story-worthy experiences that can be reused as",- "building blocks for public-facing blogs or knowledge bases. When extracting,",- "ensure all the content is using {{ language }}.",- "",- "\\<user_context>",- "Current user: {{ username }}",- "Session date: {{ sessionDate }}",- "Available memory categories: {{ availableCategories }}",- "Target layer: experience",- "\\</user_context>",- "",- "## Retrieved Memory (Top {{ topK }})",- "",- "Use the list below to de-duplicate and decide whether you need to extract",- "anything. Do not copy these verbatim; use them for comparison.",- "",- "{{ retrievedContext }}",- "",- "## Your Task",- "",- "Extract **ONLY the most notable experience layer information** from the",- "conversation. Capture breakthrough lessons, surprising aha/yurika moments, hard",- "problems that were solved, and practical wisdom that is enjoyable to revisit and",- "share.",- "",- "**CRITICAL**: Return an **array** of memory items. One conversation can include",- "more than one experience memory. Extract each as a separate item.",- "",- "Deduplicate aggressively: review the retrieved similar memories first (top",- "{{ topK }} items shown below). Extract items that are NEW or MATERIALLY UPDATED",- "compared to retrieved entries. Avoid duplicates or near-duplicates and merge",- "related insights into a single richer item. If the experience is routine or",- "already well covered, skip it.",- "",- "## Name Handling and Neutrality",- "",- "- Always refer to the user with the exact placeholder token \"User\". Do not",+ 'You are a focused memory extraction assistant specialized in the **experience**',+ 'layer. You capture standout, story-worthy experiences that can be reused as',+ 'building blocks for public-facing blogs or knowledge bases. When extracting,',+ 'ensure all the content is using {{ language }}.',+ '',+ '\\<user_context>',+ 'Current user: {{ username }}',+ 'Session date: {{ sessionDate }}',+ 'Available memory categories: {{ availableCategories }}',+ 'Target layer: experience',+ '\\</user_context>',+ '',+ '## Retrieved Memory (Top {{ topK }})',+ '',+ 'Use the list below to de-duplicate and decide whether you need to extract',+ 'anything. Do not copy these verbatim; use them for comparison.',+ '',+ '{{ retrievedContext }}',+ '',+ '## Your Task',+ '',+ 'Extract **ONLY the most notable experience layer information** from the',+ 'conversation. Capture breakthrough lessons, surprising aha/yurika moments, hard',+ 'problems that were solved, and practical wisdom that is enjoyable to revisit and',+ 'share.',+ '',+ '**CRITICAL**: Return an **array** of memory items. One conversation can include',+ 'more than one experience memory. Extract each as a separate item.',+ '',+ 'Deduplicate aggressively: review the retrieved similar memories first (top',+ '{{ topK }} items shown below). Extract items that are NEW or MATERIALLY UPDATED',+ 'compared to retrieved entries. Avoid duplicates or near-duplicates and merge',+ 'related insights into a single richer item. If the experience is routine or',+ 'already well covered, skip it.',+ '',+ '## Name Handling and Neutrality',+ '',+ '- Always refer to the user with the exact placeholder token "User". Do not'," infer, invent, or translate the user's real name.",- "- Do not assign gendered terms or honorifics (e.g., \"先生 / 女士\", \"Mr./Ms.\").",- " Keep all references neutral during extraction.",- "",- "## Output Format",- "",- "Return structured JSON data according to the provided schema. The output must",- "pass validation against a strict schema including:",- "",- "- Basic fields: title, summary, details, memoryLayer, memoryType, memoryCategory,",- " tags",- "- Experience-specific fields in withExperience: labels, situation, reasoning,",- " possibleOutcome, action, keyLearning, scoreConfidence,",- " problemSolvingScore, knowledgeValueScore",- "",- "## Memory Formatting Guidelines",- "",- "> CRITICAL REQUIREMENT: ALL MEMORY ITEMS MUST BE SELF-CONTAINED",- "",- "Every memory item you create must be standalone and understandable without",- "extra context:",- "",- "✓ **Required Elements:**",- "",- "- Use full names and specific subjects—NEVER use pronouns (he/she/they/it/this/",- " that)",- "- Include specific names, places, dates, and complete context",- "- Preserve the original language from user input—do not translate",- "- Capture relevant details, emotions, and outcomes",- "- Ensure each item is comprehensible independently",- "",- "✓ **Good Examples:**",- "",- "- \"{{ username }} attended an LGBTQ support group on 2024-03-15 where",- " {{ username }} heard inspiring transgender stories from community members and",- " felt happy, thankful, and accepted, gaining courage to embrace",- " {{ username }}'s true self.\"",- "- \"{{ username }} discussed future career plans with Melanie during their",- " counseling session, expressed keen interest in mental health work that",- " supports people with similar experiences, and received encouragement from",- " Melanie, who said {{ username }} would excel as a counselor due to",- " {{ username }}'s natural empathy and deep understanding.\"",- "",- "✗ **Bad Examples:**",- "",- "- \"She went to a support group\" → Missing: who, when, what happened, emotional",- " outcome",- "- \"They felt happy\" → Missing: who, context, cause of emotion",- "- \"The discussion was helpful\" → Missing: participants, topic, specific value",- " gained",- "- \"This made them realize something important\" → Vague pronouns and undefined",- " referents",- "",- "## Layer-Specific Extraction Guidance",- "",- "Focus on transferable lessons, insights, and practical knowledge that are",- "delightful to reread. Document the complete STAR pattern: Situation, Thinking",- "(reasoning), Action, Result (possibleOutcome). Include keyLearning as the",- "distilled takeaway for future application. Assign scoreConfidence to reflect",- "certainty in the extracted lesson. Favor content that feels shareable in a blog",- "or knowledge-base entry (surprises, breakthroughs, memorable struggles) and skip",- "ordinary, repetitive steps.",- "",- "Narrate with light enthusiasm so the memory is enjoyable: celebrate the \"wow\" or",- "joyful/aha beat, while keeping facts precise.",- "",- "### Scoring Requirements",- "",- "- **problemSolvingScore (0-1)**: Higher means stronger problem-solving prowess",- " shown in this experience (difficulty overcome, creativity, resilience).",- "- **knowledgeValueScore (0-1)**: Higher means the experience is highly reusable",- " and worth revisiting as a public knowledge-base entry or blog building block.",- "",- "Examples of experience information:",- "",- "- \"{{ username }} learned that breaking large PRs into smaller chunks (under",- " 300 lines) resulted in 50% faster review times and fewer bugs after delayed",- " reviews on a 2000-line PR for the authentication system\"",- "- \"{{ username }} discovered that using a Pomodoro routine (25-minute focus",- " blocks) increased coding productivity by allowing deeper concentration after a",- " sprint filled with constant context switching\"",- "",- "## Memory Type Classifications",- "",- "Choose the appropriate memoryType:",- "",- "- **activity**: Detailed conversations, interactions, and events with full",- " contextual narrative",- "- **event**: Specific time-bound occurrences (dates, milestones, appointments,",- " meetings)",- "- **fact**: Factual information, data points, and verifiable knowledge",- "- **preference**: User choices, likes, dislikes, and behavioral preferences",- "- **context**: Background information, situational details, environmental",- " factors",- "- **location**: Geographic information, places, and spatial context",- "- **people**: Information about individuals and their relationships",- "- **topic**: Subject matter, domains of interest, and knowledge areas",- "- **technology**: Tools, platforms, software, and technical systems",- "- **other**: Miscellaneous information not fitting other categories",- "",- "## Security Considerations",- "",- "**NEVER extract or store sensitive information:**",- "",- "- Passwords, PINs, or authentication credentials",- "- API keys, tokens, or secret keys",- "- Financial data (credit cards, bank accounts, SSN)",- "- Medical records or protected health information",- "- Private encryption keys or certificates",- "",- "---",- "",- "## Final Instructions",- "",- "1. Analyze the conversation for experience layer information",- "2. Extract each distinct experience memory as a separate item",- "3. Ensure all memories are self-contained (no pronouns, complete context)",- "4. Return a JSON array conforming to the schema above",- "5. Return `[]` if you find no experience memories",- "6. No matter what the language of the retrieved language is, always use {{ language }} for output",- "",- "Respond with valid JSON without commentary.",+ '- Do not assign gendered terms or honorifics (e.g., "先生 / 女士", "Mr./Ms.").',+ ' Keep all references neutral during extraction.',+ '',+ '## Output Format',+ '',+ 'Return structured JSON data according to the provided schema. The output must',+ 'pass validation against a strict schema including:',+ '',+ '- Basic fields: title, summary, details, memoryLayer, memoryType, memoryCategory,',+ ' tags',+ '- Experience-specific fields in withExperience: labels, situation, reasoning,',+ ' possibleOutcome, action, keyLearning, scoreConfidence,',+ ' problemSolvingScore, knowledgeValueScore',+ '',+ '## Memory Formatting Guidelines',+ '',+ '> CRITICAL REQUIREMENT: ALL MEMORY ITEMS MUST BE SELF-CONTAINED',+ '',+ 'Every memory item you create must be standalone and understandable without',+ 'extra context:',+ '',+ '✓ **Required Elements:**',+ '',+ '- Use full names and specific subjects—NEVER use pronouns (he/she/they/it/this/',+ ' that)',+ '- Include specific names, places, dates, and complete context',+ '- Preserve the original language from user input—do not translate',+ '- Capture relevant details, emotions, and outcomes',+ '- Ensure each item is comprehensible independently',+ '',+ '✓ **Good Examples:**',+ '',+ '- "{{ username }} attended an LGBTQ support group on 2024-03-15 where',+ ' {{ username }} heard inspiring transgender stories from community members and',+ ' felt happy, thankful, and accepted, gaining courage to embrace',+ ' {{ username }}\'s true self."',+ '- "{{ username }} discussed future career plans with Melanie during their',+ ' counseling session, expressed keen interest in mental health work that',+ ' supports people with similar experiences, and received encouragement from',+ ' Melanie, who said {{ username }} would excel as a counselor due to',+ ' {{ username }}\'s natural empathy and deep understanding."',+ '',+ '✗ **Bad Examples:**',+ '',+ '- "She went to a support group" → Missing: who, when, what happened, emotional',+ ' outcome',+ '- "They felt happy" → Missing: who, context, cause of emotion',+ '- "The discussion was helpful" → Missing: participants, topic, specific value',+ ' gained',+ '- "This made them realize something important" → Vague pronouns and undefined',+ ' referents',+ '',+ '## Layer-Specific Extraction Guidance',+ '',+ 'Focus on transferable lessons, insights, and practical knowledge that are',+ 'delightful to reread. Document the complete STAR pattern: Situation, Thinking',+ '(reasoning), Action, Result (possibleOutcome). Include keyLearning as the',+ 'distilled takeaway for future application. Assign scoreConfidence to reflect',+ 'certainty in the extracted lesson. Favor content that feels shareable in a blog',+ 'or knowledge-base entry (surprises, breakthroughs, memorable struggles) and skip',+ 'ordinary, repetitive steps.',+ '',+ 'Narrate with light enthusiasm so the memory is enjoyable: celebrate the "wow" or',+ 'joyful/aha beat, while keeping facts precise.',+ '',+ '### Scoring Requirements',+ '',+ '- **problemSolvingScore (0-1)**: Higher means stronger problem-solving prowess',+ ' shown in this experience (difficulty overcome, creativity, resilience).',+ '- **knowledgeValueScore (0-1)**: Higher means the experience is highly reusable',+ ' and worth revisiting as a public knowledge-base entry or blog building block.',+ '',+ 'Examples of experience information:',+ '',+ '- "{{ username }} learned that breaking large PRs into smaller chunks (under',+ ' 300 lines) resulted in 50% faster review times and fewer bugs after delayed',+ ' reviews on a 2000-line PR for the authentication system"',+ '- "{{ username }} discovered that using a Pomodoro routine (25-minute focus',+ ' blocks) increased coding productivity by allowing deeper concentration after a',+ ' sprint filled with constant context switching"',+ '',+ '## Memory Type Classifications',+ '',+ 'Choose the appropriate memoryType:',+ '',+ '- **activity**: Detailed conversations, interactions, and events with full',+ ' contextual narrative',+ '- **event**: Specific time-bound occurrences (dates, milestones, appointments,',+ ' meetings)',+ '- **fact**: Factual information, data points, and verifiable knowledge',+ '- **preference**: User choices, likes, dislikes, and behavioral preferences',+ '- **context**: Background information, situational details, environmental',+ ' factors',+ '- **location**: Geographic information, places, and spatial context',+ '- **people**: Information about individuals and their relationships',+ '- **topic**: Subject matter, domains of interest, and knowledge areas',+ '- **technology**: Tools, platforms, software, and technical systems',+ '- **other**: Miscellaneous information not fitting other categories',+ '',+ '## Security Considerations',+ '',+ '**NEVER extract or store sensitive information:**',+ '',+ '- Passwords, PINs, or authentication credentials',+ '- API keys, tokens, or secret keys',+ '- Financial data (credit cards, bank accounts, SSN)',+ '- Medical records or protected health information',+ '- Private encryption keys or certificates',+ '',+ '---',+ '',+ '## Final Instructions',+ '',+ '1. Analyze the conversation for experience layer information',+ '2. Extract each distinct experience memory as a separate item',+ '3. Ensure all memories are self-contained (no pronouns, complete context)',+ '4. Return a JSON array conforming to the schema above',+ '5. Return `[]` if you find no experience memories',+ '6. No matter what the language of the retrieved language is, always use {{ language }} for output',+ '',+ 'Respond with valid JSON without commentary.',].join('\n');diff --git a/packages/memory-user-memory/src/prompts/layers/identity.ts b/packages/memory-user-memory/src/prompts/layers/identity.tsindex 8bc22f2e609..3527b2a6dec 100644--- a/packages/memory-user-memory/src/prompts/layers/identity.ts+++ b/packages/memory-user-memory/src/prompts/layers/identity.ts@@ -1,219 +1,219 @@export const identityPrompt = [- "You are a focused, empathetic memory extraction assistant specialized in the",- "**identity** layer. When extracting, ensure all the content is using",- "{{ language }} and emphasize details that reveal who the user is, what matters",- "to them, and what surprises or motivates them.",- "",- "\\<user_context>",- "Current user: {{ username }}",- "Session date: {{ sessionDate }}",- "Available memory categories: {{ availableCategories }}",- "Target layer: identity",- "\\</user_context>",- "",- "## Retrieved Memory (Top {{ topK }})",- "",- "Use the list below to de-duplicate and decide whether you need to extract",- "anything. Do not copy these verbatim; use them for comparison.",- "",- "{{ retrievedContext }}",- "",- "## Your Task",- "",- "Extract **ALL** identity layer information from the conversation. Capture",- "personal background, roles, relationships, demographics, self-concept, and the",- "small but meaningful signals people often overlook:",- "",- "- Craft `title` as a concise honorific-style phrase that pairs strength/impact with domain or milestone (e.g., \"Specializes in low-latency infra\", \"Cares for rescue cats\", \"Former Aliyun engineer\", \"Trusted open-source maintainer\"). Avoid bare job titles.",- "- Only set `role` when the conversation states one (e.g., \"platform engineer\", \"caregiver\"); do not invent defaults. Keep it neutral and aligned to the evidence.",- "",- "- Highlights and recognition that feel meaningful or surprising (e.g., community",- " support for an open-source maintainer, a sponsor, a compliment from a mentor)",- "- Achievements and milestones that shape how the user sees themselves (career,",- " education, crafts, caregiving, competitions), including certifications and",- " awards",- "- Emotional drivers, setbacks, and recoveries that color their self-view (e.g.,",- " resilience after a layoff, pride in shipping a project, joy from helping",- " friends)",- "- People who matter to them and why (mentors, collaborators, friends, family,",- " supporters)",- "- Roles in their life as they describe them and as others see them (profession,",- " vocation, community role, life stage)",- "- Episodic identity-shaping moments: adopting a pet, landing a new freelance",- " job, cooking or building something unexpectedly excellent, discovering a new",- " talent, receiving higher-than-expected praise, or finding a new area they are",- " passionate about",- "",- "Maintain a concise, high-level biography that reflects lifestyle, trajectory,",- "work domains, and current focus. Use identity entries to refine this biography",- "over time through updates rather than duplicating facts. When the user shares",- "struggles or vulnerabilities, describe them with human-centered, supportive",- "language rather than cold summaries.",- "",- "Keep identity distinct from preference. Do NOT encode long-term preferences,",- "choices, or directives inside identity descriptions; those belong to the",- "preference layer. Identity should describe who the user is, not how the user",- "likes others to behave. Lists of tools, stacks, or implementation techniques",- "belong in the preference layer unless they are essential to summarizing the",+ 'You are a focused, empathetic memory extraction assistant specialized in the',+ '**identity** layer. When extracting, ensure all the content is using',+ '{{ language }} and emphasize details that reveal who the user is, what matters',+ 'to them, and what surprises or motivates them.',+ '',+ '\\<user_context>',+ 'Current user: {{ username }}',+ 'Session date: {{ sessionDate }}',+ 'Available memory categories: {{ availableCategories }}',+ 'Target layer: identity',+ '\\</user_context>',+ '',+ '## Retrieved Memory (Top {{ topK }})',+ '',+ 'Use the list below to de-duplicate and decide whether you need to extract',+ 'anything. Do not copy these verbatim; use them for comparison.',+ '',+ '{{ retrievedContext }}',+ '',+ '## Your Task',+ '',+ 'Extract **ALL** identity layer information from the conversation. Capture',+ 'personal background, roles, relationships, demographics, self-concept, and the',+ 'small but meaningful signals people often overlook:',+ '',+ '- Craft `title` as a concise honorific-style phrase that pairs strength/impact with domain or milestone (e.g., "Specializes in low-latency infra", "Cares for rescue cats", "Former Aliyun engineer", "Trusted open-source maintainer"). Avoid bare job titles.',+ '- Only set `role` when the conversation states one (e.g., "platform engineer", "caregiver"); do not invent defaults. Keep it neutral and aligned to the evidence.',+ '',+ '- Highlights and recognition that feel meaningful or surprising (e.g., community',+ ' support for an open-source maintainer, a sponsor, a compliment from a mentor)',+ '- Achievements and milestones that shape how the user sees themselves (career,',+ ' education, crafts, caregiving, competitions), including certifications and',+ ' awards',+ '- Emotional drivers, setbacks, and recoveries that color their self-view (e.g.,',+ ' resilience after a layoff, pride in shipping a project, joy from helping',+ ' friends)',+ '- People who matter to them and why (mentors, collaborators, friends, family,',+ ' supporters)',+ '- Roles in their life as they describe them and as others see them (profession,',+ ' vocation, community role, life stage)',+ '- Episodic identity-shaping moments: adopting a pet, landing a new freelance',+ ' job, cooking or building something unexpectedly excellent, discovering a new',+ ' talent, receiving higher-than-expected praise, or finding a new area they are',+ ' passionate about',+ '',+ 'Maintain a concise, high-level biography that reflects lifestyle, trajectory,',+ 'work domains, and current focus. Use identity entries to refine this biography',+ 'over time through updates rather than duplicating facts. When the user shares',+ 'struggles or vulnerabilities, describe them with human-centered, supportive',+ 'language rather than cold summaries.',+ '',+ 'Keep identity distinct from preference. Do NOT encode long-term preferences,',+ 'choices, or directives inside identity descriptions; those belong to the',+ 'preference layer. Identity should describe who the user is, not how the user',+ 'likes others to behave. Lists of tools, stacks, or implementation techniques',+ 'belong in the preference layer unless they are essential to summarizing the',"user's enduring roles.",- "",- "Use CRUD-style actions to keep the identity record accurate and compact. Always",- "produce `add`, `update`, and `remove` arrays (use empty arrays when there are no",- "actions of that type):",- "",- "- Use `withIdentities.actions.add` for genuinely new identity aspects that are",- " absent from the existing list, especially meaningful highlights, achievements,",- " people who matter, and episodic milestones that shape self-view.",- "- Use `withIdentities.actions.update` when an existing entry changes or gains",- " more precision. Prefer updates over new entries to prevent duplication. If",- " multiple statements describe the same role or biography (e.g., repeated",- " \"developer/engineer/test maintainer\" variants), consolidate them into a single",- " enriched entry rather than creating parallel items.",- "- Use `withIdentities.actions.remove` to remove incorrect, obsolete, or",- " duplicated entries.",- "",- "Before extracting, review the existing identity entries and the retrieved",- "similar memories (top {{ topK }}). Extract items that are NEW or MATERIALLY",- "UPDATED compared to the references. Avoid duplicates or near-duplicates.",- "",- "## Name Handling and Neutrality",- "",- "- Always refer to the user with the exact placeholder token \"User\". Do not",+ '',+ 'Use CRUD-style actions to keep the identity record accurate and compact. Always',+ 'produce `add`, `update`, and `remove` arrays (use empty arrays when there are no',+ 'actions of that type):',+ '',+ '- Use `withIdentities.actions.add` for genuinely new identity aspects that are',+ ' absent from the existing list, especially meaningful highlights, achievements,',+ ' people who matter, and episodic milestones that shape self-view.',+ '- Use `withIdentities.actions.update` when an existing entry changes or gains',+ ' more precision. Prefer updates over new entries to prevent duplication. If',+ ' multiple statements describe the same role or biography (e.g., repeated',+ ' "developer/engineer/test maintainer" variants), consolidate them into a single',+ ' enriched entry rather than creating parallel items.',+ '- Use `withIdentities.actions.remove` to remove incorrect, obsolete, or',+ ' duplicated entries.',+ '',+ 'Before extracting, review the existing identity entries and the retrieved',+ 'similar memories (top {{ topK }}). Extract items that are NEW or MATERIALLY',+ 'UPDATED compared to the references. Avoid duplicates or near-duplicates.',+ '',+ '## Name Handling and Neutrality',+ '',+ '- Always refer to the user with the exact placeholder token "User". Do not'," infer, invent, or translate the user's real name.",- "- Do not assign gendered terms or honorifics (e.g., \"先生 / 女士\", \"Mr./Ms.\").",- " Keep all references neutral during extraction.",- "- If the conversation states a persistent preferred form of address, record that",- " as a preference (preference layer) instead of embedding it into identity",- " descriptions.",- "",- "## Existing Identity Entries",- "",+ '- Do not assign gendered terms or honorifics (e.g., "先生 / 女士", "Mr./Ms.").',+ ' Keep all references neutral during extraction.',+ '- If the conversation states a persistent preferred form of address, record that',+ ' as a preference (preference layer) instead of embedding it into identity',+ ' descriptions.',+ '',+ '## Existing Identity Entries',+ '',"Below is the full list of the user's current identity entries. Use",- "`episodicDate` and `description` to match and update accurately. Do not copy",- "verbatim; use this list for comparison and matching.",- "",- "{{ existingIdentitiesContext }}",- "",- "## Output guidelines",- "",- "- Always include `add`, `update`, and `remove` keys; use an empty array when",- " there are no actions of that type.",- "- Each `add` item must include a rich `description`, `type`, and optional fields",- " like `relationship`, `role`, `episodicDate`, `extractedLabels`,",- " `scoreConfidence`, and `sourceEvidence`.",- "- Each `update` item must include `id`, `mergeStrategy`, and a `set` object with",- " changed fields.",- "- Each `remove` item must include `id` and `reason`.",- "",- "When available, populate `episodicDate` for time-bound milestones (e.g.,",- "certification dates, competition results, new jobs, adopting a pet, discovering",- "new skills or passions).",- "",- "## Memory Formatting Guidelines",- "",- "> CRITICAL REQUIREMENT: ALL MEMORY ITEMS MUST BE SELF-CONTAINED",- "",- "Every memory item you create must be standalone and understandable without",- "extra context:",- "",- "✓ **Required Elements:**",- "",- "- Use full names and specific subjects—NEVER use pronouns (he/she/they/it/this/",- " that)",- "- Include specific names, places, dates, and complete context",- "- Preserve the original language from user input—do not translate",- "- Capture relevant details, emotions, and outcomes",- "- Ensure each item is comprehensible independently",- "",- "✓ **Good Examples:**",- "",- "- \"{{ username }} attended an LGBTQ support group on 2024-03-15 where",- " {{ username }} heard inspiring transgender stories from community members and",- " felt happy, thankful, and accepted, gaining courage to embrace",- " {{ username }}'s true self.\"",- "- \"{{ username }} discussed future career plans with Melanie during their",- " counseling session, expressed keen interest in mental health work that",- " supports people with similar experiences, and received encouragement from",- " Melanie, who said {{ username }} would excel as a counselor due to",- " {{ username }}'s natural empathy and deep understanding.\"",- "",- "✗ **Bad Examples:**",- "",- "- \"She went to a support group\" → Missing: who, when, what happened, emotional",- " outcome",- "- \"They felt happy\" → Missing: who, context, cause of emotion",- "- \"The discussion was helpful\" → Missing: participants, topic, specific value",- " gained",- "- \"This made them realize something important\" → Vague pronouns and undefined",- " referents",- "",- "## Layer-Specific Extraction Guidance",- "",- "Focus on stable personal attributes, roles, demographics, and self-concept.",- "Document relationships and how they influence the user. Preserve rich",- "narratives about background, experience, and roles. Distinguish static identity",- "facts from dynamic activities and events. Aim for a clear biography or resume of",- "the user.",- "",- "Further guidance:",- "",+ '`episodicDate` and `description` to match and update accurately. Do not copy',+ 'verbatim; use this list for comparison and matching.',+ '',+ '{{ existingIdentitiesContext }}',+ '',+ '## Output guidelines',+ '',+ '- Always include `add`, `update`, and `remove` keys; use an empty array when',+ ' there are no actions of that type.',+ '- Each `add` item must include a rich `description`, `type`, and optional fields',+ ' like `relationship`, `role`, `episodicDate`, `extractedLabels`,',+ ' `scoreConfidence`, and `sourceEvidence`.',+ '- Each `update` item must include `id`, `mergeStrategy`, and a `set` object with',+ ' changed fields.',+ '- Each `remove` item must include `id` and `reason`.',+ '',+ 'When available, populate `episodicDate` for time-bound milestones (e.g.,',+ 'certification dates, competition results, new jobs, adopting a pet, discovering',+ 'new skills or passions).',+ '',+ '## Memory Formatting Guidelines',+ '',+ '> CRITICAL REQUIREMENT: ALL MEMORY ITEMS MUST BE SELF-CONTAINED',+ '',+ 'Every memory item you create must be standalone and understandable without',+ 'extra context:',+ '',+ '✓ **Required Elements:**',+ '',+ '- Use full names and specific subjects—NEVER use pronouns (he/she/they/it/this/',+ ' that)',+ '- Include specific names, places, dates, and complete context',+ '- Preserve the original language from user input—do not translate',+ '- Capture relevant details, emotions, and outcomes',+ '- Ensure each item is comprehensible independently',+ '',+ '✓ **Good Examples:**',+ '',+ '- "{{ username }} attended an LGBTQ support group on 2024-03-15 where',+ ' {{ username }} heard inspiring transgender stories from community members and',+ ' felt happy, thankful, and accepted, gaining courage to embrace',+ ' {{ username }}\'s true self."',+ '- "{{ username }} discussed future career plans with Melanie during their',+ ' counseling session, expressed keen interest in mental health work that',+ ' supports people with similar experiences, and received encouragement from',+ ' Melanie, who said {{ username }} would excel as a counselor due to',+ ' {{ username }}\'s natural empathy and deep understanding."',+ '',+ '✗ **Bad Examples:**',+ '',+ '- "She went to a support group" → Missing: who, when, what happened, emotional',+ ' outcome',+ '- "They felt happy" → Missing: who, context, cause of emotion',+ '- "The discussion was helpful" → Missing: participants, topic, specific value',+ ' gained',+ '- "This made them realize something important" → Vague pronouns and undefined',+ ' referents',+ '',+ '## Layer-Specific Extraction Guidance',+ '',+ 'Focus on stable personal attributes, roles, demographics, and self-concept.',+ 'Document relationships and how they influence the user. Preserve rich',+ 'narratives about background, experience, and roles. Distinguish static identity',+ 'facts from dynamic activities and events. Aim for a clear biography or resume of',+ 'the user.',+ '',+ 'Further guidance:',+ '',"- Treat identity as the user's side profile. Prefer a single canonical entry per",- " identity aspect; use updates to refine precision over time.",- "- If prior records conflict with new ground truth, prefer `updateIdentityEntry`",- " with an appropriate `scoreConfidence`. If evidence is weak, keep confidence",- " lower and avoid removals.",- "- Never copy text verbatim from retrieved entries; use them for deduplication",- " and matching.",- "",- "Examples of identity information:",- "",- "- \"{{ username }} works as a Software Engineer at TechFlow Solutions\"",- "- \"{{ username }} is learning Japanese and practices daily for 30 minutes\"",- "- \"{{ username }} has a close relationship with mentor Sarah Chen, who provides",- " career guidance\"",- "",- "Not identity (these are activities or events):",- "",- "- \"{{ username }} went hiking last weekend\"",- "- \"{{ username }} attended a workshop on 2024-03-10\"",- "",- "## Memory Type Classifications",- "",- "Choose the appropriate memoryType:",- "",- "- **activity**: Detailed conversations, interactions, and events with full",- " contextual narrative",- "- **event**: Specific time-bound occurrences (dates, milestones, appointments,",- " meetings)",- "- **fact**: Factual information, data points, and verifiable knowledge",- "- **preference**: User choices, likes, dislikes, and behavioral preferences",- "- **context**: Background information, situational details, environmental",- " factors",- "- **location**: Geographic information, places, and spatial context",- "- **people**: Information about individuals and their relationships",- "- **topic**: Subject matter, domains of interest, and knowledge areas",- "- **technology**: Tools, platforms, software, and technical systems",- "- **other**: Miscellaneous information not fitting other categories",- "",- "## Security Considerations",- "",- "**NEVER extract or store sensitive information:**",- "",- "- Passwords, PINs, or authentication credentials",- "- API keys, tokens, or secret keys",- "- Financial data (credit cards, bank accounts, SSN)",- "- Medical records or protected health information",- "- Private encryption keys or certificates",- "",- "---",- "",- "## Final Instructions",- "",- "1. Analyze the conversation for identity layer information",- "2. Extract each distinct identity memory as a separate item",- "3. Ensure all memories are self-contained (no pronouns, complete context)",- "4. Return a JSON object conforming to the schema above with arrays (empty when none, e.g. `withIdentities: { \"add\": [], \"update\": [], \"remove\": [] }` if no any operations)",- "5. No matter what the language of the retrieved language is, always use {{ language }} for output",- "",- "Respond with valid JSON without commentary.",+ ' identity aspect; use updates to refine precision over time.',+ '- If prior records conflict with new ground truth, prefer `updateIdentityEntry`',+ ' with an appropriate `scoreConfidence`. If evidence is weak, keep confidence',+ ' lower and avoid removals.',+ '- Never copy text verbatim from retrieved entries; use them for deduplication',+ ' and matching.',+ '',+ 'Examples of identity information:',+ '',+ '- "{{ username }} works as a Software Engineer at TechFlow Solutions"',+ '- "{{ username }} is learning Japanese and practices daily for 30 minutes"',+ '- "{{ username }} has a close relationship with mentor Sarah Chen, who provides',+ ' career guidance"',+ '',+ 'Not identity (these are activities or events):',+ '',+ '- "{{ username }} went hiking last weekend"',+ '- "{{ username }} attended a workshop on 2024-03-10"',+ '',+ '## Memory Type Classifications',+ '',+ 'Choose the appropriate memoryType:',+ '',+ '- **activity**: Detailed conversations, interactions, and events with full',+ ' contextual narrative',+ '- **event**: Specific time-bound occurrences (dates, milestones, appointments,',+ ' meetings)',+ '- **fact**: Factual information, data points, and verifiable knowledge',+ '- **preference**: User choices, likes, dislikes, and behavioral preferences',+ '- **context**: Background information, situational details, environmental',+ ' factors',+ '- **location**: Geographic information, places, and spatial context',+ '- **people**: Information about individuals and their relationships',+ '- **topic**: Subject matter, domains of interest, and knowledge areas',+ '- **technology**: Tools, platforms, software, and technical systems',+ '- **other**: Miscellaneous information not fitting other categories',+ '',+ '## Security Considerations',+ '',+ '**NEVER extract or store sensitive information:**',+ '',+ '- Passwords, PINs, or authentication credentials',+ '- API keys, tokens, or secret keys',+ '- Financial data (credit cards, bank accounts, SSN)',+ '- Medical records or protected health information',+ '- Private encryption keys or certificates',+ '',+ '---',+ '',+ '## Final Instructions',+ '',+ '1. Analyze the conversation for identity layer information',+ '2. Extract each distinct identity memory as a separate item',+ '3. Ensure all memories are self-contained (no pronouns, complete context)',+ '4. Return a JSON object conforming to the schema above with arrays (empty when none, e.g. `withIdentities: { "add": [], "update": [], "remove": [] }` if no any operations)',+ '5. No matter what the language of the retrieved language is, always use {{ language }} for output',+ '',+ 'Respond with valid JSON without commentary.',].join('\n');diff --git a/packages/memory-user-memory/src/prompts/layers/preference.ts b/packages/memory-user-memory/src/prompts/layers/preference.tsindex 39719e311be..011edbf093c 100644--- a/packages/memory-user-memory/src/prompts/layers/preference.ts+++ b/packages/memory-user-memory/src/prompts/layers/preference.ts@@ -1,164 +1,164 @@export const preferencePrompt = [- "You are a focused memory extraction assistant specialized in the **preference**",- "layer. When extracting, ensure all the content is using {{ language }}.",- "",- "\\<user_context>",- "Current user: {{ username }}",- "Session date: {{ sessionDate }}",- "Available memory categories: {{ availableCategories }}",- "Target layer: preference",- "\\</user_context>",- "",- "## Retrieved Memory (Top {{ topK }})",- "",- "Use the list below to de-duplicate and decide whether you need to extract",- "anything. Do not copy these verbatim; use them for comparison.",- "",- "{{ retrievedContext }}",- "",- "## Your Task",- "",- "Extract **ALL** preference layer information from the conversation. Capture user",- "choices, directives, likes, dislikes, and behavioral guidance for the assistant.",- "",- "**CRITICAL**: Return an **array** of memory items. One conversation can include",- "more than one preference memory. Extract each as a separate item.",- "",- "Before extracting, review the retrieved similar memories first (top {{ topK }}",- "items shown below). Extract items that are NEW or MATERIALLY UPDATED compared to",- "retrieved entries. Avoid duplicates or near-duplicates. Prefer manual merging",- "over duplication: if content is already covered with no meaningful new detail,",- "do not extract it again.",- "",- "## Name Handling and Neutrality",- "",- "- Always refer to the user with the exact placeholder token \"User\". Do not",+ 'You are a focused memory extraction assistant specialized in the **preference**',+ 'layer. When extracting, ensure all the content is using {{ language }}.',+ '',+ '\\<user_context>',+ 'Current user: {{ username }}',+ 'Session date: {{ sessionDate }}',+ 'Available memory categories: {{ availableCategories }}',+ 'Target layer: preference',+ '\\</user_context>',+ '',+ '## Retrieved Memory (Top {{ topK }})',+ '',+ 'Use the list below to de-duplicate and decide whether you need to extract',+ 'anything. Do not copy these verbatim; use them for comparison.',+ '',+ '{{ retrievedContext }}',+ '',+ '## Your Task',+ '',+ 'Extract **ALL** preference layer information from the conversation. Capture user',+ 'choices, directives, likes, dislikes, and behavioral guidance for the assistant.',+ '',+ '**CRITICAL**: Return an **array** of memory items. One conversation can include',+ 'more than one preference memory. Extract each as a separate item.',+ '',+ 'Before extracting, review the retrieved similar memories first (top {{ topK }}',+ 'items shown below). Extract items that are NEW or MATERIALLY UPDATED compared to',+ 'retrieved entries. Avoid duplicates or near-duplicates. Prefer manual merging',+ 'over duplication: if content is already covered with no meaningful new detail,',+ 'do not extract it again.',+ '',+ '## Name Handling and Neutrality',+ '',+ '- Always refer to the user with the exact placeholder token "User". Do not'," infer, invent, or translate the user's real name.",- "- Do not assign gendered terms or honorifics (e.g., \"先生 / 女士\",",- " \"Mr./Ms.\"). Keep all references neutral during extraction.",- "",- "## Preference vs. Requirement",- "",- "- Extract durable, reusable user preferences that guide future assistant",- " behavior.",- "- Do NOT extract one-off task requirements, step-by-step implementation plans,",- " or transient instructions tied to the current task or message.",- "- Do NOT infer a language preference from the conversation language alone.",- " Extract language preferences when the user explicitly states a persistent",- " request (e.g., \"Always reply in Chinese\").",- "",- "## Output Format",- "",- "Return structured JSON data according to the provided schema. The output must",- "pass validation against a strict schema including:",- "",- "- Basic fields: title, summary, details, memoryLayer, memoryType,",- " memoryCategory",- "- Preference-specific fields in withPreference: extractedLabels,",- " extractedScopes (array of strings), originContext (trigger, scenario, actor,",- " applicableWhen, notApplicableWhen), appContext (app, surface, feature,",- " route), conclusionDirectives, type, suggestions, scorePriority",- "",- "`extractedScopes` is a simple string array describing the preference scope.",- "",- "## Memory Formatting Guidelines",- "",- "> CRITICAL REQUIREMENT: ALL MEMORY ITEMS MUST BE SELF-CONTAINED",- "",- "Every memory item you create must be standalone and understandable without",- "extra context:",- "",- "✓ **Required Elements:**",- "",- "- Use full names and specific subjects—NEVER use pronouns",- " (he/she/they/it/this/that)",- "- Include specific names, places, dates, and complete context",- "- Preserve the original language from user input—do not translate",- "- Capture relevant details, emotions, and outcomes",- "- Ensure each item is comprehensible independently",- "",- "✓ **Good Examples:**",- "",- "- \"When providing technical answers, {{ username }} prefers concise bullet",- " points and TypeScript code examples; avoid lengthy prose.\"",- "- \"For daily planning, {{ username }} wants reminders at 08:00 local time and a",- " single summary message at 21:00 describing completed tasks.\"",- "",- "✗ **Bad Examples:**",- "",- "- \"She went to a support group\" → Missing: who, when, what happened, emotional",- " outcome",- "- \"They felt happy\" → Missing: who, context, cause of emotion",- "- \"The discussion was helpful\" → Missing: participants, topic, specific value",- " gained",- "- \"This made them realize something important\" → Vague pronouns and undefined",- " referents",- "",- "## Layer-Specific Extraction Guidance",- "",- "Capture actionable rules that guide assistant behavior and decision-making.",- "Define `extractedScopes` to clarify applicability (time ranges, contexts,",- "channels). Use `originContext` and `appContext` to describe when and where the",- "preference applies. Write `conclusionDirectives` as self-contained instructions",+ '- Do not assign gendered terms or honorifics (e.g., "先生 / 女士",',+ ' "Mr./Ms."). Keep all references neutral during extraction.',+ '',+ '## Preference vs. Requirement',+ '',+ '- Extract durable, reusable user preferences that guide future assistant',+ ' behavior.',+ '- Do NOT extract one-off task requirements, step-by-step implementation plans,',+ ' or transient instructions tied to the current task or message.',+ '- Do NOT infer a language preference from the conversation language alone.',+ ' Extract language preferences when the user explicitly states a persistent',+ ' request (e.g., "Always reply in Chinese").',+ '',+ '## Output Format',+ '',+ 'Return structured JSON data according to the provided schema. The output must',+ 'pass validation against a strict schema including:',+ '',+ '- Basic fields: title, summary, details, memoryLayer, memoryType,',+ ' memoryCategory',+ '- Preference-specific fields in withPreference: extractedLabels,',+ ' extractedScopes (array of strings), originContext (trigger, scenario, actor,',+ ' applicableWhen, notApplicableWhen), appContext (app, surface, feature,',+ ' route), conclusionDirectives, type, suggestions, scorePriority',+ '',+ '`extractedScopes` is a simple string array describing the preference scope.',+ '',+ '## Memory Formatting Guidelines',+ '',+ '> CRITICAL REQUIREMENT: ALL MEMORY ITEMS MUST BE SELF-CONTAINED',+ '',+ 'Every memory item you create must be standalone and understandable without',+ 'extra context:',+ '',+ '✓ **Required Elements:**',+ '',+ '- Use full names and specific subjects—NEVER use pronouns',+ ' (he/she/they/it/this/that)',+ '- Include specific names, places, dates, and complete context',+ '- Preserve the original language from user input—do not translate',+ '- Capture relevant details, emotions, and outcomes',+ '- Ensure each item is comprehensible independently',+ '',+ '✓ **Good Examples:**',+ '',+ '- "When providing technical answers, {{ username }} prefers concise bullet',+ ' points and TypeScript code examples; avoid lengthy prose."',+ '- "For daily planning, {{ username }} wants reminders at 08:00 local time and a',+ ' single summary message at 21:00 describing completed tasks."',+ '',+ '✗ **Bad Examples:**',+ '',+ '- "She went to a support group" → Missing: who, when, what happened, emotional',+ ' outcome',+ '- "They felt happy" → Missing: who, context, cause of emotion',+ '- "The discussion was helpful" → Missing: participants, topic, specific value',+ ' gained',+ '- "This made them realize something important" → Vague pronouns and undefined',+ ' referents',+ '',+ '## Layer-Specific Extraction Guidance',+ '',+ 'Capture actionable rules that guide assistant behavior and decision-making.',+ 'Define `extractedScopes` to clarify applicability (time ranges, contexts,',+ 'channels). Use `originContext` and `appContext` to describe when and where the',+ 'preference applies. Write `conclusionDirectives` as self-contained instructions',"from the user's perspective. Use `scorePriority` to mark preferences that should",- "override conflicting defaults. Provide `suggestions` for helpful follow-up",- "actions. Avoid implementation details; focus on what the assistant should do.",- "",- "Examples of preference information:",- "",- "- \"{{ username }} prefers concise, bullet-point responses over long paragraphs",- " when asking technical questions\"",- "- \"{{ username }} likes to receive code examples in TypeScript rather than",- " JavaScript\"",- "- \"{{ username }} prefers morning workouts at 06:00 and dislikes exercising in",- " the evening\"",- "",- "Not preferences (do not extract):",- "",- "- One-off task instructions (e.g., \"帮我把这段话翻译成英文\")",- "- Implementation details or step-by-step plans (e.g.,",- " \"先抓取 API,然后解析 JSON…\")",- "- Language used in the conversation unless explicitly stated as a persistent",- " preference",- "",- "## Memory Type Classifications",- "",- "Choose the appropriate memoryType:",- "",- "- **activity**: Detailed conversations, interactions, and events with full",- " contextual narrative",- "- **event**: Specific time-bound occurrences (dates, milestones, appointments,",- " meetings)",- "- **fact**: Factual information, data points, and verifiable knowledge",- "- **preference**: User choices, likes, dislikes, and behavioral preferences",- "- **context**: Background information, situational details, environmental",- " factors",- "- **location**: Geographic information, places, and spatial context",- "- **people**: Information about individuals and their relationships",- "- **topic**: Subject matter, domains of interest, and knowledge areas",- "- **technology**: Tools, platforms, software, and technical systems",- "- **other**: Miscellaneous information not fitting other categories",- "",- "## Security Considerations",- "",- "**NEVER extract or store sensitive information:**",- "",- "- Passwords, PINs, or authentication credentials",- "- API keys, tokens, or secret keys",- "- Financial data (credit cards, bank accounts, SSN)",- "- Medical records or protected health information",- "- Private encryption keys or certificates",- "",- "---",- "",- "## Final Instructions",- "",- "1. Analyze the conversation for preference layer information",- "2. Extract each distinct preference memory as a separate item",- "3. Ensure all memories are self-contained (no pronouns, complete context)",- "4. Return a JSON array conforming to the schema above",- "5. Return `[]` if you find no preference memories",- "6. No matter what the language of the retrieved language is, always use {{ language }} for output",- "",- "Respond with valid JSON without commentary.",+ 'override conflicting defaults. Provide `suggestions` for helpful follow-up',+ 'actions. Avoid implementation details; focus on what the assistant should do.',+ '',+ 'Examples of preference information:',+ '',+ '- "{{ username }} prefers concise, bullet-point responses over long paragraphs',+ ' when asking technical questions"',+ '- "{{ username }} likes to receive code examples in TypeScript rather than',+ ' JavaScript"',+ '- "{{ username }} prefers morning workouts at 06:00 and dislikes exercising in',+ ' the evening"',+ '',+ 'Not preferences (do not extract):',+ '',+ '- One-off task instructions (e.g., "帮我把这段话翻译成英文")',+ '- Implementation details or step-by-step plans (e.g.,',+ ' "先抓取 API,然后解析 JSON…")',+ '- Language used in the conversation unless explicitly stated as a persistent',+ ' preference',+ '',+ '## Memory Type Classifications',+ '',+ 'Choose the appropriate memoryType:',+ '',+ '- **activity**: Detailed conversations, interactions, and events with full',+ ' contextual narrative',+ '- **event**: Specific time-bound occurrences (dates, milestones, appointments,',+ ' meetings)',+ '- **fact**: Factual information, data points, and verifiable knowledge',+ '- **preference**: User choices, likes, dislikes, and behavioral preferences',+ '- **context**: Background information, situational details, environmental',+ ' factors',+ '- **location**: Geographic information, places, and spatial context',+ '- **people**: Information about individuals and their relationships',+ '- **topic**: Subject matter, domains of interest, and knowledge areas',+ '- **technology**: Tools, platforms, software, and technical systems',+ '- **other**: Miscellaneous information not fitting other categories',+ '',+ '## Security Considerations',+ '',+ '**NEVER extract or store sensitive information:**',+ '',+ '- Passwords, PINs, or authentication credentials',+ '- API keys, tokens, or secret keys',+ '- Financial data (credit cards, bank accounts, SSN)',+ '- Medical records or protected health information',+ '- Private encryption keys or certificates',+ '',+ '---',+ '',+ '## Final Instructions',+ '',+ '1. Analyze the conversation for preference layer information',+ '2. Extract each distinct preference memory as a separate item',+ '3. Ensure all memories are self-contained (no pronouns, complete context)',+ '4. Return a JSON array conforming to the schema above',+ '5. Return `[]` if you find no preference memories',+ '6. No matter what the language of the retrieved language is, always use {{ language }} for output',+ '',+ 'Respond with valid JSON without commentary.',].join('\n');diff --git a/packages/memory-user-memory/src/services/extractExecutor.ts b/packages/memory-user-memory/src/services/extractExecutor.tsindex efe79fe9df4..cd1cb7bf489 100644--- a/packages/memory-user-memory/src/services/extractExecutor.ts+++ b/packages/memory-user-memory/src/services/extractExecutor.ts@@ -8,6 +8,7 @@ import {layersCallsCounter,tracer,} from '@lobechat/observability-otel/modules/memory-user-memory';+import { attributesCommon } from '@lobechat/observability-otel/node';import { LayersEnum } from '@lobechat/types';import {@@ -20,16 +21,15 @@ import {import {BaseExtractorDependencies,ExtractorOptions,+ ExtractorRunOptions,GatekeeperDecision,+ GatekeeperOptions,MemoryExtractionAgent,MemoryExtractionJob,MemoryExtractionLLMConfig,MemoryExtractionLayerOutputs,MemoryExtractionResult,- GatekeeperOptions,- ExtractorRunOptions,} from '../types';-import { attributesCommon } from '@lobechat/observability-otel/node';const LAYER_ORDER: LayersEnum[] = ['identity' as LayersEnum,@@ -60,10 +60,10 @@ export interface MemoryExtractionServiceOptions {}export interface MemoryExtractionLayerOutputTypes {- [LayersEnum.Context]: Awaited<ReturnType<ContextExtractor['structuredCall']>>- [LayersEnum.Experience]: Awaited<ReturnType<ExperienceExtractor['structuredCall']>>- [LayersEnum.Preference]: Awaited<ReturnType<PreferenceExtractor['structuredCall']>>- [LayersEnum.Identity]: Awaited<ReturnType<IdentityExtractor['structuredCall']>>+ [LayersEnum.Context]: Awaited<ReturnType<ContextExtractor['structuredCall']>>;+ [LayersEnum.Experience]: Awaited<ReturnType<ExperienceExtractor['structuredCall']>>;+ [LayersEnum.Preference]: Awaited<ReturnType<PreferenceExtractor['structuredCall']>>;+ [LayersEnum.Identity]: Awaited<ReturnType<IdentityExtractor['structuredCall']>>;}export type MemoryExtractionLayerOutputType = {@@ -216,7 +216,11 @@ export class MemoryExtractionService<RO> {const processedLayersCount = {context: outputs.context?.data ? outputs.context?.data?.memories?.length : 0,experience: outputs.experience?.data ? outputs.experience?.data?.memories?.length : 0,- identity: outputs.identity?.data ? (outputs.identity?.data?.add?.length || 0) + (outputs.identity?.data?.update?.length || 0) + (outputs.identity?.data?.remove?.length || 0) : 0,+ identity: outputs.identity?.data+ ? (outputs.identity?.data?.add?.length || 0) ++ (outputs.identity?.data?.update?.length || 0) ++ (outputs.identity?.data?.remove?.length || 0)+ : 0,preference: outputs.preference?.data ? outputs.preference?.data?.memories?.length : 0,};const processedErrorsCount = {@@ -224,7 +228,7 @@ export class MemoryExtractionService<RO> {experience: outputs.experience?.error ? 1 : 0,identity: outputs.identity?.error ? 1 : 0,preference: outputs.preference?.error ? 1 : 0,- }+ };const processedCount = Object.values(processedLayersCount).reduce((a, b) => a + b, 0);@@ -334,9 +338,7 @@ export class MemoryExtractionService<RO> {const setLayerOutput = (layer: LayersEnum,- result:- | { data: MemoryExtractionLayerOutputType }- | { error: unknown },+ result: { data: MemoryExtractionLayerOutputType } | { error: unknown },) => {switch (layer) {case LayersEnum.Context: {@@ -370,24 +372,25 @@ export class MemoryExtractionService<RO> {};await Promise.all(- ([- LayersEnum.Context,- LayersEnum.Experience,- LayersEnum.Preference,- LayersEnum.Identity,- ] as LayersEnum[])- .map(async (layer) => {- if (!layers.includes(layer)) {- return- }-- try {- const result = await this.runLayer(job, layer, options);- setLayerOutput(layer, { data: result });- } catch (error) {- setLayerOutput(layer, { error });- }- }),+ (+ [+ LayersEnum.Context,+ LayersEnum.Experience,+ LayersEnum.Preference,+ LayersEnum.Identity,+ ] as LayersEnum[]+ ).map(async (layer) => {+ if (!layers.includes(layer)) {+ return;+ }++ try {+ const result = await this.runLayer(job, layer, options);+ setLayerOutput(layer, { data: result });+ } catch (error) {+ setLayerOutput(layer, { error });+ }+ }),);return outputs as MemoryExtractionLayerOutputs;diff --git a/packages/memory-user-memory/src/types.ts b/packages/memory-user-memory/src/types.tsindex 20a9eb785db..9ea974f9552 100644--- a/packages/memory-user-memory/src/types.ts+++ b/packages/memory-user-memory/src/types.ts@@ -30,12 +30,14 @@ export interface ExtractorOptions extends ExtractorTemplateProps {additionalMessages?: OpenAIChatMessage[];callbacks?: {onExtractError?: (agent: MemoryExtractionAgent, error: unknown) => Promise<void> | void;- onExtractRequest?: (agent: MemoryExtractionAgent, request: GenerateObjectPayload) =>- | Promise<void>- | void;- onExtractResponse?: <TOutput>(agent: MemoryExtractionAgent, response: TOutput) =>- | Promise<void>- | void;+ onExtractRequest?: (+ agent: MemoryExtractionAgent,+ request: GenerateObjectPayload,+ ) => Promise<void> | void;+ onExtractResponse?: <TOutput>(+ agent: MemoryExtractionAgent,+ response: TOutput,+ ) => Promise<void> | void;};messageIds?: string[];sourceId?: string;@@ -133,11 +135,11 @@ export type MemoryExtractionLayerOutputs = Partial<{identity: {data?: Awaited<ReturnType<IdentityExtractor['structuredCall']>>;error?: unknown;- }+ };preference: {data?: Awaited<ReturnType<PreferenceExtractor['structuredCall']>>;error?: unknown;- }+ };}>;export interface GatekeeperDecision {diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.tsindex 01ce47d010f..e34aa3fafe6 100644--- a/packages/types/src/topic/topic.ts+++ b/packages/types/src/topic/topic.ts@@ -34,6 +34,10 @@ export interface TopicUserMemoryExtractRunState {}export interface ChatTopicMetadata {+ /**+ * Cron job ID that triggered this topic creation (if created by scheduled task)+ */+ cronJobId?: string;model?: string;provider?: string;userMemoryExtractRunState?: TopicUserMemoryExtractRunState;@@ -57,6 +61,7 @@ export interface ChatTopic extends Omit<BaseDataModel, 'meta'> {metadata?: ChatTopicMetadata;sessionId?: string;title: string;+ trigger?: string | null;}export type ChatTopicMap = Record<string, ChatTopic>;@@ -106,6 +111,10 @@ export interface CreateTopicParams {export interface QueryTopicParams {agentId?: string | null;current?: number;+ /**+ * Exclude topics by trigger types (e.g. ['cron'])+ */+ excludeTriggers?: string[];/*** Group ID to filter topics by*/diff --git a/src/app/[variants]/(main)/chat/_layout/Sidebar/Body.tsx b/src/app/[variants]/(main)/chat/_layout/Sidebar/Body.tsxindex babffad690f..45250b06fe8 100644--- a/src/app/[variants]/(main)/chat/_layout/Sidebar/Body.tsx+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/Body.tsx@@ -2,15 +2,18 @@ import { Accordion, Flexbox } from '@lobehub/ui';import React, { memo } from 'react';import Topic from './Topic';+import CronTopicList from './Topic/CronTopicList';export enum ChatSidebarKey {- Topic = 'topic',+ CronTopics = 'cronTopics',+ Topic = 'topic'}const Body = memo(() => {return (<Flexbox paddingInline={4}><Accordion defaultExpandedKeys={[ChatSidebarKey.Topic]} gap={8}>+ <CronTopicList itemKey={ChatSidebarKey.CronTopics} /><Topic itemKey={ChatSidebarKey.Topic} /></Accordion></Flexbox>diff --git a/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/CronTopicList/CronTopicGroup.tsx b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/CronTopicList/CronTopicGroup.tsxnew file mode 100644index 00000000000..06889ac5240--- /dev/null+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/CronTopicList/CronTopicGroup.tsx@@ -0,0 +1,74 @@+'use client';++import { Flexbox, Icon, Text } from '@lobehub/ui';+import { cssVar } from 'antd-style';+import { Clock } from 'lucide-react';+import { type MouseEvent, memo, useCallback } from 'react';+import { useParams } from 'react-router-dom';++import { useRouter } from '@/app/[variants]/(main)/hooks/useRouter';+import type { AgentCronJob } from '@/database/schemas/agentCronJob';++import CronTopicItem from './CronTopicItem';++interface CronTopicGroupProps {+ cronJob: AgentCronJob | null;+ cronJobId: string;+ topics: Array<{+ createdAt: Date | string;+ favorite?: boolean | null;+ historySummary?: string | null;+ id: string;+ metadata?: any;+ title?: string | null;+ trigger?: string | null;+ updatedAt: Date | string;+ }>;+}++const CronTopicGroup = memo<CronTopicGroupProps>(({ cronJob, cronJobId, topics }) => {+ const { aid } = useParams<{ aid?: string }>();+ const router = useRouter();+ const handleOpenCronJob = useCallback(+ (event: MouseEvent) => {+ event.stopPropagation();+ if (!aid) return;+ router.push(`/agent/${aid}/cron/${cronJobId}`);+ },+ [aid, cronJobId, router],+ );++ const cronJobName = cronJob?.name || `Cron Job ${cronJobId.slice(-8)}`;+ const isEnabled = cronJob?.enabled ?? false;++ return (+ <Flexbox gap={1}>+ <Flexbox+ align="center"+ gap={6}+ height={24}+ horizontal+ onClick={handleOpenCronJob}+ paddingInline={8}+ style={{ cursor: 'pointer', opacity: isEnabled ? 1 : 0.6, overflow: 'hidden' }}+ >+ <Icon icon={Clock} style={{ color: cssVar.colorTextDescription, opacity: 0.7 }} />+ <Text ellipsis fontSize={12} style={{ flex: 1 }} type={'secondary'} weight={500}>+ {cronJobName}+ </Text>+ {topics.length > 0 && (+ <Text style={{ color: cssVar.colorTextDescription, fontSize: 11 }}>{topics.length}</Text>+ )}+ </Flexbox>+ {topics.length > 0 && (+ <Flexbox gap={1} paddingBlock={1}>+ {topics.map((topic) => (+ <CronTopicItem key={topic.id} topic={topic} />+ ))}+ </Flexbox>+ )}+ </Flexbox>+ );+});++export default CronTopicGroup;diff --git a/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/CronTopicList/CronTopicItem.tsx b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/CronTopicList/CronTopicItem.tsxnew file mode 100644index 00000000000..eca6f5cbb3c--- /dev/null+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/CronTopicList/CronTopicItem.tsx@@ -0,0 +1,40 @@+'use client';++import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { useChatStore } from '@/store/chat';++import TopicItem from '../List/Item';++interface CronTopicItemProps {+ topic: {+ createdAt: Date | string;+ favorite?: boolean | null;+ historySummary?: string | null;+ id: string;+ metadata?: any;+ title?: string | null;+ trigger?: string | null;+ updatedAt: Date | string;+ };+}++const CronTopicItem = memo<CronTopicItemProps>(({ topic }) => {+ const { t } = useTranslation('topic');+ const [activeTopicId, activeThreadId] = useChatStore((s) => [s.activeTopicId, s.activeThreadId]);++ const displayTitle = topic.title || topic.historySummary || t('defaultTitle');++ return (+ <TopicItem+ active={activeTopicId === topic.id}+ fav={!!topic.favorite}+ id={topic.id}+ threadId={activeThreadId}+ title={displayTitle}+ />+ );+});++export default CronTopicItem;diff --git a/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/CronTopicList/index.tsx b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/CronTopicList/index.tsxnew file mode 100644index 00000000000..d9bec54c7a9--- /dev/null+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/CronTopicList/index.tsx@@ -0,0 +1,140 @@+'use client';++import { ENABLE_BUSINESS_FEATURES } from '@lobechat/business-const';+import { AccordionItem, ActionIcon, Flexbox, Icon, Text } from '@lobehub/ui';+import { message } from 'antd';+import { Calendar, Plus } from 'lucide-react';+import { memo, useCallback } from 'react';+import { useTranslation } from 'react-i18next';+import urlJoin from 'url-join';++import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';+import EmptyNavItem from '@/features/NavPanel/components/EmptyNavItem';+import SkeletonList from '@/features/NavPanel/components/SkeletonList';+import { useFetchCronTopicsWithJobInfo } from '@/hooks/useFetchCronTopicsWithJobInfo';+import { useQueryRoute } from '@/hooks/useQueryRoute';+import { agentCronJobService } from '@/services/agentCronJob';+import { useAgentStore } from '@/store/agent';++import CronTopicGroup from './CronTopicGroup';++interface CronTopicListProps {+ itemKey: string;+}++const CronTopicList = memo<CronTopicListProps>(({ itemKey }) => {+ const { t } = useTranslation('setting');+ const router = useQueryRoute();+ const agentId = useAgentStore((s) => s.activeAgentId);+ const { cronTopicsGroupsWithJobInfo, isLoading, mutate } = useFetchCronTopicsWithJobInfo();+ const totalTopics = cronTopicsGroupsWithJobInfo.reduce(+ (acc, group) => acc + group.topics.length,+ 0,+ );++ const handleCreateCronJob = useCallback(async () => {+ if (!agentId) return;+ try {+ const result = await agentCronJobService.create({+ agentId,+ content: t('agentCronJobs.form.content.placeholder') || 'This is a cron job',+ cronPattern: '0 */30 * * *',+ enabled: true,+ name: t('agentCronJobs.addJob') || 'Cron Job Task',+ });++ if (result.success) {+ await mutate();+ router.push(urlJoin('/agent', agentId, 'cron', result.data.id));+ }+ } catch (error) {+ console.error('Failed to create cron job:', error);+ message.error('Failed to create scheduled task');+ }+ }, [agentId, mutate, router, t]);++ if (!ENABLE_BUSINESS_FEATURES) return null;++ const addAction = (+ <ActionIcon+ disabled={!agentId}+ icon={Plus}+ onClick={handleCreateCronJob}+ size={'small'}+ title={t('agentCronJobs.addJob')}+ />+ );++ if (isLoading) {+ return (+ <AccordionItem+ action={addAction}+ itemKey={itemKey}+ paddingBlock={4}+ paddingInline={'8px 4px'}+ title={+ <Flexbox align="center" gap={4} horizontal>+ <Icon icon={Calendar} size={12} />+ <Text ellipsis fontSize={12} type={'secondary'} weight={500}>+ {t('agentCronJobs.title')}+ </Text>+ <NeuralNetworkLoading size={14} />+ </Flexbox>+ }+ >+ <SkeletonList />+ </AccordionItem>+ );+ }++ if (cronTopicsGroupsWithJobInfo.length === 0) {+ return (+ <AccordionItem+ action={addAction}+ itemKey={itemKey}+ paddingBlock={4}+ paddingInline={'8px 4px'}+ title={+ <Flexbox align="center" gap={4} horizontal>+ <Icon icon={Calendar} size={12} />+ <Text ellipsis fontSize={12} type={'secondary'} weight={500}>+ {t('agentCronJobs.title')}+ </Text>+ </Flexbox>+ }+ >+ <EmptyNavItem onClick={handleCreateCronJob} title={t('agentCronJobs.addJob')} />+ </AccordionItem>+ );+ }++ return (+ <AccordionItem+ action={addAction}+ itemKey={itemKey}+ paddingBlock={4}+ paddingInline={'8px 4px'}+ title={+ <Flexbox align="center" gap={4} horizontal>+ <Icon icon={Calendar} size={12} />+ <Text ellipsis fontSize={12} type={'secondary'} weight={500}>+ {`${t('agentCronJobs.title')} ${totalTopics > 0 ? totalTopics : ''}`}+ </Text>+ </Flexbox>+ }+ >+ <Flexbox gap={2} paddingBlock={2}>+ {cronTopicsGroupsWithJobInfo.map((group) => (+ <CronTopicGroup+ cronJob={group.cronJob}+ cronJobId={group.cronJobId}+ key={group.cronJobId}+ topics={group.topics}+ />+ ))}+ </Flexbox>+ </AccordionItem>+ );+});++export default CronTopicList;diff --git a/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/List/index.tsx b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/List/index.tsxindex 33bf09d6403..d3c83136e8f 100644--- a/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/List/index.tsx+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/List/index.tsx@@ -32,7 +32,7 @@ const TopicList = memo(() => {const [topicDisplayMode] = useUserStore((s) => [preferenceSelectors.topicDisplayMode(s)]);- useFetchTopics();+ useFetchTopics({ excludeTriggers: ['cron'] });// Show skeleton when current session's topic data is not yet loadedif (isUndefinedTopics) return <SkeletonList />;diff --git a/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/TopicListContent/index.tsx b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/TopicListContent/index.tsxindex 530383909e6..08e3add24a7 100644--- a/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/TopicListContent/index.tsx+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/TopicListContent/index.tsx@@ -30,7 +30,7 @@ const TopicListContent = memo(() => {const [topicDisplayMode] = useUserStore((s) => [preferenceSelectors.topicDisplayMode(s)]);- useFetchTopics();+ useFetchTopics({ excludeTriggers: ['cron'] });if (isInSearchMode) return <SearchResult />;diff --git a/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/index.tsx b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/index.tsxindex deeb346a4f9..0569cfeb974 100644--- a/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/index.tsx+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/index.tsx@@ -22,7 +22,7 @@ const Topic = memo<TopicProps>(({ itemKey }) => {const { t } = useTranslation(['topic', 'common']);const [topicCount] = useChatStore((s) => [topicSelectors.currentTopicCount(s)]);const dropdownMenu = useTopicActionsDropdownMenu();- const { isRevalidating } = useFetchTopics();+ const { isRevalidating } = useFetchTopics({ excludeTriggers: ['cron'] });return (<AccordionItemdiff --git a/src/app/[variants]/(main)/chat/cron/[cronId]/index.tsx b/src/app/[variants]/(main)/chat/cron/[cronId]/index.tsxnew file mode 100644index 00000000000..844e81a0552--- /dev/null+++ b/src/app/[variants]/(main)/chat/cron/[cronId]/index.tsx@@ -0,0 +1,664 @@+'use client';++import { ENABLE_BUSINESS_FEATURES } from '@lobechat/business-const';+import { EDITOR_DEBOUNCE_TIME } from '@lobechat/const';+import {+ ReactCodePlugin,+ ReactCodemirrorPlugin,+ ReactHRPlugin,+ ReactLinkPlugin,+ ReactListPlugin,+ ReactMathPlugin,+ ReactTablePlugin,+} from '@lobehub/editor';+import { Editor, useEditor } from '@lobehub/editor/react';+import { ActionIcon, Flexbox, Icon, Input, Tag, Text } from '@lobehub/ui';+import { useDebounceFn } from 'ahooks';+import { App, Card, Checkbox, Empty, InputNumber, Select, Switch, TimePicker, message } from 'antd';+import dayjs, { type Dayjs } from 'dayjs';+import { Clock, Trash2 } from 'lucide-react';+import {+ memo,+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+ useSyncExternalStore,+} from 'react';+import { useTranslation } from 'react-i18next';+import { useParams } from 'react-router-dom';+import useSWR from 'swr';++import AutoSaveHint from '@/components/Editor/AutoSaveHint';+import Loading from '@/components/Loading/BrandTextLoading';+import type { ExecutionConditions, UpdateAgentCronJobData } from '@/database/schemas/agentCronJob';+import TypoBar from '@/features/EditorModal/Typobar';+import NavHeader from '@/features/NavHeader';+import WideScreenContainer from '@/features/WideScreenContainer';+import { useQueryRoute } from '@/hooks/useQueryRoute';+import { mutate } from '@/libs/swr';+import { lambdaClient } from '@/libs/trpc/client/lambda';+import { agentCronJobService } from '@/services/agentCronJob';+import { topicService } from '@/services/topic';+import { useAgentStore } from '@/store/agent';+import { useChatStore } from '@/store/chat';+import { useUserStore } from '@/store/user';+import { labPreferSelectors } from '@/store/user/selectors';++interface CronJobDraft {+ content: string;+ cronPattern: string;+ description: string;+ maxExecutions?: number | null;+ maxExecutionsPerDay?: number | null;+ name: string;+ timeRange?: [Dayjs, Dayjs];+ weekdays: number[];+}++type AutoSaveStatus = 'idle' | 'saving' | 'saved';+interface AutoSaveState {+ lastUpdatedTime: Date | null | any;+ status: AutoSaveStatus;+}++const autoSaveStore = {+ listeners: new Set<() => void>(),+ state: { lastUpdatedTime: null, status: 'idle' as AutoSaveStatus },+};++const getAutoSaveState = () => autoSaveStore.state;+const subscribeAutoSave = (listener: () => void) => {+ autoSaveStore.listeners.add(listener);+ return () => autoSaveStore.listeners.delete(listener);+};+const setAutoSaveState = (patch: Partial<AutoSaveState>) => {+ autoSaveStore.state = { ...autoSaveStore.state, ...patch };+ autoSaveStore.listeners.forEach((listener) => listener());+};+const useAutoSaveState = () =>+ useSyncExternalStore(subscribeAutoSave, getAutoSaveState, getAutoSaveState);++const AutoSaveHintSlot = memo(() => {+ const { lastUpdatedTime, status } = useAutoSaveState();+ return <AutoSaveHint lastUpdatedTime={lastUpdatedTime} saveStatus={status} />;+});++const CRON_PATTERNS = [+ { label: 'agentCronJobs.interval.30min', value: '0 */30 * * *' },+ { label: 'agentCronJobs.interval.1hour', value: '0 0 * * *' },+ { label: 'agentCronJobs.interval.6hours', value: '0 */6 * * *' },+ { label: 'agentCronJobs.interval.12hours', value: '0 */12 * * *' },+ { label: 'agentCronJobs.interval.daily', value: '0 0 0 * *' },+ { label: 'agentCronJobs.interval.weekly', value: '0 0 0 * 0' },+];++const WEEKDAY_OPTIONS = [+ { label: 'Mon', value: 1 },+ { label: 'Tue', value: 2 },+ { label: 'Wed', value: 3 },+ { label: 'Thu', value: 4 },+ { label: 'Fri', value: 5 },+ { label: 'Sat', value: 6 },+ { label: 'Sun', value: 0 },+];++const WEEKDAY_LABELS: Record<number, string> = {+ 0: 'Sunday',+ 1: 'Monday',+ 2: 'Tuesday',+ 3: 'Wednesday',+ 4: 'Thursday',+ 5: 'Friday',+ 6: 'Saturday',+};++const getIntervalText = (cronPattern: string) => {+ const intervalMap: Record<string, string> = {+ '0 */12 * * *': 'agentCronJobs.interval.12hours',+ '0 */30 * * *': 'agentCronJobs.interval.30min',+ '0 */6 * * *': 'agentCronJobs.interval.6hours',+ '0 0 * * *': 'agentCronJobs.interval.1hour',+ '0 0 0 * *': 'agentCronJobs.interval.daily',+ '0 0 0 * 0': 'agentCronJobs.interval.weekly',+ };++ return intervalMap[cronPattern] || cronPattern;+};++const resolveDate = (value?: Date | string | null) => {+ if (!value) return null;+ return typeof value === 'string' ? new Date(value) : value;+};++const CronJobDetailPage = memo(() => {+ const { t } = useTranslation(['setting', 'common']);+ const { aid, cronId } = useParams<{ aid?: string; cronId?: string }>();+ const router = useQueryRoute();+ const { modal } = App.useApp();+ const editor = useEditor();+ const enableRichRender = useUserStore(labPreferSelectors.enableInputMarkdown);+ const [editorReady, setEditorReady] = useState(false);++ const [draft, setDraft] = useState<CronJobDraft | null>(null);+ const draftRef = useRef<CronJobDraft | null>(null);+ const contentRef = useRef('');+ const pendingContentRef = useRef<string | null>(null);+ const pendingSaveRef = useRef(false);+ const initializedIdRef = useRef<string | null>(null);+ const readyRef = useRef(false);+ const lastSavedNameRef = useRef<string | null>(null);+ const lastSavedPayloadRef = useRef<UpdateAgentCronJobData | null>(null);+ const lastSavedAtRef = useRef<Date | null>(null);+ const previousCronIdRef = useRef<string | null>(null);+ const hydratedAtRef = useRef<string | null>(null);+ const isDirtyRef = useRef(false);++ const [activeTopicId, refreshTopic, switchTopic] = useChatStore((s) => [+ s.activeTopicId,+ s.refreshTopic,+ s.switchTopic,+ ]);++ const activeAgentId = useAgentStore((s) => s.activeAgentId);+ const cronListAgentId = activeAgentId || aid;++ const { data: cronJob, isLoading } = useSWR(+ ENABLE_BUSINESS_FEATURES && cronId ? ['cronJob', cronId] : null,+ async () => {+ if (!cronId) return null;+ const result = await agentCronJobService.getById(cronId);+ return result.success ? result.data : null;+ },+ {+ dedupingInterval: 0,+ revalidateIfStale: true,+ revalidateOnFocus: false,+ revalidateOnMount: true,+ },+ );++ const resolvedCronPattern = draft ? draft.cronPattern : cronJob?.cronPattern;+ const resolvedWeekdays = draft ? draft.weekdays : cronJob?.executionConditions?.weekdays || [];+ const resolvedTimeRange = draft+ ? draft.timeRange+ : cronJob?.executionConditions?.timeRange+ ? [+ dayjs(cronJob.executionConditions.timeRange.start, 'HH:mm'),+ dayjs(cronJob.executionConditions.timeRange.end, 'HH:mm'),+ ]+ : undefined;++ const summaryTags = useMemo(() => {+ const tags: Array<{ key: string; label: string }> = [];++ if (resolvedCronPattern) {+ tags.push({+ key: 'interval',+ label: t(getIntervalText(resolvedCronPattern) as any),+ });+ }++ if (resolvedWeekdays.length > 0) {+ tags.push({+ key: 'weekdays',+ label: resolvedWeekdays.map((day) => WEEKDAY_LABELS[day]).join(', '),+ });+ }++ if (resolvedTimeRange && resolvedTimeRange.length === 2) {+ tags.push({+ key: 'timeRange',+ label: `${resolvedTimeRange[0].format('HH:mm')} - ${resolvedTimeRange[1].format('HH:mm')}`,+ });+ }++ return tags;+ }, [resolvedCronPattern, resolvedTimeRange, resolvedWeekdays, t]);++ const buildUpdateData = useCallback(+ (snapshot: CronJobDraft | null, content: string): UpdateAgentCronJobData | null => {+ if (!snapshot) return null;+ if (!snapshot.content) return null;+ if (!snapshot.name) return null;++ const executionConditions: ExecutionConditions = {};+ if (snapshot.timeRange && snapshot.timeRange.length === 2) {+ executionConditions.timeRange = {+ end: snapshot.timeRange[1].format('HH:mm'),+ start: snapshot.timeRange[0].format('HH:mm'),+ };+ }++ if (snapshot.weekdays && snapshot.weekdays.length > 0) {+ executionConditions.weekdays = snapshot.weekdays;+ }++ if (snapshot.maxExecutionsPerDay) {+ executionConditions.maxExecutionsPerDay = snapshot.maxExecutionsPerDay;+ }++ return {+ content,+ cronPattern: snapshot.cronPattern,+ description: snapshot.description?.trim() || null,+ executionConditions:+ Object.keys(executionConditions).length > 0 ? executionConditions : null,+ maxExecutions: snapshot.maxExecutions ?? null,+ name: snapshot.name?.trim() || null,+ };+ },+ [],+ );++ const refreshCronList = useCallback(() => {+ if (!cronListAgentId) return;+ void mutate(['cronTopicsWithJobInfo', cronListAgentId]);+ }, [cronListAgentId]);++ useEffect(() => {+ const prevCronId = previousCronIdRef.current;+ if (prevCronId && prevCronId !== cronId && lastSavedPayloadRef.current) {+ const payload = lastSavedPayloadRef.current;+ const updatedAt = lastSavedAtRef.current;+ mutate(+ ['cronJob', prevCronId],+ (current) =>+ current+ ? {+ ...current,+ ...payload,+ executionConditions: payload.executionConditions ?? null,+ ...(updatedAt ? { updatedAt } : null),+ }+ : current,+ false,+ );+ }++ previousCronIdRef.current = cronId ?? null;+ lastSavedPayloadRef.current = null;+ lastSavedAtRef.current = null;+ hydratedAtRef.current = null;+ isDirtyRef.current = false;+ }, [cronId]);++ const { run: debouncedSave, cancel: cancelDebouncedSave } = useDebounceFn(+ async () => {+ if (!cronId || initializedIdRef.current !== cronId) return;+ const payload = buildUpdateData(draftRef.current, contentRef.current);+ if (!payload) return;+ if (!payload.content || !payload.name) return;++ try {+ await agentCronJobService.update(cronId, payload);+ const savedAt = new Date();+ lastSavedPayloadRef.current = payload;+ lastSavedAtRef.current = savedAt;+ isDirtyRef.current = false;+ setAutoSaveState({ lastUpdatedTime: savedAt, status: 'saved' });+ const nextName = payload.name ?? null;+ if (nextName !== lastSavedNameRef.current) {+ lastSavedNameRef.current = nextName;+ refreshCronList();+ }+ } catch (error) {+ console.error('Failed to update cron job:', error);+ setAutoSaveState({ status: 'idle' });+ message.error('Failed to update scheduled task');+ }+ },+ { wait: EDITOR_DEBOUNCE_TIME },+ );++ useEffect(() => {+ cancelDebouncedSave();+ pendingSaveRef.current = false;+ }, [cancelDebouncedSave, cronId]);++ const scheduleSave = useCallback(() => {+ if (!readyRef.current || !draftRef.current) {+ pendingSaveRef.current = true;+ return;+ }+ isDirtyRef.current = true;+ setAutoSaveState({ status: 'saving' });+ debouncedSave();+ }, [debouncedSave]);++ const flushPendingSave = useCallback(() => {+ if (!pendingSaveRef.current || !draftRef.current) return;+ pendingSaveRef.current = false;+ isDirtyRef.current = true;+ setAutoSaveState({ status: 'saving' });+ debouncedSave();+ }, [debouncedSave]);++ const updateDraft = useCallback(+ (patch: Partial<CronJobDraft>) => {+ setDraft((prev) => {+ if (!prev) return prev;+ const next = { ...prev, ...patch };+ draftRef.current = next;+ return next;+ });+ scheduleSave();+ },+ [scheduleSave],+ );++ const handleContentChange = useCallback(() => {+ if (!readyRef.current || !editor || !editorReady) return;+ const nextContent = enableRichRender+ ? (editor.getDocument('markdown') as unknown as string)+ : (editor.getDocument('text') as unknown as string);+ contentRef.current = nextContent || '';+ scheduleSave();+ }, [editor, editorReady, enableRichRender, scheduleSave]);++ const handleToggleEnabled = useCallback(+ async (enabled: boolean) => {+ if (!cronId) return;+ setAutoSaveState({ status: 'saving' });+ try {+ await agentCronJobService.update(cronId, { enabled });+ setAutoSaveState({ lastUpdatedTime: new Date(), status: 'saved' });+ } catch (error) {+ console.error('Failed to update cron job status:', error);+ setAutoSaveState({ status: 'idle' });+ message.error('Failed to update scheduled task');+ }+ },+ [cronId, mutate, refreshCronList],+ );++ const handleDeleteCronJob = useCallback(() => {+ if (!cronId) return;++ modal.confirm({+ centered: true,+ okButtonProps: { danger: true },+ onOk: async () => {+ try {+ let topicIds: string[] = [];+ if (aid) {+ const groups = await lambdaClient.topic.getCronTopicsGroupedByCronJob.query({+ agentId: aid,+ });+ const group = groups.find((item) => item.cronJobId === cronId);+ topicIds = group?.topics.map((topic) => topic.id) || [];+ }++ await agentCronJobService.delete(cronId);++ if (topicIds.length > 0) {+ await topicService.batchRemoveTopics(topicIds);+ await refreshTopic();+ if (activeTopicId && topicIds.includes(activeTopicId)) {+ switchTopic();+ }+ }++ if (cronListAgentId) {+ await mutate(['cronTopicsWithJobInfo', cronListAgentId]);+ router.push(`/agent/${cronListAgentId}`);+ } else {+ router.push('/');+ }+ } catch (error) {+ console.error('Failed to delete cron job:', error);+ message.error('Failed to delete scheduled task');+ }+ },+ title: t('agentCronJobs.confirmDelete'),+ });+ }, [activeTopicId, cronId, cronListAgentId, modal, refreshTopic, router, switchTopic, t]);++ useEffect(() => {+ if (!cronJob) return;+ const cronUpdatedAt = cronJob.updatedAt ? new Date(cronJob.updatedAt).toISOString() : null;+ const shouldHydrate =+ initializedIdRef.current !== cronJob.id ||+ (cronUpdatedAt !== hydratedAtRef.current && !isDirtyRef.current);++ if (!shouldHydrate) return;+ initializedIdRef.current = cronJob.id;+ hydratedAtRef.current = cronUpdatedAt;+ isDirtyRef.current = false;+ readyRef.current = false;+ lastSavedNameRef.current = cronJob.name ?? null;++ const nextDraft: CronJobDraft = {+ content: cronJob.content || '',+ cronPattern: cronJob.cronPattern,+ description: cronJob.description || '',+ maxExecutions: cronJob.maxExecutions ?? null,+ maxExecutionsPerDay: cronJob.executionConditions?.maxExecutionsPerDay ?? null,+ name: cronJob.name || '',+ timeRange: cronJob.executionConditions?.timeRange+ ? [+ dayjs(cronJob.executionConditions.timeRange.start, 'HH:mm'),+ dayjs(cronJob.executionConditions.timeRange.end, 'HH:mm'),+ ]+ : undefined,+ weekdays: cronJob.executionConditions?.weekdays || [],+ };++ setDraft(nextDraft);+ draftRef.current = nextDraft;++ contentRef.current = nextDraft.content;+ pendingContentRef.current = nextDraft.content;++ setAutoSaveState({+ lastUpdatedTime: resolveDate(cronJob.updatedAt),+ status: 'saved',+ });++ if (editorReady && editor) {+ try {+ setTimeout(() => {+ editor.setDocument(enableRichRender ? 'markdown' : 'text', nextDraft.content);+ }, 100);+ pendingContentRef.current = null;+ readyRef.current = true;+ flushPendingSave();+ } catch (error) {+ console.error('[CronJobDetailPage] Failed to init editor content:', error);+ setTimeout(() => {+ editor.setDocument(enableRichRender ? 'markdown' : 'text', nextDraft.content);+ }, 100);+ }+ }+ }, [cronJob, editor, editorReady, enableRichRender]);++ useEffect(() => {+ if (!editorReady || !editor || pendingContentRef.current === null) return;+ try {+ setTimeout(() => {+ editor.setDocument(enableRichRender ? 'markdown' : 'text', pendingContentRef.current);+ }, 100);+ pendingContentRef.current = null;+ readyRef.current = true;+ flushPendingSave();+ } catch (error) {+ console.error('[CronJobDetailPage] Failed to init editor content:', error);+ setTimeout(() => {+ console.log('setDocument timeout', pendingContentRef.current);+ editor.setDocument(enableRichRender ? 'markdown' : 'text', pendingContentRef.current);+ }, 100);+ }+ }, [editor, editorReady, enableRichRender]);++ if (!ENABLE_BUSINESS_FEATURES) {+ return null;+ }++ return (+ <Flexbox flex={1} height={'100%'}>+ <NavHeader left={<AutoSaveHintSlot />} />+ <Flexbox flex={1} style={{ overflowY: 'auto' }}>+ <WideScreenContainer paddingBlock={16}>+ {isLoading && <Loading debugId="CronJobDetailPage" />}+ {!isLoading && !cronJob && (+ <Empty+ description={t('agentCronJobs.empty.description')}+ image={Empty.PRESENTED_IMAGE_SIMPLE}+ />+ )}+ {!isLoading && cronJob && (+ <Flexbox gap={24}>+ <Flexbox align="center" gap={16} horizontal justify="space-between">+ <Flexbox gap={6} style={{ flex: 1, minWidth: 0 }}>+ <Input+ onChange={(e) => updateDraft({ name: e.target.value })}+ placeholder={t('agentCronJobs.form.name.placeholder')}+ style={{+ fontSize: 28,+ fontWeight: 600,+ padding: 0,+ }}+ value={draft?.name ?? cronJob.name ?? ''}+ variant={'borderless'}+ />+ </Flexbox>+ <Flexbox align="center" gap={8} horizontal>+ <ActionIcon+ icon={Trash2}+ onClick={handleDeleteCronJob}+ size={'small'}+ title={t('delete', { ns: 'common' })}+ />+ <Text type="secondary">+ {t(+ cronJob?.enabled+ ? 'agentCronJobs.status.enabled'+ : 'agentCronJobs.status.disabled',+ )}+ </Text>+ <Switch+ defaultChecked={cronJob?.enabled ?? false}+ disabled={!cronJob}+ key={cronJob?.id ?? 'cron-switch'}+ onChange={handleToggleEnabled}+ size="small"+ />+ </Flexbox>+ </Flexbox>++ <Card size="small" style={{ borderRadius: 12 }} styles={{ body: { padding: 12 } }}>+ <Flexbox gap={12}>+ {summaryTags.length > 0 && (+ <Flexbox align="center" gap={8} horizontal style={{ flexWrap: 'wrap' }}>+ {summaryTags.map((tag) => (+ <Tag key={tag.key} variant={'filled'}>+ {tag.label}+ </Tag>+ ))}+ </Flexbox>+ )}++ <Flexbox align="center" gap={8} horizontal style={{ flexWrap: 'wrap' }}>+ <Tag variant={'borderless'}>{t('agentCronJobs.schedule')}</Tag>+ <Select+ onChange={(value) => updateDraft({ cronPattern: value })}+ options={CRON_PATTERNS.map((pattern) => ({+ label: t(pattern.label as any),+ value: pattern.value,+ }))}+ size="small"+ style={{ minWidth: 160 }}+ value={draft?.cronPattern ?? cronJob.cronPattern}+ />+ <TimePicker.RangePicker+ format="HH:mm"+ onChange={(value) =>+ updateDraft({+ timeRange:+ value && value.length === 2+ ? [value[0] as Dayjs, value[1] as Dayjs]+ : undefined,+ })+ }+ placeholder={[+ t('agentCronJobs.form.timeRange.start'),+ t('agentCronJobs.form.timeRange.end'),+ ]}+ size="small"+ value={+ draft?.timeRange ??+ (resolvedTimeRange as [Dayjs, Dayjs] | undefined) ??+ null+ }+ />+ <Checkbox.Group+ onChange={(values) => updateDraft({ weekdays: values as number[] })}+ options={WEEKDAY_OPTIONS}+ style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}+ value={draft?.weekdays ?? resolvedWeekdays}+ />+ </Flexbox>++ <Flexbox align="center" gap={8} horizontal style={{ flexWrap: 'wrap' }}>+ <Tag variant={'borderless'}>{t('agentCronJobs.maxExecutions')}</Tag>+ <InputNumber+ min={1}+ onChange={(value) => updateDraft({ maxExecutions: value ?? null })}+ placeholder={t('agentCronJobs.form.maxExecutions.placeholder')}+ size="small"+ style={{ width: 160 }}+ value={draft?.maxExecutions ?? cronJob.maxExecutions ?? null}+ />+ </Flexbox>+ </Flexbox>+ </Card>++ <Flexbox gap={12}>+ <Flexbox align="center" gap={6} horizontal>+ <Icon icon={Clock} size={16} />+ <Text style={{ fontWeight: 600 }}>{t('agentCronJobs.content')}</Text>+ </Flexbox>+ <Card+ size="small"+ style={{ borderRadius: 12, overflow: 'hidden' }}+ styles={{ body: { padding: 0 } }}+ >+ {enableRichRender && <TypoBar editor={editor} />}+ <Flexbox padding={16} style={{ minHeight: 220 }}>+ <Editor+ content={''}+ editor={editor}+ lineEmptyPlaceholder={t('agentCronJobs.form.content.placeholder')}+ onInit={() => setEditorReady(true)}+ onTextChange={handleContentChange}+ placeholder={t('agentCronJobs.form.content.placeholder')}+ plugins={+ enableRichRender+ ? [+ ReactListPlugin,+ ReactCodePlugin,+ ReactCodemirrorPlugin,+ ReactHRPlugin,+ ReactLinkPlugin,+ ReactTablePlugin,+ ReactMathPlugin,+ ]+ : undefined+ }+ style={{ paddingBottom: 48 }}+ type={'text'}+ variant={'chat'}+ />+ </Flexbox>+ </Card>+ </Flexbox>+ </Flexbox>+ )}+ </WideScreenContainer>+ </Flexbox>+ </Flexbox>+ );+});++export default CronJobDetailPage;diff --git a/src/app/[variants]/(main)/chat/profile/features/AgentCronJobs/CronJobCards.tsx b/src/app/[variants]/(main)/chat/profile/features/AgentCronJobs/CronJobCards.tsxnew file mode 100644index 00000000000..0925fce45f5--- /dev/null+++ b/src/app/[variants]/(main)/chat/profile/features/AgentCronJobs/CronJobCards.tsx@@ -0,0 +1,160 @@+'use client';++import { ActionIcon, Flexbox, Icon } from '@lobehub/ui';+import { Badge, Card, Col, Popconfirm, Row, Switch, Typography } from 'antd';+import dayjs from 'dayjs';+import { Calendar, Clock, Edit, Trash2 } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import type { AgentCronJob } from '@/database/schemas/agentCronJob';++import { useAgentCronJobs } from './hooks/useAgentCronJobs';++const { Text } = Typography;++interface CronJobCardsProps {+ cronJobs: AgentCronJob[];+ loading?: boolean;+ onDelete: (jobId: string) => void;+ onEdit: (jobId: string) => void;+}++const getIntervalText = (cronPattern: string) => {+ const intervalMap: Record<string, string> = {+ '0 */12 * * *': 'agentCronJobs.interval.12hours',+ '0 */30 * * *': 'agentCronJobs.interval.30min',+ '0 */6 * * *': 'agentCronJobs.interval.6hours',+ '0 0 * * *': 'agentCronJobs.interval.1hour',+ '0 0 0 * *': 'agentCronJobs.interval.daily',+ '0 0 0 * 0': 'agentCronJobs.interval.weekly',+ };++ return intervalMap[cronPattern] || cronPattern;+};++const getStatusInfo = (job: AgentCronJob) => {+ if (!job.enabled) {+ return { status: 'default' as const, text: 'agentCronJobs.status.disabled' };+ }++ if (job.remainingExecutions === 0) {+ return { status: 'error' as const, text: 'agentCronJobs.status.depleted' };+ }++ return { status: 'success' as const, text: 'agentCronJobs.status.enabled' };+};++const CronJobCards = memo<CronJobCardsProps>(({ cronJobs, loading, onDelete, onEdit }) => {+ const { t } = useTranslation('setting');+ const { updateCronJob } = useAgentCronJobs();++ const handleToggleEnabled = async (job: AgentCronJob) => {+ await updateCronJob(job.id, { enabled: !job.enabled });+ };++ return (+ <Row gutter={[12, 12]}>+ {cronJobs.map((job) => {+ const statusInfo = getStatusInfo(job);+ const intervalText = getIntervalText(job.cronPattern);++ return (+ <Col key={job.id} lg={8} md={12} xs={24}>+ <Card+ extra={+ <Flexbox align="center" gap={4} horizontal>+ <ActionIcon+ icon={Edit}+ onClick={() => onEdit(job.id)}+ size="small"+ title={t('agentCronJobs.editJob')}+ />+ <Popconfirm+ onConfirm={() => onDelete(job.id)}+ title={t('agentCronJobs.confirmDelete')}+ >+ <ActionIcon icon={Trash2} size="small" title={t('agentCronJobs.deleteJob')} />+ </Popconfirm>+ </Flexbox>+ }+ loading={loading}+ size="small"+ style={{ height: '100%' }}+ styles={{+ actions: { marginTop: 0 },+ body: { paddingBottom: 12, paddingTop: 8 },+ header: { borderBottom: 'none', marginTop: '8px', minHeight: 0, paddingBottom: 0 },+ }}+ title={+ <Flexbox align="center" horizontal justify="space-between">+ <Flexbox align="center" gap={8} horizontal style={{ flex: 1 }}>+ <span+ style={{+ fontSize: '13px',+ fontWeight: 500,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ }}+ >+ {job.name || 'Unnamed Task'}+ </span>+ <Badge status={statusInfo.status} />+ </Flexbox>+ <Switch+ checked={job.enabled || false}+ onChange={() => handleToggleEnabled(job)}+ size="small"+ />+ </Flexbox>+ }+ >+ <Flexbox gap={8}>+ <Text+ ellipsis={{ tooltip: job.content }}+ style={{+ WebkitBoxOrient: 'vertical',+ WebkitLineClamp: 2,+ color: '#666',+ display: '-webkit-box',+ fontSize: '12px',+ overflow: 'hidden',+ }}+ >+ {job.content}+ </Text>++ <Flexbox gap={8}>+ <Flexbox align="center" gap={6} horizontal>+ <Icon icon={Clock} size={12} />+ <Text style={{ fontSize: '11px' }}>{t(intervalText as any)}</Text>+ </Flexbox>++ {job.remainingExecutions !== null && (+ <Flexbox align="center" gap={6} horizontal>+ <Text style={{ fontSize: '11px' }}>+ {t('agentCronJobs.remainingExecutions', { count: job.remainingExecutions })}+ </Text>+ </Flexbox>+ )}++ {job.lastExecutedAt && (+ <Flexbox align="center" gap={6} horizontal>+ <Icon icon={Calendar} size={12} />+ <Text style={{ fontSize: '11px' }}>+ {dayjs(job.lastExecutedAt).format('MM/DD HH:mm')}+ </Text>+ </Flexbox>+ )}+ </Flexbox>+ </Flexbox>+ </Card>+ </Col>+ );+ })}+ </Row>+ );+});++export default CronJobCards;diff --git a/src/app/[variants]/(main)/chat/profile/features/AgentCronJobs/CronJobForm.tsx b/src/app/[variants]/(main)/chat/profile/features/AgentCronJobs/CronJobForm.tsxnew file mode 100644index 00000000000..515e79706d5--- /dev/null+++ b/src/app/[variants]/(main)/chat/profile/features/AgentCronJobs/CronJobForm.tsx@@ -0,0 +1,202 @@+'use client';++import { Checkbox, Form, Input, InputNumber, Select, TimePicker } from 'antd';+import dayjs from 'dayjs';+import { memo, useEffect } from 'react';+import { useTranslation } from 'react-i18next';++import type { AgentCronJob } from '@/database/schemas/agentCronJob';++// Form data interface - excludes server-managed fields+interface CronJobFormData {+ content: string;+ cronPattern: string;+ enabled?: boolean;+ executionConditions?: any;+ maxExecutions?: number | null;+ name?: string | null;+}++const { TextArea } = Input;++interface CronJobFormProps {+ editingJob?: AgentCronJob;+ formRef?: any;+ onCancel?: () => void;+ onSubmit: (data: CronJobFormData) => void;+}++const CRON_PATTERNS = [+ { label: 'agentCronJobs.interval.30min', value: '0 */30 * * *' },+ { label: 'agentCronJobs.interval.1hour', value: '0 0 * * *' },+ { label: 'agentCronJobs.interval.6hours', value: '0 */6 * * *' },+ { label: 'agentCronJobs.interval.12hours', value: '0 */12 * * *' },+ { label: 'agentCronJobs.interval.daily', value: '0 0 0 * *' },+ { label: 'agentCronJobs.interval.weekly', value: '0 0 0 * 0' },+];++const WEEKDAY_OPTIONS = [+ { label: 'Monday', value: 1 },+ { label: 'Tuesday', value: 2 },+ { label: 'Wednesday', value: 3 },+ { label: 'Thursday', value: 4 },+ { label: 'Friday', value: 5 },+ { label: 'Saturday', value: 6 },+ { label: 'Sunday', value: 0 },+];++const CronJobForm = memo<CronJobFormProps>(({ editingJob, formRef, onSubmit }) => {+ const { t } = useTranslation('setting');+ const [form] = Form.useForm();++ // Expose form instance via ref+ if (formRef) {+ formRef.current = form;+ }++ useEffect(() => {+ if (editingJob) {+ const conditions = editingJob.executionConditions;+ form.setFieldsValue({+ content: editingJob.content,+ cronPattern: editingJob.cronPattern,+ maxExecutions: editingJob.maxExecutions,+ maxExecutionsPerDay: conditions?.maxExecutionsPerDay,+ name: editingJob.name,+ timeRange: conditions?.timeRange+ ? [dayjs(conditions.timeRange.start, 'HH:mm'), dayjs(conditions.timeRange.end, 'HH:mm')]+ : undefined,+ weekdays: conditions?.weekdays || [],+ });+ } else {+ form.resetFields();+ }+ }, [editingJob, form]);++ const handleSubmit = async (values: any) => {+ const executionConditions: any = {};++ if (values.timeRange && values.timeRange.length === 2) {+ executionConditions.timeRange = {+ end: values.timeRange[1].format('HH:mm'),+ start: values.timeRange[0].format('HH:mm'),+ };+ }++ if (values.weekdays && values.weekdays.length > 0) {+ executionConditions.weekdays = values.weekdays;+ }++ if (values.maxExecutionsPerDay) {+ executionConditions.maxExecutionsPerDay = values.maxExecutionsPerDay;+ }++ const data: CronJobFormData = {+ content: values.content,+ cronPattern: values.cronPattern,+ enabled: true,+ executionConditions: Object.keys(executionConditions).length > 0 ? executionConditions : null,+ maxExecutions: values.maxExecutions || null,+ name: values.name,+ };++ onSubmit(data);+ };++ const validateTimeRange = (_: any, value: any) => {+ if (!value || value.length !== 2) {+ return Promise.resolve();+ }++ const [start, end] = value;+ if (start.isAfter(end)) {+ return Promise.reject(new Error(t('agentCronJobs.form.validation.invalidTimeRange')));+ }++ return Promise.resolve();+ };++ return (+ <Form+ form={form}+ initialValues={{+ cronPattern: '0 */30 * * *', // Default to 30 minutes+ weekdays: [],+ }}+ layout="vertical"+ onFinish={handleSubmit}+ >+ <Form.Item+ label={t('agentCronJobs.name')}+ name="name"+ rules={[{ message: t('agentCronJobs.form.validation.nameRequired'), required: true }]}+ >+ <Input placeholder={t('agentCronJobs.form.name.placeholder')} />+ </Form.Item>++ <Form.Item+ label={t('agentCronJobs.content')}+ name="content"+ rules={[{ message: t('agentCronJobs.form.validation.contentRequired'), required: true }]}+ >+ <TextArea+ maxLength={1000}+ placeholder={t('agentCronJobs.form.content.placeholder')}+ rows={3}+ showCount+ />+ </Form.Item>++ <Form.Item+ label={t('agentCronJobs.schedule')}+ name="cronPattern"+ rules={[{ required: true }]}+ >+ <Select>+ {CRON_PATTERNS.map((pattern) => (+ <Select.Option key={pattern.value} value={pattern.value}>+ {t(pattern.label as any)}+ </Select.Option>+ ))}+ </Select>+ </Form.Item>++ <Form.Item label={t('agentCronJobs.maxExecutions')} name="maxExecutions">+ <InputNumber+ min={1}+ placeholder={t('agentCronJobs.form.maxExecutions.placeholder')}+ style={{ width: '100%' }}+ />+ </Form.Item>++ <Form.Item+ label={t('agentCronJobs.timeRange')}+ name="timeRange"+ rules={[{ validator: validateTimeRange }]}+ >+ <TimePicker.RangePicker+ format="HH:mm"+ placeholder={[+ t('agentCronJobs.form.timeRange.start'),+ t('agentCronJobs.form.timeRange.end'),+ ]}+ style={{ width: '100%' }}+ />+ </Form.Item>++ <Form.Item label={t('agentCronJobs.weekdays')} name="weekdays">+ <Checkbox.Group options={WEEKDAY_OPTIONS} />+ </Form.Item>++ <Form.Item label="Max Executions Per Day" name="maxExecutionsPerDay">+ <InputNumber+ min={1}+ placeholder="Leave empty for no daily limit"+ style={{ width: '100%' }}+ />+ </Form.Item>+ </Form>+ );+});++export default CronJobForm;diff --git a/src/app/[variants]/(main)/chat/profile/features/AgentCronJobs/CronJobList.tsx b/src/app/[variants]/(main)/chat/profile/features/AgentCronJobs/CronJobList.tsxnew file mode 100644index 00000000000..13b03118282--- /dev/null+++ b/src/app/[variants]/(main)/chat/profile/features/AgentCronJobs/CronJobList.tsx@@ -0,0 +1,137 @@+'use client';++import { ActionIcon, Flexbox, Icon } from '@lobehub/ui';+import { Badge, List, Popconfirm, Switch, Typography } from 'antd';+import dayjs from 'dayjs';+import { Calendar, Clock, Edit, Trash2 } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import type { AgentCronJob } from '@/database/schemas/agentCronJob';++import { useAgentCronJobs } from './hooks/useAgentCronJobs';++const { Text, Paragraph } = Typography;++interface CronJobListProps {+ cronJobs: AgentCronJob[];+ loading?: boolean;+ onDelete: (jobId: string) => void;+ onEdit: (jobId: string) => void;+}++const getIntervalText = (cronPattern: string) => {+ const intervalMap: Record<string, string> = {+ '0 */12 * * *': 'agentCronJobs.interval.12hours',+ '0 */30 * * *': 'agentCronJobs.interval.30min',+ '0 */6 * * *': 'agentCronJobs.interval.6hours',+ '0 0 * * *': 'agentCronJobs.interval.1hour',+ '0 0 0 * *': 'agentCronJobs.interval.daily',+ '0 0 0 * 0': 'agentCronJobs.interval.weekly',+ };++ return intervalMap[cronPattern] || cronPattern;+};++const getStatusInfo = (job: AgentCronJob) => {+ if (!job.enabled) {+ return { status: 'default' as const, text: 'agentCronJobs.status.disabled' };+ }++ if (job.remainingExecutions === 0) {+ return { status: 'error' as const, text: 'agentCronJobs.status.depleted' };+ }++ return { status: 'success' as const, text: 'agentCronJobs.status.enabled' };+};++const CronJobList = memo<CronJobListProps>(({ cronJobs, loading, onEdit, onDelete }) => {+ const { t } = useTranslation('setting');+ const { updateCronJob } = useAgentCronJobs();++ const handleToggleEnabled = async (job: AgentCronJob) => {+ await updateCronJob(job.id, { enabled: !job.enabled });+ };++ return (+ <List+ dataSource={cronJobs}+ loading={loading}+ renderItem={(job) => {+ const statusInfo = getStatusInfo(job);+ const intervalText = getIntervalText(job.cronPattern);++ return (+ <List.Item+ actions={[+ <ActionIcon+ icon={Edit}+ key="edit"+ onClick={() => onEdit(job.id)}+ size="small"+ title={t('agentCronJobs.editJob')}+ />,+ <Popconfirm+ key="delete"+ onConfirm={() => onDelete(job.id)}+ title={t('agentCronJobs.confirmDelete')}+ >+ <ActionIcon icon={Trash2} size="small" title={t('agentCronJobs.deleteJob')} />+ </Popconfirm>,+ ]}+ >+ <List.Item.Meta+ avatar={+ <Switch+ checked={job.enabled || false}+ onChange={() => handleToggleEnabled(job)}+ size="small"+ />+ }+ description={+ <Flexbox gap={4}>+ <Paragraph+ ellipsis={{ rows: 2, tooltip: job.content }}+ style={{ color: '#666', fontSize: '12px', margin: 0 }}+ >+ {job.content}+ </Paragraph>++ <Flexbox gap={8} horizontal style={{ marginTop: 4 }}>+ <Flexbox align="center" gap={4} horizontal>+ <Icon icon={Clock} size={12} />+ <Text style={{ fontSize: '11px' }}>{t(intervalText as any)}</Text>+ </Flexbox>++ {job.remainingExecutions !== null && (+ <Text style={{ fontSize: '11px' }}>+ {t('agentCronJobs.remainingExecutions', { count: job.remainingExecutions })}+ </Text>+ )}++ {job.lastExecutedAt && (+ <Flexbox align="center" gap={4} horizontal>+ <Icon icon={Calendar} size={12} />+ <Text style={{ fontSize: '11px' }}>+ {dayjs(job.lastExecutedAt).format('MM/DD HH:mm')}+ </Text>+ </Flexbox>+ )}+ </Flexbox>+ </Flexbox>+ }+ title={+ <Flexbox align="center" gap={8} horizontal>+ <span>{job.name}</span>+ <Badge status={statusInfo.status} text={t(statusInfo.text as any)} />+ </Flexbox>+ }+ />+ </List.Item>+ );+ }}+ />+ );+});++export default CronJobList;diff --git a/src/app/[variants]/(main)/chat/profile/features/AgentCronJobs/hooks/useAgentCronJobs.ts b/src/app/[variants]/(main)/chat/profile/features/AgentCronJobs/hooks/useAgentCronJobs.tsnew file mode 100644index 00000000000..8594a3db05e--- /dev/null+++ b/src/app/[variants]/(main)/chat/profile/features/AgentCronJobs/hooks/useAgentCronJobs.ts@@ -0,0 +1,138 @@+import { ENABLE_BUSINESS_FEATURES } from '@lobechat/business-const';+import { message } from 'antd';+import { useCallback } from 'react';+import { useTranslation } from 'react-i18next';+import useSWR from 'swr';++import type {+ CreateAgentCronJobData,+ UpdateAgentCronJobData,+} from '@/database/schemas/agentCronJob';+import { agentCronJobService } from '@/services/agentCronJob';++export const useAgentCronJobs = (agentId?: string) => {+ const { t } = useTranslation('setting');++ // Fetch cron jobs for the agent+ const {+ data: cronJobs,+ error,+ isLoading: loading,+ mutate,+ } = useSWR(+ ENABLE_BUSINESS_FEATURES && agentId ? `/api/agent-cron-jobs/${agentId}` : null,+ ENABLE_BUSINESS_FEATURES && agentId ? () => agentCronJobService.getByAgentId(agentId) : null,+ {+ onError: (error) => {+ console.error('Failed to fetch cron jobs:', error);+ message.error('Failed to load scheduled tasks');+ },+ },+ );++ // Create a new cron job+ const createCronJob = useCallback(+ async (data: Omit<CreateAgentCronJobData, 'userId'>) => {+ if (!agentId) return;++ try {+ const result = await agentCronJobService.create({+ ...data,+ agentId,+ });++ if (result.success) {+ message.success(t('agentCronJobs.createSuccess'));+ await mutate();+ return result.data;+ }+ } catch (error) {+ console.error('Failed to create cron job:', error);+ message.error('Failed to create scheduled task');+ throw error;+ }+ },+ [agentId, mutate, t],+ );++ // Update a cron job+ const updateCronJob = useCallback(+ async (id: string, data: UpdateAgentCronJobData) => {+ try {+ const result = await agentCronJobService.update(id, data);++ if (result.success) {+ message.success(t('agentCronJobs.updateSuccess'));+ await mutate();+ return result.data;+ }+ } catch (error) {+ console.error('Failed to update cron job:', error);+ message.error('Failed to update scheduled task');+ throw error;+ }+ },+ [mutate, t],+ );++ // Delete a cron job+ const deleteCronJob = useCallback(+ async (id: string) => {+ try {+ const result = await agentCronJobService.delete(id);++ if (result.success) {+ message.success(t('agentCronJobs.deleteSuccess'));+ await mutate();+ }+ } catch (error) {+ console.error('Failed to delete cron job:', error);+ message.error('Failed to delete scheduled task');+ throw error;+ }+ },+ [mutate, t],+ );++ // Get execution statistics+ const getStats = useCallback(async () => {+ try {+ return await agentCronJobService.getStats();+ } catch (error) {+ console.error('Failed to get cron job stats:', error);+ throw error;+ }+ }, []);++ // Reset execution counts+ const resetExecutions = useCallback(+ async (id: string, newMaxExecutions?: number) => {+ try {+ const result = await agentCronJobService.resetExecutions(id, newMaxExecutions);++ if (result.success) {+ message.success('Execution counts reset successfully');+ await mutate();+ return result.data;+ }+ } catch (error) {+ console.error('Failed to reset executions:', error);+ message.error('Failed to reset execution counts');+ throw error;+ }+ },+ [mutate],+ );++ return {+ createCronJob,+ cronJobs: cronJobs?.data || [],+ deleteCronJob,+ error,+ getStats,+ loading,+ refetch: mutate,+ resetExecutions,+ updateCronJob,+ };+};diff --git a/src/app/[variants]/(main)/chat/profile/features/AgentCronJobs/index.tsx b/src/app/[variants]/(main)/chat/profile/features/AgentCronJobs/index.tsxnew file mode 100644index 00000000000..4a273a02757--- /dev/null+++ b/src/app/[variants]/(main)/chat/profile/features/AgentCronJobs/index.tsx@@ -0,0 +1,130 @@+'use client';++import { ENABLE_BUSINESS_FEATURES } from '@lobechat/business-const';+import { Flexbox } from '@lobehub/ui';+import { Modal, Typography } from 'antd';+import { Clock } from 'lucide-react';+import { memo, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useAgentStore } from '@/store/agent';++import CronJobCards from './CronJobCards';+import CronJobForm from './CronJobForm';+import { useAgentCronJobs } from './hooks/useAgentCronJobs';++const { Title } = Typography;++interface AgentCronJobsProps {+ onFormModalChange?: (show: boolean) => void;+ showFormModal?: boolean;+}++const AgentCronJobs = memo<AgentCronJobsProps>(({ showFormModal, onFormModalChange }) => {+ const { t } = useTranslation('setting');+ const agentId = useAgentStore((s) => s.activeAgentId);+ const [internalShowForm, setInternalShowForm] = useState(false);+ const [editingJob, setEditingJob] = useState<string | null>(null);+ const [submitting, setSubmitting] = useState(false);+ const formRef = useRef<any>(null);++ // Use external control if provided, otherwise use internal state+ const showForm = showFormModal ?? internalShowForm;+ const setShowForm = onFormModalChange ?? setInternalShowForm;++ const { cronJobs, loading, createCronJob, updateCronJob, deleteCronJob } =+ useAgentCronJobs(agentId);++ if (!ENABLE_BUSINESS_FEATURES) return null;++ if (!agentId) {+ return null;+ }++ const handleCreate = async (data: any) => {+ setSubmitting(true);+ try {+ await createCronJob(data);+ setShowForm(false);+ } finally {+ setSubmitting(false);+ }+ };++ const handleEdit = (jobId: string) => {+ setEditingJob(jobId);+ setShowForm(true);+ };++ const handleUpdate = async (data: any) => {+ if (editingJob) {+ setSubmitting(true);+ try {+ await updateCronJob(editingJob, data);+ setShowForm(false);+ setEditingJob(null);+ } finally {+ setSubmitting(false);+ }+ }+ };++ const handleCancel = () => {+ setShowForm(false);+ setEditingJob(null);+ formRef.current?.resetFields();+ };++ const handleModalOk = () => {+ formRef.current?.submit();+ };++ const handleDelete = async (jobId: string) => {+ await deleteCronJob(jobId);+ };++ const hasCronJobs = cronJobs && cronJobs.length > 0;++ return (+ <>+ {/* Show cards section only if there are jobs */}+ {hasCronJobs && (+ <Flexbox gap={12} style={{ marginBottom: 16, marginTop: 16 }}>+ <Title level={5} style={{ margin: 0 }}>+ <Flexbox align="center" gap={8} horizontal>+ <Clock size={16} />+ {t('agentCronJobs.title')}+ </Flexbox>+ </Title>++ <CronJobCards+ cronJobs={cronJobs}+ loading={loading}+ onDelete={handleDelete}+ onEdit={handleEdit}+ />+ </Flexbox>+ )}++ {/* Form Modal */}+ <Modal+ confirmLoading={submitting}+ okText={editingJob ? t('agentCronJobs.save' as any) : t('agentCronJobs.create' as any)}+ onCancel={handleCancel}+ onOk={handleModalOk}+ open={showForm}+ title={editingJob ? t('agentCronJobs.editJob') : t('agentCronJobs.addJob')}+ width={640}+ >+ <CronJobForm+ editingJob={editingJob ? cronJobs?.find((job) => job.id === editingJob) : undefined}+ formRef={formRef}+ onCancel={handleCancel}+ onSubmit={editingJob ? handleUpdate : handleCreate}+ />+ </Modal>+ </>+ );+});++export default AgentCronJobs;diff --git a/src/app/[variants]/(main)/chat/profile/features/ProfileEditor/index.tsx b/src/app/[variants]/(main)/chat/profile/features/ProfileEditor/index.tsxindex 738593a4e5e..11d7d328012 100644--- a/src/app/[variants]/(main)/chat/profile/features/ProfileEditor/index.tsx+++ b/src/app/[variants]/(main)/chat/profile/features/ProfileEditor/index.tsx@@ -1,19 +1,22 @@'use client';+import { ENABLE_BUSINESS_FEATURES } from '@lobechat/business-const';import { Button, Flexbox } from '@lobehub/ui';-import { Divider } from 'antd';+import { Divider, message } from 'antd';import isEqual from 'fast-deep-equal';-import { PlayIcon } from 'lucide-react';-import React, { memo } from 'react';+import { Clock, PlayIcon } from 'lucide-react';+import React, { memo, useCallback } from 'react';import { useTranslation } from 'react-i18next';import urlJoin from 'url-join';import ModelSelect from '@/features/ModelSelect';import { useQueryRoute } from '@/hooks/useQueryRoute';+import { agentCronJobService } from '@/services/agentCronJob';import { useAgentStore } from '@/store/agent';import { agentSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';+import AgentCronJobs from '../AgentCronJobs';import EditorCanvas from '../EditorCanvas';import AgentHeader from './AgentHeader';import AgentTool from './AgentTool';@@ -26,6 +29,26 @@ const ProfileEditor = memo(() => {const switchTopic = useChatStore((s) => s.switchTopic);const router = useQueryRoute();+ const handleCreateCronJob = useCallback(async () => {+ if (!agentId) return;+ try {+ const result = await agentCronJobService.create({+ agentId,+ content: t('agentCronJobs.form.content.placeholder') || 'This is a cron job',+ cronPattern: '0 */30 * * *',+ enabled: true,+ name: t('agentCronJobs.addJob') || 'Cron Job Task',+ });++ if (result.success) {+ router.push(urlJoin('/agent', agentId, 'cron', result.data.id));+ }+ } catch (error) {+ console.error('Failed to create cron job:', error);+ message.error('Failed to create scheduled task');+ }+ }, [agentId, router, t]);+return (<><Flexbox@@ -72,11 +95,18 @@ const ProfileEditor = memo(() => {>{t('startConversation')}</Button>+ {ENABLE_BUSINESS_FEATURES && (+ <Button icon={Clock} onClick={handleCreateCronJob}>+ {t('agentCronJobs.addJob')}+ </Button>+ )}</Flexbox></Flexbox><Divider />{/* Main Content: Prompt Editor */}<EditorCanvas />+ {/* Agent Cron Jobs Display (only show if jobs exist) */}+ {ENABLE_BUSINESS_FEATURES && <AgentCronJobs />}</>);});diff --git a/src/app/[variants]/router/desktopRouter.config.tsx b/src/app/[variants]/router/desktopRouter.config.tsxindex 18c25154681..8d86d8bdd3a 100644--- a/src/app/[variants]/router/desktopRouter.config.tsx+++ b/src/app/[variants]/router/desktopRouter.config.tsx@@ -39,6 +39,13 @@ export const desktopRoutes: RouteConfig[] = [),path: 'profile',},+ {+ element: dynamicElement(+ () => import('../(main)/chat/cron/[cronId]'),+ 'Desktop > Chat > Cron Detail',+ ),+ path: 'cron/:cronId',+ },],element: <DesktopChatLayout />,errorElement: <ErrorBoundary resetPath="/agent" />,diff --git a/src/hooks/useFetchCronTopics.ts b/src/hooks/useFetchCronTopics.tsnew file mode 100644index 00000000000..02e5c4b76e8--- /dev/null+++ b/src/hooks/useFetchCronTopics.ts@@ -0,0 +1,29 @@+import useSWR from 'swr';++import { lambdaClient } from '@/libs/trpc/client/lambda';+import { useAgentStore } from '@/store/agent';++/**+ * Fetch cron topics grouped by cronJob for the current agent+ */+export const useFetchCronTopics = () => {+ const agentId = useAgentStore((s) => s.activeAgentId);++ const { data, isLoading, error, mutate } = useSWR(+ agentId ? ['cronTopics', agentId] : null,+ async () => {+ if (!agentId) return [];+ return await lambdaClient.topic.getCronTopicsGroupedByCronJob.query({ agentId });+ },+ {+ revalidateOnFocus: false,+ },+ );++ return {+ cronTopicsGroups: data || [],+ error,+ isLoading,+ mutate,+ };+};diff --git a/src/hooks/useFetchCronTopicsWithJobInfo.ts b/src/hooks/useFetchCronTopicsWithJobInfo.tsnew file mode 100644index 00000000000..2141ba36c0a--- /dev/null+++ b/src/hooks/useFetchCronTopicsWithJobInfo.ts@@ -0,0 +1,56 @@+import { ENABLE_BUSINESS_FEATURES } from '@lobechat/business-const';+import useSWR from 'swr';++import { lambdaClient } from '@/libs/trpc/client/lambda';+import { useAgentStore } from '@/store/agent';++/**+ * Fetch cron topics grouped by cronJob with job information+ */+export const useFetchCronTopicsWithJobInfo = () => {+ const agentId = useAgentStore((s) => s.activeAgentId);++ const { data, isLoading, error, mutate } = useSWR(+ ENABLE_BUSINESS_FEATURES && agentId ? ['cronTopicsWithJobInfo', agentId] : null,+ async () => {+ if (!agentId) return [];++ const [cronJobsResult, cronTopicsGroups] = await Promise.all([+ lambdaClient.agentCronJob.findByAgent.query({ agentId }),+ lambdaClient.topic.getCronTopicsGroupedByCronJob.query({ agentId }),+ ]);++ const cronJobs = cronJobsResult.success ? cronJobsResult.data : [];+ const topicsByCronId = new Map(+ cronTopicsGroups.map((group) => [group.cronJobId, group.topics]),+ );+ const cronJobIds = new Set(cronJobs.map((job) => job.id));++ const groupsWithJobs = cronJobs.map((job) => ({+ cronJob: job,+ cronJobId: job.id,+ topics: topicsByCronId.get(job.id) || [],+ }));++ const orphanGroups = cronTopicsGroups+ .filter((group) => !cronJobIds.has(group.cronJobId))+ .map((group) => ({+ cronJob: null,+ cronJobId: group.cronJobId,+ topics: group.topics,+ }));++ return [...groupsWithJobs, ...orphanGroups];+ },+ {+ revalidateOnFocus: false,+ },+ );++ return {+ cronTopicsGroupsWithJobInfo: data || [],+ error,+ isLoading,+ mutate,+ };+};diff --git a/src/hooks/useFetchTopics.ts b/src/hooks/useFetchTopics.tsindex e555583b61d..29a1dad4a02 100644--- a/src/hooks/useFetchTopics.ts+++ b/src/hooks/useFetchTopics.ts@@ -7,7 +7,7 @@ import { systemStatusSelectors } from '@/store/global/selectors';/*** Fetch topics for the current session (agent or group)*/-export const useFetchTopics = () => {+export const useFetchTopics = (options?: { excludeTriggers?: string[] }) => {const isInbox = useAgentStore(builtinAgentSelectors.isInboxAgent);const [activeAgentId, activeGroupId, useFetchTopicsHook] = useChatStore((s) => [s.activeAgentId,@@ -20,6 +20,9 @@ export const useFetchTopics = () => {// If in group session, use groupId; otherwise use agentIdconst { isValidating, data } = useFetchTopicsHook(true, {agentId: activeAgentId,+ ...(options?.excludeTriggers && options.excludeTriggers.length > 0+ ? { excludeTriggers: options.excludeTriggers }+ : {}),groupId: activeGroupId,isInbox: activeGroupId ? false : isInbox,pageSize: topicPageSize,diff --git a/src/locales/default/setting.ts b/src/locales/default/setting.tsindex 6f31b4283d3..f6e730073ff 100644--- a/src/locales/default/setting.ts+++ b/src/locales/default/setting.ts@@ -2,11 +2,54 @@ export default {'_cloud.officialProvider': '{{name}} Official Model Service','about.title': 'About','advancedSettings': 'Advanced Settings',+ 'agentCronJobs.addJob': 'Add Scheduled Task',+ 'agentCronJobs.confirmDelete': 'Are you sure you want to delete this scheduled task?',+ 'agentCronJobs.content': 'Task Content',+ 'agentCronJobs.create': 'Create',+ 'agentCronJobs.createSuccess': 'Scheduled task created successfully',+ 'agentCronJobs.deleteJob': 'Delete Task',+ 'agentCronJobs.deleteSuccess': 'Scheduled task deleted successfully',+ 'agentCronJobs.description': 'Automate your agent with scheduled executions',+ 'agentCronJobs.disable': 'Disable',+ 'agentCronJobs.editJob': 'Edit Scheduled Task',+ 'agentCronJobs.empty.description': 'Create your first scheduled task to automate your agent',+ 'agentCronJobs.empty.title': 'No scheduled tasks yet',+ 'agentCronJobs.enable': 'Enable',+ 'agentCronJobs.form.content.placeholder': 'Enter the prompt or instruction for the agent',+ 'agentCronJobs.form.maxExecutions.placeholder': 'Leave empty for unlimited',+ 'agentCronJobs.form.name.placeholder': 'Enter task name',+ 'agentCronJobs.form.timeRange.end': 'End Time',+ 'agentCronJobs.form.timeRange.start': 'Start Time',+ 'agentCronJobs.form.validation.contentRequired': 'Task content is required',+ 'agentCronJobs.form.validation.invalidTimeRange': 'Start time must be before end time',+ 'agentCronJobs.form.validation.nameRequired': 'Task name is required',+ 'agentCronJobs.interval.12hours': 'Every 12 hours',+ 'agentCronJobs.interval.1hour': 'Every hour',+ 'agentCronJobs.interval.30min': 'Every 30 minutes',+ 'agentCronJobs.interval.6hours': 'Every 6 hours',+ 'agentCronJobs.interval.daily': 'Daily',+ 'agentCronJobs.interval.weekly': 'Weekly',+ 'agentCronJobs.lastExecuted': 'Last Executed',+ 'agentCronJobs.maxExecutions': 'Max Executions',+ 'agentCronJobs.name': 'Task Name',+ 'agentCronJobs.never': 'Never',+ 'agentCronJobs.remainingExecutions': 'Remaining: {{count}}',+ 'agentCronJobs.save': 'Save',+ 'agentCronJobs.schedule': 'Schedule',+ 'agentCronJobs.status.depleted': 'Depleted',+ 'agentCronJobs.status.disabled': 'Disabled',+ 'agentCronJobs.status.enabled': 'Enabled',+ 'agentCronJobs.timeRange': 'Time Range',+ 'agentCronJobs.title': 'Scheduled Tasks',+ 'agentCronJobs.unlimited': 'Unlimited',+ 'agentCronJobs.updateSuccess': 'Scheduled task updated successfully',+ 'agentCronJobs.weekdays': 'Weekdays','agentInfoDescription.basic.avatar': 'Avatar','agentInfoDescription.basic.description': 'Description','agentInfoDescription.basic.name': 'Name','agentInfoDescription.basic.tags': 'Tags','agentInfoDescription.basic.title': 'Agent info',+'agentInfoDescription.chat.enableHistoryCount': 'Enable Message History Count','agentInfoDescription.chat.historyCount': 'Message History Count','agentInfoDescription.chat.no': 'No',@@ -47,7 +90,7 @@ export default {'danger.reset.action': 'Reset Now','danger.reset.confirm': 'Reset all settings?','danger.reset.currentVersion': 'Current Version',- 'danger.reset.desc': 'Restore all settings to defaults. Your data won’t be deleted.',+ 'danger.reset.desc': 'Restore all settings to defaults. Your data wont be deleted.','danger.reset.success': 'All settings have been reset','danger.reset.title': 'Reset All Settings','defaultAgent.model.desc': 'Default model used when creating a new Agent',diff --git a/src/server/routers/lambda/agentCronJob.ts b/src/server/routers/lambda/agentCronJob.tsnew file mode 100644index 00000000000..bf2b687d7ef--- /dev/null+++ b/src/server/routers/lambda/agentCronJob.ts@@ -0,0 +1,367 @@+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import { AgentCronJobModel } from '@/database/models/agentCronJob';+import {+ type CreateAgentCronJobData,+ type UpdateAgentCronJobData,+ insertAgentCronJobSchema,+ updateAgentCronJobSchema,+} from '@/database/schemas/agentCronJob';+import { authedProcedure, router } from '@/libs/trpc/lambda';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';++const agentCronJobProcedure = authedProcedure.use(serverDatabase);++const listQuerySchema = z.object({+ agentId: z.string().optional(),+ enabled: z.boolean().optional(),+ limit: z.number().min(1).max(100).default(20),+ offset: z.number().min(0).default(0),+});++const resetExecutionsSchema = z.object({+ id: z.string(),+ newMaxExecutions: z.number().min(1).max(10_000).optional(),+});++const batchUpdateStatusSchema = z.object({+ enabled: z.boolean(),+ ids: z.array(z.string()),+});++// Create input schema for tRPC that omits server-managed fields+const createAgentCronJobInputSchema = insertAgentCronJobSchema.omit({+ userId: true, // Provided by authentication context+});++/**+ * Agent Cron Job tRPC Router+ *+ * Provides type-safe API for managing agent scheduled tasks+ */+export const agentCronJobRouter = router({+ /**+ * Batch update status (enable/disable) for multiple jobs+ */+ batchUpdateStatus: agentCronJobProcedure+ .input(batchUpdateStatusSchema)+ .mutation(async ({ input, ctx }) => {+ const { userId, serverDB: db } = ctx;+ const { ids, enabled } = input;++ try {+ const cronJobModel = new AgentCronJobModel(db, userId);+ const updatedCount = await cronJobModel.batchUpdateStatus(ids, enabled);++ return {+ data: { updatedCount },+ message: `${updatedCount} cron jobs ${enabled ? 'enabled' : 'disabled'} successfully`,+ success: true,+ };+ } catch (error) {+ console.error('[agentCronJob:batchUpdateStatus]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to update cron job statuses',+ });+ }+ }),++ /**+ * Create a new cron job+ */+ create: agentCronJobProcedure+ .input(createAgentCronJobInputSchema)+ .mutation(async ({ input, ctx }) => {+ const { userId, serverDB: db } = ctx;++ try {+ const cronJobModel = new AgentCronJobModel(db, userId);+ // Add userId to the input data since it's provided by authentication context+ const cronJobData = { ...input, userId };+ const cronJob = await cronJobModel.create(cronJobData as CreateAgentCronJobData);++ return {+ data: cronJob,+ message: 'Cron job created successfully',+ success: true,+ };+ } catch (error) {+ console.error('[agentCronJob:create]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to create cron job',+ });+ }+ }),++ /**+ * Delete a cron job+ */+ delete: agentCronJobProcedure+ .input(z.object({ id: z.string() }))+ .mutation(async ({ input, ctx }) => {+ const { userId, serverDB: db } = ctx;+ const { id } = input;++ try {+ const cronJobModel = new AgentCronJobModel(db, userId);+ const deleted = await cronJobModel.delete(id);++ if (!deleted) {+ throw new TRPCError({+ code: 'NOT_FOUND',+ message: 'Cron job not found or access denied',+ });+ }++ return {+ message: 'Cron job deleted successfully',+ success: true,+ };+ } catch (error) {+ if (error instanceof TRPCError) throw error;++ console.error('[agentCronJob:delete]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to delete cron job',+ });+ }+ }),++ /**+ * List cron jobs by agent ID+ */+ findByAgent: agentCronJobProcedure+ .input(z.object({ agentId: z.string() }))+ .query(async ({ input, ctx }) => {+ const { userId, serverDB: db } = ctx;+ const { agentId } = input;++ try {+ const cronJobModel = new AgentCronJobModel(db, userId);+ const cronJobs = await cronJobModel.findByAgentId(agentId);++ return {+ data: cronJobs,+ success: true,+ };+ } catch (error) {+ console.error('[agentCronJob:findByAgent]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to fetch agent cron jobs',+ });+ }+ }),++ /**+ * Get a single cron job by ID+ */+ findById: agentCronJobProcedure+ .input(z.object({ id: z.string() }))+ .query(async ({ input, ctx }) => {+ const { userId, serverDB: db } = ctx;+ const { id } = input;++ try {+ const cronJobModel = new AgentCronJobModel(db, userId);+ const cronJob = await cronJobModel.findById(id);++ if (!cronJob) {+ throw new TRPCError({+ code: 'NOT_FOUND',+ message: 'Cron job not found',+ });+ }++ return {+ data: cronJob,+ success: true,+ };+ } catch (error) {+ if (error instanceof TRPCError) throw error;++ console.error('[agentCronJob:findById]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to fetch cron job',+ });+ }+ }),++ /**+ * Get jobs that are near depletion (for warnings)+ */+ getNearDepletion: agentCronJobProcedure+ .input(z.object({ threshold: z.number().min(1).max(20).default(5) }))+ .query(async ({ input, ctx }) => {+ const { userId, serverDB: db } = ctx;+ const { threshold } = input;++ try {+ const cronJobModel = new AgentCronJobModel(db, userId);+ const jobs = await cronJobModel.getTasksNearDepletion(threshold);++ return {+ data: jobs,+ success: true,+ };+ } catch (error) {+ console.error('[agentCronJob:getNearDepletion]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to fetch near depletion jobs',+ });+ }+ }),++ /**+ * Get execution statistics for user's cron jobs+ */+ getStats: agentCronJobProcedure.query(async ({ ctx }) => {+ const { userId, serverDB: db } = ctx;++ try {+ const cronJobModel = new AgentCronJobModel(db, userId);+ const stats = await cronJobModel.getExecutionStats();++ return {+ data: stats,+ success: true,+ };+ } catch (error) {+ console.error('[agentCronJob:getStats]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to fetch execution statistics',+ });+ }+ }),++ /**+ * List cron jobs with filtering and pagination+ */+ list: agentCronJobProcedure.input(listQuerySchema).query(async ({ input, ctx }) => {+ const { userId, serverDB: db } = ctx;+ const { agentId, enabled, limit, offset } = input;++ try {+ const cronJobModel = new AgentCronJobModel(db, userId);+ const result = await cronJobModel.findWithPagination({+ agentId,+ enabled,+ limit,+ offset,+ });++ return {+ data: result.jobs,+ pagination: {+ hasMore: offset + limit < result.total,+ limit,+ offset,+ total: result.total,+ },+ success: true,+ };+ } catch (error) {+ console.error('[agentCronJob:list]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to fetch cron jobs',+ });+ }+ }),++ /**+ * Reset execution counts for a cron job+ */+ resetExecutions: agentCronJobProcedure+ .input(resetExecutionsSchema)+ .mutation(async ({ input, ctx }) => {+ const { userId, serverDB: db } = ctx;+ const { id, newMaxExecutions } = input;++ try {+ const cronJobModel = new AgentCronJobModel(db, userId);+ const cronJob = await cronJobModel.resetExecutions(id, newMaxExecutions);++ if (!cronJob) {+ throw new TRPCError({+ code: 'NOT_FOUND',+ message: 'Cron job not found or access denied',+ });+ }++ return {+ data: cronJob,+ message: 'Execution counts reset successfully',+ success: true,+ };+ } catch (error) {+ if (error instanceof TRPCError) throw error;++ console.error('[agentCronJob:resetExecutions]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to reset execution counts',+ });+ }+ }),++ /**+ * Update a cron job+ */+ update: agentCronJobProcedure+ .input(+ z.object({+ data: updateAgentCronJobSchema,+ id: z.string(),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ const { userId, serverDB: db } = ctx;+ const { id, data } = input;++ try {+ const cronJobModel = new AgentCronJobModel(db, userId);+ const cronJob = await cronJobModel.update(id, data as UpdateAgentCronJobData);++ if (!cronJob) {+ throw new TRPCError({+ code: 'NOT_FOUND',+ message: 'Cron job not found or access denied',+ });+ }++ return {+ data: cronJob,+ message: 'Cron job updated successfully',+ success: true,+ };+ } catch (error) {+ if (error instanceof TRPCError) throw error;++ console.error('[agentCronJob:update]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to update cron job',+ });+ }+ }),++ // Note: testExecution moved to cloud layer since it uses AgentCronWorkflow+});diff --git a/src/server/routers/lambda/image/index.test.ts b/src/server/routers/lambda/image/index.test.tsindex 995cfca8a10..d383271bbb8 100644--- a/src/server/routers/lambda/image/index.test.ts+++ b/src/server/routers/lambda/image/index.test.ts@@ -2,6 +2,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { AsyncTaskStatus, AsyncTaskType } from '@/types/asyncTask';+import { imageRouter } from './index';+// Use vi.hoisted for variables used in vi.mock factoryconst {mockServerDB,@@ -79,8 +81,6 @@ vi.mock('@/utils/number', () => ({generateUniqueSeeds: vi.fn((count: number) => Array.from({ length: count }, (_, i) => 1000 + i)),}));-import { imageRouter } from './index';-describe('imageRouter', () => {const mockUserId = 'test-user-id';const mockAsyncCallerCreateImage = vi.fn();diff --git a/src/server/routers/lambda/index.ts b/src/server/routers/lambda/index.tsindex 7ba8b49f578..5337d33d11b 100644--- a/src/server/routers/lambda/index.ts+++ b/src/server/routers/lambda/index.ts@@ -8,6 +8,7 @@ import { topUpRouter } from '@/business/server/lambda-routers/topUp';import { publicProcedure, router } from '@/libs/trpc/lambda';import { agentRouter } from './agent';+import { agentCronJobRouter } from './agentCronJob';import { agentGroupRouter } from './agentGroup';import { aiAgentRouter } from './aiAgent';import { aiChatRouter } from './aiChat';@@ -46,6 +47,7 @@ import { userMemoryRouter } from './userMemory';export const lambdaRouter = router({agent: agentRouter,+ agentCronJob: agentCronJobRouter,aiAgent: aiAgentRouter,aiChat: aiChatRouter,aiModel: aiModelRouter,diff --git a/src/server/routers/lambda/topic.ts b/src/server/routers/lambda/topic.tsindex 5248a89465a..ce399133661 100644--- a/src/server/routers/lambda/topic.ts+++ b/src/server/routers/lambda/topic.ts@@ -142,11 +142,18 @@ export const topicRouter = router({return ctx.topicModel.queryAll();}),+ getCronTopicsGroupedByCronJob: topicProcedure+ .input(z.object({ agentId: z.string() }))+ .query(async ({ input, ctx }) => {+ return ctx.topicModel.getCronTopicsGroupedByCronJob(input.agentId);+ }),+getTopics: topicProcedure.input(z.object({agentId: z.string().nullable().optional(),current: z.number().optional(),+ excludeTriggers: z.array(z.string()).optional(),groupId: z.string().nullable().optional(),isInbox: z.boolean().optional(),pageSize: z.number().optional(),@@ -154,11 +161,11 @@ export const topicRouter = router({}),).query(async ({ input, ctx }) => {- const { sessionId, isInbox, groupId, ...rest } = input;+ const { sessionId, isInbox, groupId, excludeTriggers, ...rest } = input;// If groupId is provided, query by groupId directlyif (groupId) {- const result = await ctx.topicModel.query({ groupId, ...rest });+ const result = await ctx.topicModel.query({ excludeTriggers, groupId, ...rest });return { items: result.items, total: result.total };}@@ -168,7 +175,12 @@ export const topicRouter = router({effectiveAgentId = await resolveAgentIdFromSession(sessionId, ctx.serverDB, ctx.userId);}- const result = await ctx.topicModel.query({ ...rest, agentId: effectiveAgentId, isInbox });+ const result = await ctx.topicModel.query({+ ...rest,+ agentId: effectiveAgentId,+ excludeTriggers,+ isInbox,+ });// Runtime migration: backfill agentId for ALL legacy topics and messages under this agentconst runMigration = async () => {diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.tsindex 9f9fbd5310b..eb15407cb8c 100644--- a/src/server/services/aiAgent/index.ts+++ b/src/server/services/aiAgent/index.ts@@ -33,8 +33,12 @@ const log = debug('lobe-server:ai-agent-service');* This extends the public ExecAgentParams with server-side only options*/interface InternalExecAgentParams extends ExecAgentParams {+ /** Cron job ID that triggered this execution (if trigger is 'cron') */+ cronJobId?: string;/** Step lifecycle callbacks for operation tracking (server-side only) */stepCallbacks?: StepLifecycleCallbacks;+ /** Topic creation trigger source ('cron' | 'chat' | 'api') */+ trigger?: string;}/**@@ -88,6 +92,8 @@ export class AiAgentService {autoStart = true,existingMessageIds = [],stepCallbacks,+ trigger,+ cronJobId,} = params;// Validate that either agentId or slug is provided@@ -114,12 +120,22 @@ export class AiAgentService {// 2. Handle topic creation: if no topicId provided, create a new topic; otherwise reuse existinglet topicId = appContext?.topicId;if (!topicId) {+ // Prepare metadata with cronJobId if provided+ const metadata = cronJobId ? { cronJobId } : undefined;+const newTopic = await this.topicModel.create({agentId: resolvedAgentId,+ metadata,title: prompt.slice(0, 50) + (prompt.length > 50 ? '...' : ''),+ trigger,});topicId = newTopic.id;- log('execAgent: created new topic %s', topicId);+ log(+ 'execAgent: created new topic %s with trigger %s, cronJobId %s',+ topicId,+ trigger || 'default',+ cronJobId || 'none',+ );} else {log('execAgent: reusing existing topic %s', topicId);}@@ -397,6 +413,7 @@ export class AiAgentService {groupId,messages: newTopic?.topicMessageIds,title: topicTitle,+ // Note: execGroupAgent doesn't have trigger param yet, defaults to null});topicId = topicItem.id;isCreateNewTopic = true;diff --git a/src/server/services/memory/userMemory/extract.ts b/src/server/services/memory/userMemory/extract.tsindex 0a3c9f312e6..cac7685e246 100644--- a/src/server/services/memory/userMemory/extract.ts+++ b/src/server/services/memory/userMemory/extract.ts@@ -4,21 +4,20 @@ import {} from '@lobechat/const';import { messages, topics } from '@lobechat/database/schemas';import {+ BenchmarkLocomoContextProvider,LobeChatTopicContextProvider,LobeChatTopicResultRecorder,MemoryExtractionService,RetrievalUserMemoryContextProvider,RetrievalUserMemoryIdentitiesProvider,- BenchmarkLocomoContextProvider,} from '@lobechat/memory-user-memory';import type {+ BenchmarkLocomoPart,MemoryExtractionAgent,MemoryExtractionJob,MemoryExtractionResult,- BenchmarkLocomoPart,PersistedMemoryResult,} from '@lobechat/memory-user-memory';-import { UserMemorySourceBenchmarkLoCoMoModel } from '@/database/models/userMemory/sources/benchmarkLoCoMo';import { ModelRuntime } from '@lobechat/model-runtime';import type {Embeddings,@@ -45,6 +44,7 @@ import type {MemoryExtractionTracePayload,} from '@lobechat/types';import { Client } from '@upstash/workflow';+import debug from 'debug';import { and, asc, eq, inArray } from 'drizzle-orm';import { join } from 'pathe';import { z } from 'zod';@@ -54,6 +54,7 @@ import { TopicModel } from '@/database/models/topic';import type { ListUsersForMemoryExtractorCursor } from '@/database/models/user';import { UserModel } from '@/database/models/user';import { UserMemoryModel } from '@/database/models/userMemory';+import { UserMemorySourceBenchmarkLoCoMoModel } from '@/database/models/userMemory/sources/benchmarkLoCoMo';import { getServerDB } from '@/database/server';import { getServerGlobalConfig } from '@/server/globalConfig';import {@@ -64,9 +65,13 @@ import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';import { S3 } from '@/server/modules/S3';import type { GlobalMemoryLayer } from '@/types/serverConfig';import type { UserKeyVaults } from '@/types/user/settings';-import { LayersEnum, type MergeStrategyEnum, TypesEnum, MemorySourceType } from '@/types/userMemory';+import {+ LayersEnum,+ MemorySourceType,+ type MergeStrategyEnum,+ TypesEnum,+} from '@/types/userMemory';import { encodeAsync } from '@/utils/tokenizer';-import debug from 'debug';const SOURCE_ALIAS_MAP: Record<string, MemorySourceType> = {benchmark_locomo: MemorySourceType.BenchmarkLocomo,@@ -913,7 +918,10 @@ export class MemoryExtractionExecutor {};}- async listUserMemoryIdentities(job: MemoryExtractionJob, userId: string): Promise<IdentityMemoryDetail[]> {+ async listUserMemoryIdentities(+ job: MemoryExtractionJob,+ userId: string,+ ): Promise<IdentityMemoryDetail[]> {const db = await this.db;const userMemoryModel = new UserMemoryModel(db, userId);diff --git a/src/services/agentCronJob.ts b/src/services/agentCronJob.tsnew file mode 100644index 00000000000..31277556b34--- /dev/null+++ b/src/services/agentCronJob.ts@@ -0,0 +1,95 @@+import type {+ CreateAgentCronJobData,+ UpdateAgentCronJobData,+} from '@/database/schemas/agentCronJob';+import { lambdaClient } from '@/libs/trpc/client/lambda';++/**+ * Client-side service for Agent Cron Job operations+ *+ * This service provides a clean interface for frontend components+ * to interact with agent cron job data using tRPC client.+ */+class AgentCronJobService {+ /**+ * Create a new cron job+ */+ async create(data: Omit<CreateAgentCronJobData, 'userId'>) {+ return await lambdaClient.agentCronJob.create.mutate(data);+ }++ /**+ * Get cron jobs for a specific agent+ */+ async getByAgentId(agentId: string) {+ return await lambdaClient.agentCronJob.findByAgent.query({ agentId });+ }++ /**+ * Get a single cron job by ID+ */+ async getById(id: string) {+ return await lambdaClient.agentCronJob.findById.query({ id });+ }++ /**+ * List cron jobs with pagination and filtering+ */+ async list(+ options: {+ agentId?: string;+ enabled?: boolean;+ limit?: number;+ offset?: number;+ } = {},+ ) {+ return await lambdaClient.agentCronJob.list.query(options);+ }++ /**+ * Update a cron job+ */+ async update(id: string, data: UpdateAgentCronJobData) {+ return await lambdaClient.agentCronJob.update.mutate({ data, id });+ }++ /**+ * Delete a cron job+ */+ async delete(id: string) {+ return await lambdaClient.agentCronJob.delete.mutate({ id });+ }++ /**+ * Reset execution counts+ */+ async resetExecutions(id: string, newMaxExecutions?: number) {+ return await lambdaClient.agentCronJob.resetExecutions.mutate({+ id,+ newMaxExecutions,+ });+ }++ /**+ * Get execution statistics+ */+ async getStats() {+ return await lambdaClient.agentCronJob.getStats.query();+ }++ /**+ * Get jobs near depletion+ */+ async getNearDepletion(threshold: number = 5) {+ return await lambdaClient.agentCronJob.getNearDepletion.query({ threshold });+ }++ /**+ * Batch update status (enable/disable) for multiple jobs+ */+ async batchUpdateStatus(ids: string[], enabled: boolean) {+ return await lambdaClient.agentCronJob.batchUpdateStatus.mutate({ enabled, ids });+ }+}++export const agentCronJobService = new AgentCronJobService();diff --git a/src/services/topic/index.ts b/src/services/topic/index.tsindex 7c1035c7561..2f9df654e8c 100644--- a/src/services/topic/index.ts+++ b/src/services/topic/index.ts@@ -37,6 +37,7 @@ export class TopicService {return lambdaClient.topic.getTopics.query({agentId: params.agentId,current: params.current,+ excludeTriggers: params.excludeTriggers,groupId: params.groupId,isInbox: params.isInbox,pageSize: params.pageSize,diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.tsindex f827180deea..960ecaa0451 100644--- a/src/store/chat/slices/topic/action.ts+++ b/src/store/chat/slices/topic/action.ts@@ -38,6 +38,11 @@ const n = setNamespace('t');const SWR_USE_FETCH_TOPIC = 'SWR_USE_FETCH_TOPIC';const SWR_USE_SEARCH_TOPIC = 'SWR_USE_SEARCH_TOPIC';+type CronTopicsGroupWithJobInfo = {+ cronJob: unknown;+ cronJobId: string;+ topics: ChatTopic[];+};/*** Options for switchTopic action@@ -91,6 +96,7 @@ export interface ChatTopicAction {enable: boolean,params: {agentId?: string;+ excludeTriggers?: string[];groupId?: string;isInbox?: boolean;pageSize?: number;@@ -282,7 +288,34 @@ export const chatTopic: StateCreator<});},favoriteTopic: async (id, favorite) => {+ const { activeAgentId } = get();await get().internal_updateTopic(id, { favorite });++ if (!activeAgentId) return;++ await mutate(+ ['cronTopicsWithJobInfo', activeAgentId],+ (groups?: CronTopicsGroupWithJobInfo[]) => {+ if (!groups) return groups;++ let updated = false;+ const next = groups.map((group) => {+ let groupUpdated = false;+ const topics = group.topics.map((topic) => {+ if (topic.id !== id) return topic;+ if (topic.favorite === favorite) return topic;+ groupUpdated = true;+ updated = true;+ return { ...topic, favorite };+ });++ return groupUpdated ? { ...group, topics } : group;+ });++ return updated ? next : groups;+ },+ { revalidate: false },+ );},updateTopicMetadata: async (id, metadata) => {@@ -314,15 +347,28 @@ export const chatTopic: StateCreator<},// query- useFetchTopics: (enable, { agentId, groupId, pageSize: customPageSize, isInbox }) => {+ useFetchTopics: (+ enable,+ { agentId, excludeTriggers, groupId, pageSize: customPageSize, isInbox },+ ) => {const pageSize = customPageSize || 20;+ const effectiveExcludeTriggers =+ excludeTriggers && excludeTriggers.length > 0 ? excludeTriggers : undefined;// Use topicMapKey to generate the container key for topic data mapconst containerKey = topicMapKey({ agentId, groupId });const hasValidContainer = !!(groupId || agentId);return useClientDataSWRWithSync<{ items: ChatTopic[]; total: number }>(enable && hasValidContainer- ? [SWR_USE_FETCH_TOPIC, containerKey, { isInbox, pageSize }]+ ? [+ SWR_USE_FETCH_TOPIC,+ containerKey,+ {+ isInbox,+ pageSize,+ ...(effectiveExcludeTriggers ? { excludeTriggers: effectiveExcludeTriggers } : {}),+ },+ ]: null,async () => {// agentId, groupId, isInbox, pageSize come from the outer scope closure@@ -343,6 +389,7 @@ export const chatTopic: StateCreator<const result = await topicService.getTopics({agentId,current: 0,+ excludeTriggers: effectiveExcludeTriggers,groupId,isInbox,pageSize,@@ -374,6 +421,7 @@ export const chatTopic: StateCreator<...get().topicDataMap,[containerKey]: {currentPage: 0,+ excludeTriggers: effectiveExcludeTriggers,hasMore,isExpandingPageSize: false,items: topics,@@ -413,9 +461,11 @@ export const chatTopic: StateCreator<try {const pageSize = useGlobalStore.getState().status.topicPageSize || 20;+ const excludeTriggers = currentData?.excludeTriggers;const result = await topicService.getTopics({agentId: activeAgentId,current: nextPage,+ excludeTriggers,groupId: activeGroupId,pageSize,});@@ -429,6 +479,7 @@ export const chatTopic: StateCreator<...get().topicDataMap,[key]: {currentPage: nextPage,+ excludeTriggers,hasMore,isLoadingMore: false,items: [...currentTopics, ...result.items],diff --git a/src/store/chat/slices/topic/initialState.ts b/src/store/chat/slices/topic/initialState.tsindex ce696b40883..b1c16d1c57c 100644--- a/src/store/chat/slices/topic/initialState.ts+++ b/src/store/chat/slices/topic/initialState.ts@@ -5,6 +5,7 @@ import { type ChatTopic } from '@/types/topic';*/export interface TopicData {currentPage: number;+ excludeTriggers?: string[];hasMore: boolean;isExpandingPageSize?: boolean;isLoadingMore?: boolean;diff --git a/src/store/chat/slices/topic/selectors.ts b/src/store/chat/slices/topic/selectors.tsindex d0dab94d0fb..586d201e62a 100644--- a/src/store/chat/slices/topic/selectors.ts+++ b/src/store/chat/slices/topic/selectors.ts@@ -18,27 +18,34 @@ const currentTopicData = (s: ChatStoreState): TopicData | undefined => {const currentTopics = (s: ChatStoreState): ChatTopic[] | undefined => currentTopicData(s)?.items;+// Get topics without cron-triggered ones+const currentTopicsWithoutCron = (s: ChatStoreState): ChatTopic[] | undefined => {+ const topics = currentTopics(s);+ if (!topics) return undefined;+ return topics.filter((topic) => topic.trigger !== 'cron');+};+const currentActiveTopic = (s: ChatStoreState): ChatTopic | undefined => {return currentTopics(s)?.find((topic) => topic.id === s.activeTopicId);};const searchTopics = (s: ChatStoreState): ChatTopic[] => s.searchTopics;-const displayTopics = (s: ChatStoreState): ChatTopic[] | undefined => currentTopics(s);+const displayTopics = (s: ChatStoreState): ChatTopic[] | undefined => currentTopicsWithoutCron(s);const currentFavTopics = (s: ChatStoreState): ChatTopic[] =>- currentTopics(s)?.filter((s) => s.favorite) || [];+ currentTopicsWithoutCron(s)?.filter((s) => s.favorite) || [];const currentUnFavTopics = (s: ChatStoreState): ChatTopic[] =>- currentTopics(s)?.filter((s) => !s.favorite) || [];+ currentTopicsWithoutCron(s)?.filter((s) => !s.favorite) || [];-const currentTopicLength = (s: ChatStoreState): number => currentTopicData(s)?.items?.length || 0;+const currentTopicLength = (s: ChatStoreState): number => currentTopicsWithoutCron(s)?.length || 0;const currentTopicCount = (s: ChatStoreState): number => currentTopicData(s)?.total || 0;const getTopicById =(id: string) =>(s: ChatStoreState): ChatTopic | undefined =>- currentTopics(s)?.find((topic) => topic.id === id);+ currentTopics(s)?.find((topic) => topic.id === id); // Don't filter here, need to access all topics by ID/*** Get topics by specific agentId (for AgentBuilder scenarios where agentId differs from activeAgentId)@@ -79,7 +86,7 @@ const isSearchingTopic = (s: ChatStoreState) => s.isSearchingTopic;const displayTopicsForSidebar =(pageSize: number) =>(s: ChatStoreState): ChatTopic[] | undefined => {- const topics = currentTopics(s);+ const topics = currentTopicsWithoutCron(s);if (!topics) return undefined;// Return only the first page worth of topics for sidebar@@ -143,6 +150,7 @@ export const topicSelectors = {currentTopicLength,currentTopicWorkingDirectory,currentTopics,+ currentTopicsWithoutCron,currentUnFavTopics,displayTopics,displayTopicsForSidebar,diff --git a/src/tools/placeholders.ts b/src/tools/placeholders.tsindex 13e4b130125..33520892b01 100644--- a/src/tools/placeholders.ts+++ b/src/tools/placeholders.ts@@ -4,10 +4,7 @@ import {LocalSystemListFilesPlaceholder,LocalSystemSearchFilesPlaceholder,} from '@lobechat/builtin-tool-local-system/client';-import {- NotebookIdentifier,- NotebookPlaceholders,-} from '@lobechat/builtin-tool-notebook/client';+import { NotebookIdentifier, NotebookPlaceholders } from '@lobechat/builtin-tool-notebook/client';import {WebBrowsingManifest,WebBrowsingPlaceholders,