🤯 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 automatic topic summary workflow (#17796)
Arvin Xu560d1993784e
diff --git a/apps/server/src/services/topicAutoSummary/index.test.ts b/apps/server/src/services/topicAutoSummary/index.test.tsnew file mode 100644index 00000000000..5389374c461--- /dev/null+++ b/apps/server/src/services/topicAutoSummary/index.test.ts@@ -0,0 +1,79 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { TopicAutoSummaryService } from './index';++const mocks = vi.hoisted(() => ({+ generateObject: vi.fn(),+ getUserSettings: vi.fn(),+ updateSummaryIfCurrent: vi.fn(),+}));++vi.mock('@/database/models/topicSummary', () => ({+ TopicSummaryModel: class {+ updateSummaryIfCurrent = mocks.updateSummaryIfCurrent;+ },+ topicSummaryEligibleMessage: undefined,+}));+vi.mock('@/database/models/user', () => ({+ UserModel: class {+ getUserSettings = mocks.getUserSettings;+ },+}));+vi.mock('@/server/services/aiGeneration', () => ({+ AiGenerationService: class {+ generateObject = mocks.generateObject;+ },+}));+vi.mock('@/server/services/systemAgent/modelConfig', () => ({+ resolveSystemAgentModelConfig: vi.fn().mockResolvedValue({+ model: 'deepseek-v4-flash',+ provider: 'deepseek',+ }),+}));++const createDb = () => {+ const results = [+ [{ historySummary: 'Earlier decision: use PostgreSQL.' }],+ [+ {+ content: 'What is next?',+ id: 'message-1',+ role: 'user',+ updatedAt: new Date('2026-07-31T10:00:00Z'),+ },+ ],+ ];++ return {+ select: vi.fn(() => ({+ from: vi.fn(() => ({+ where: vi.fn(() => ({+ limit: vi.fn(async () => results.shift()),+ orderBy: vi.fn(() => ({ limit: vi.fn(async () => results.shift()) })),+ })),+ })),+ })),+ } as never;+};++describe('TopicAutoSummaryService', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.getUserSettings.mockResolvedValue({});+ mocks.generateObject.mockResolvedValue({ description: 'Next steps', summary: 'Combined' });+ mocks.updateSummaryIfCurrent.mockResolvedValue(true);+ });++ it('rolls the previous summary into the next bounded summary', async () => {+ const service = new TopicAutoSummaryService(createDb(), 'user-1');++ const result = await service.summarize('topic-1');++ expect(result).toEqual({ summarized: true });+ const request = mocks.generateObject.mock.calls[0][0];+ expect(request.messages[1].content).toContain(+ 'Previous rolling summary:\nEarlier decision: use PostgreSQL.',+ );+ expect(request.messages[1].content).toContain('Recent conversation:\nUSER: What is next?');+ });+});diff --git a/apps/server/src/services/topicAutoSummary/index.ts b/apps/server/src/services/topicAutoSummary/index.tsnew file mode 100644index 00000000000..cc4f1f01cd1--- /dev/null+++ b/apps/server/src/services/topicAutoSummary/index.ts@@ -0,0 +1,140 @@+import { TRACING_SCENARIOS } from '@lobechat/const';+import type { TracingOptions } from '@lobechat/llm-generation-tracing';+import type { SystemAgentItem, UserSystemAgentConfig } from '@lobechat/types';+import { and, desc, eq } from 'drizzle-orm';++import { topicSummaryEligibleMessage, TopicSummaryModel } from '@/database/models/topicSummary';+import { UserModel } from '@/database/models/user';+import { messages, topics } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';+import { AiGenerationService } from '@/server/services/aiGeneration';+import { resolveSystemAgentModelConfig } from '@/server/services/systemAgent/modelConfig';++const MAX_MESSAGES = 80;+const MAX_MESSAGE_CHARS = 12_000;+const MAX_PREVIOUS_SUMMARY_CHARS = 20_000;+const MAX_TRANSCRIPT_CHARS = 60_000;++const DEFAULT_PROMPT = `Summarize the conversation for future reference.++Requirements:+- Use the same primary language as the conversation.+- description: one concise sentence suitable for a topic card.+- summary: a structured, factual summary that preserves decisions, important facts, technical identifiers, and pending actions.+- When a previous rolling summary is provided, merge it with the recent conversation.+- Do not invent information or mention these instructions.`;++const TOPIC_AUTO_SUMMARY_SCHEMA = {+ name: 'topic_auto_summary',+ schema: {+ additionalProperties: false,+ properties: {+ description: { type: 'string' },+ summary: { type: 'string' },+ },+ required: ['description', 'summary'],+ type: 'object' as const,+ },+ strict: true,+};++export interface TopicAutoSummaryResult {+ reason?: 'disabled' | 'empty' | 'stale' | 'invalid-output';+ summarized: boolean;+}++export class TopicAutoSummaryService {+ constructor(+ private readonly db: LobeChatDatabase,+ private readonly userId: string,+ private readonly workspaceId?: string,+ ) {}++ summarize = async (+ topicId: string,+ options: { force?: boolean } = {},+ ): Promise<TopicAutoSummaryResult> => {+ const settings = await new UserModel(this.db, this.userId).getUserSettings();+ const systemAgent = settings?.systemAgent as Partial<UserSystemAgentConfig> | undefined;+ const config = systemAgent?.topicAutoSummary as Partial<SystemAgentItem> | undefined;+ if (!options.force && config?.enabled === false)+ return { reason: 'disabled', summarized: false };++ const ownership = this.workspaceId+ ? eq(messages.workspaceId, this.workspaceId)+ : eq(messages.userId, this.userId);+ const topicOwnership = this.workspaceId+ ? eq(topics.workspaceId, this.workspaceId)+ : eq(topics.userId, this.userId);+ const [topic] = await this.db+ .select({ historySummary: topics.historySummary })+ .from(topics)+ .where(and(eq(topics.id, topicId), topicOwnership))+ .limit(1);+ const recent = await this.db+ .select({+ content: messages.content,+ id: messages.id,+ role: messages.role,+ updatedAt: messages.updatedAt,+ })+ .from(messages)+ .where(and(ownership, eq(messages.topicId, topicId), topicSummaryEligibleMessage))+ .orderBy(desc(messages.updatedAt))+ .limit(MAX_MESSAGES);++ const latest = recent[0];+ if (!latest) return { reason: 'empty', summarized: false };++ const transcript = recent+ .reverse()+ .map(+ ({ content, role }) =>+ `${role.toUpperCase()}: ${(content ?? '').slice(0, MAX_MESSAGE_CHARS)}`,+ )+ .join('\n\n')+ .slice(-MAX_TRANSCRIPT_CHARS);+ const { model, provider } = await resolveSystemAgentModelConfig({+ taskConfig: config,+ taskKey: 'topicAutoSummary',+ });+ const ai = new AiGenerationService(this.db, this.userId, this.workspaceId);+ const output = (await ai.generateObject(+ {+ messages: [+ { content: config?.customPrompt?.trim() || DEFAULT_PROMPT, role: 'system' },+ {+ content: topic?.historySummary+ ? `Previous rolling summary:\n${topic.historySummary.slice(-MAX_PREVIOUS_SUMMARY_CHARS)}\n\nRecent conversation:\n${transcript}`+ : transcript,+ role: 'user',+ },+ ],+ model,+ provider,+ schema: TOPIC_AUTO_SUMMARY_SCHEMA,+ },+ {+ tracing: {+ scenario: TRACING_SCENARIOS.TopicAutoSummary,+ schemaName: 'TopicAutoSummary',+ topicId,+ } satisfies TracingOptions,+ },+ )) as { description?: string; summary?: string };++ const description = output.description?.trim();+ const summary = output.summary?.trim();+ if (!description || !summary) return { reason: 'invalid-output', summarized: false };++ const updated = await new TopicSummaryModel(this.db).updateSummaryIfCurrent({+ description,+ lastMessageId: latest.id,+ lastMessageUpdatedAt: latest.updatedAt,+ summary,+ topicId,+ });++ return updated ? { summarized: true } : { reason: 'stale', summarized: false };+ };+}diff --git a/apps/server/src/workflows-hono/index.ts b/apps/server/src/workflows-hono/index.tsindex d854fba073e..8c6d5570347 100644--- a/apps/server/src/workflows-hono/index.ts+++ b/apps/server/src/workflows-hono/index.ts@@ -5,6 +5,7 @@ import memoryUserMemoryApp from './memory-user-memory';import onboardingTaskRecommendationApp from './onboarding-task-recommendation';import onboardingUnderstandingApp from './onboarding-understanding';import taskApp from './task';+import topicAutoSummaryApp from './topic-auto-summary';import verifyApp from './verify';const app = new Hono().basePath('/api/workflows');@@ -14,6 +15,7 @@ app.route('/memory-user-memory', memoryUserMemoryApp);app.route('/onboarding/understanding', onboardingUnderstandingApp);app.route('/onboarding/task-recommendations', onboardingTaskRecommendationApp);app.route('/task', taskApp);+app.route('/topic-auto-summary', topicAutoSummaryApp);app.route('/verify', verifyApp);export default app;diff --git a/apps/server/src/workflows-hono/topic-auto-summary/dispatch.test.ts b/apps/server/src/workflows-hono/topic-auto-summary/dispatch.test.tsnew file mode 100644index 00000000000..f005e0435e6--- /dev/null+++ b/apps/server/src/workflows-hono/topic-auto-summary/dispatch.test.ts@@ -0,0 +1,147 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { dispatchTopicAutoSummary } from './dispatch';++const mocks = vi.hoisted(() => ({+ listCandidates: vi.fn(),+ triggerDispatch: vi.fn(),+ triggerExecute: vi.fn(),+}));++vi.mock('@/database/server', () => ({ getServerDB: vi.fn().mockResolvedValue({}) }));+vi.mock('@/database/models/topicSummary', () => ({+ TopicSummaryModel: class {+ listCandidates = mocks.listCandidates;+ },+}));+vi.mock('@/server/workflows/topicAutoSummary', () => ({+ TopicAutoSummaryWorkflow: {+ triggerDispatch: mocks.triggerDispatch,+ triggerExecute: mocks.triggerExecute,+ },+}));++const createContext = (requestPayload: Record<string, unknown>) =>+ ({+ requestPayload,+ run: vi.fn(async (_step: string, callback: () => unknown) => callback()),+ }) as never;++describe('dispatchTopicAutoSummary', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.triggerDispatch.mockResolvedValue({ workflowRunId: 'next' });+ mocks.triggerExecute.mockResolvedValue({ workflowRunId: 'execute' });+ });++ it('uses the rolling 24-hour and one-hour idle defaults in dry-run mode', async () => {+ mocks.listCandidates.mockResolvedValue([]);+ const before = Date.now();++ const result = await dispatchTopicAutoSummary(createContext({ dryRun: true }));+ const after = Date.now();+ const options = mocks.listCandidates.mock.calls[0][0];++ expect(result).toMatchObject({ candidates: 0, dryRun: true, scheduled: 0 });+ expect(options.limit).toBe(100);+ expect(options.idleBefore.getTime()).toBeGreaterThanOrEqual(before - 60 * 60_000);+ expect(options.idleBefore.getTime()).toBeLessThanOrEqual(after - 60 * 60_000);+ expect(options.topicCreatedAfter.getTime()).toBeGreaterThanOrEqual(before - 24 * 3_600_000);+ expect(options.topicCreatedAfter.getTime()).toBeLessThanOrEqual(after - 24 * 3_600_000);+ expect(mocks.triggerExecute).not.toHaveBeenCalled();+ });++ it('counts every eligible dry-run page up to the operator limit', async () => {+ const createCandidates = (start: number, count: number) =>+ Array.from({ length: count }, (_, index) => ({+ id: `topic-${start + index}`,+ lastMessageUpdatedAt: new Date(+ `2026-07-31T10:${String(start + index).padStart(2, '0')}:00Z`,+ ),+ userId: 'user-1',+ workspaceId: null,+ }));+ mocks.listCandidates+ .mockResolvedValueOnce(createCandidates(0, 2))+ .mockResolvedValueOnce(createCandidates(2, 2))+ .mockResolvedValueOnce(createCandidates(4, 1));++ const result = await dispatchTopicAutoSummary(+ createContext({ dryRun: true, maxTopics: 10, pageSize: 2 }),+ );++ expect(result).toMatchObject({ candidates: 5, dryRun: true, truncated: false });+ expect(mocks.listCandidates).toHaveBeenCalledTimes(3);+ expect(mocks.listCandidates.mock.calls[1][0].cursor).toEqual({+ id: 'topic-1',+ lastMessageUpdatedAt: new Date('2026-07-31T10:01:00.000Z'),+ });+ expect(mocks.triggerDispatch).not.toHaveBeenCalled();+ expect(mocks.triggerExecute).not.toHaveBeenCalled();+ });++ it('reports when a dry run is truncated by maxTopics', async () => {+ const candidate = (id: string, minute: number) => ({+ id,+ lastMessageUpdatedAt: new Date(`2026-07-31T10:0${minute}:00Z`),+ userId: 'user-1',+ workspaceId: null,+ });+ mocks.listCandidates+ .mockResolvedValueOnce([candidate('topic-1', 0), candidate('topic-2', 1)])+ .mockResolvedValueOnce([candidate('topic-3', 2)]);++ const result = await dispatchTopicAutoSummary(+ createContext({ dryRun: true, maxTopics: 2, pageSize: 2 }),+ );++ expect(result).toMatchObject({ candidates: 2, dryRun: true, truncated: true });+ expect(mocks.listCandidates).toHaveBeenCalledTimes(2);+ });++ it('honors operator parameters and schedules a cursor continuation', async () => {+ const candidates = [+ {+ id: 'topic-1',+ lastMessageUpdatedAt: new Date('2026-07-31T10:00:00Z'),+ userId: 'user-1',+ workspaceId: null,+ },+ {+ id: 'topic-2',+ lastMessageUpdatedAt: new Date('2026-07-31T10:01:00Z'),+ userId: 'user-2',+ workspaceId: 'workspace-2',+ },+ ];+ mocks.listCandidates.mockResolvedValue(candidates);++ const result = await dispatchTopicAutoSummary(+ createContext({+ force: true,+ idleMinutes: 90,+ lookbackHours: 48,+ maxTopics: 10,+ pageSize: 2,+ }),+ );++ expect(result).toMatchObject({ hasNextPage: true, processed: 2, scheduled: 2 });+ expect(mocks.listCandidates).toHaveBeenCalledWith(+ expect.objectContaining({ force: true, limit: 2 }),+ );+ expect(mocks.triggerExecute).toHaveBeenCalledTimes(2);+ expect(mocks.triggerExecute).toHaveBeenLastCalledWith({+ force: true,+ topicId: 'topic-2',+ userId: 'user-2',+ workspaceId: 'workspace-2',+ });+ expect(mocks.triggerDispatch).toHaveBeenCalledWith(+ expect.objectContaining({+ cursor: { id: 'topic-2', lastMessageUpdatedAt: '2026-07-31T10:01:00.000Z' },+ processed: 2,+ }),+ );+ });+});diff --git a/apps/server/src/workflows-hono/topic-auto-summary/dispatch.ts b/apps/server/src/workflows-hono/topic-auto-summary/dispatch.tsnew file mode 100644index 00000000000..bbd06486855--- /dev/null+++ b/apps/server/src/workflows-hono/topic-auto-summary/dispatch.ts@@ -0,0 +1,126 @@+import type { WorkflowContext } from '@upstash/workflow';++import { TopicSummaryModel } from '@/database/models/topicSummary';+import { getServerDB } from '@/database/server';+import {+ type DispatchTopicAutoSummaryPayload,+ TopicAutoSummaryWorkflow,+} from '@/server/workflows/topicAutoSummary';++const DEFAULT_IDLE_MINUTES = 60;+const DEFAULT_LOOKBACK_HOURS = 24;+const DEFAULT_MAX_TOPICS = 500;+const DEFAULT_PAGE_SIZE = 100;+const MAX_IDLE_MINUTES = 7 * 24 * 60;+const MAX_LOOKBACK_HOURS = 7 * 24;+const HARD_MAX_TOPICS = 2000;+const HARD_MAX_PAGE_SIZE = 200;++const boundedInteger = (value: number | undefined, fallback: number, max: number) =>+ Math.min(Math.max(Math.floor(value ?? fallback), 1), max);++export const dispatchTopicAutoSummary = async (+ context: WorkflowContext<DispatchTopicAutoSummaryPayload>,+) => {+ const payload = context.requestPayload ?? {};+ const now = Date.now();+ const idleMinutes = boundedInteger(payload.idleMinutes, DEFAULT_IDLE_MINUTES, MAX_IDLE_MINUTES);+ const lookbackHours = boundedInteger(+ payload.lookbackHours,+ DEFAULT_LOOKBACK_HOURS,+ MAX_LOOKBACK_HOURS,+ );+ const maxTopics = boundedInteger(payload.maxTopics, DEFAULT_MAX_TOPICS, HARD_MAX_TOPICS);+ const pageSize = boundedInteger(payload.pageSize, DEFAULT_PAGE_SIZE, HARD_MAX_PAGE_SIZE);+ const processed = Math.max(payload.processed ?? 0, 0);+ const remaining = Math.max(maxTopics - processed, 0);+ if (remaining === 0) return { processed, scheduled: 0, truncated: true };++ const listCandidates = async (cursor: DispatchTopicAutoSummaryPayload['cursor'], limit: number) =>+ context.run(`topic-auto-summary:list:${cursor?.id ?? 'root'}`, async () => {+ const db = await getServerDB();+ return new TopicSummaryModel(db).listCandidates({+ cursor: cursor+ ? {+ id: cursor.id,+ lastMessageUpdatedAt: new Date(cursor.lastMessageUpdatedAt),+ }+ : undefined,+ force: payload.force,+ idleBefore: new Date(now - idleMinutes * 60_000),+ limit,+ topicCreatedAfter: new Date(now - lookbackHours * 3_600_000),+ });+ });++ if (payload.dryRun) {+ let candidates = 0;+ let cursor = payload.cursor;+ let hasNextPage = false;++ while (candidates < remaining) {+ const limit = Math.min(pageSize, remaining - candidates);+ const page = await listCandidates(cursor, limit);+ candidates += page.length;+ hasNextPage = page.length === limit;+ const last = page.at(-1);+ if (last && hasNextPage)+ cursor = {+ id: last.id,+ lastMessageUpdatedAt: last.lastMessageUpdatedAt.toISOString(),+ };+ if (!last || !hasNextPage || candidates === remaining) break;+ }++ const truncated =+ candidates === remaining && hasNextPage+ ? (await listCandidates(cursor, 1)).length > 0+ : false;++ return {+ candidates,+ dryRun: true,+ processed,+ scheduled: 0,+ truncated,+ };+ }++ const candidates = await listCandidates(payload.cursor, Math.min(pageSize, remaining));++ await Promise.all(+ candidates.map((candidate) =>+ context.run(`topic-auto-summary:schedule:${candidate.id}`, () =>+ TopicAutoSummaryWorkflow.triggerExecute({+ force: payload.force,+ topicId: candidate.id,+ userId: candidate.userId,+ workspaceId: candidate.workspaceId ?? undefined,+ }),+ ),+ ),+ );++ const nextProcessed = processed + candidates.length;+ const last = candidates.at(-1);+ const hasNextPage =+ candidates.length === Math.min(pageSize, remaining) && nextProcessed < maxTopics;+ if (last && hasNextPage) {+ await context.run(`topic-auto-summary:next:${last.id}`, () =>+ TopicAutoSummaryWorkflow.triggerDispatch({+ ...payload,+ cursor: {+ id: last.id,+ lastMessageUpdatedAt: last.lastMessageUpdatedAt.toISOString(),+ },+ processed: nextProcessed,+ }),+ );+ }++ return { hasNextPage, processed: nextProcessed, scheduled: candidates.length };+};++export const dispatchTopicAutoSummaryOptions = {+ flowControl: { key: 'topic-auto-summary.dispatch', parallelism: 1, ratePerSecond: 1 },+};diff --git a/apps/server/src/workflows-hono/topic-auto-summary/execute.ts b/apps/server/src/workflows-hono/topic-auto-summary/execute.tsnew file mode 100644index 00000000000..5c4e7872905--- /dev/null+++ b/apps/server/src/workflows-hono/topic-auto-summary/execute.ts@@ -0,0 +1,21 @@+import type { WorkflowContext } from '@upstash/workflow';++import { getServerDB } from '@/database/server';+import { TopicAutoSummaryService } from '@/server/services/topicAutoSummary';+import type { ExecuteTopicAutoSummaryPayload } from '@/server/workflows/topicAutoSummary';++export const executeTopicAutoSummary = async (+ context: WorkflowContext<ExecuteTopicAutoSummaryPayload>,+) => {+ const { force, topicId, userId, workspaceId } = context.requestPayload ?? {};+ if (!topicId || !userId) return { error: 'Missing topicId or userId', summarized: false };++ return context.run('topic-auto-summary:generate-and-save', async () => {+ const db = await getServerDB();+ return new TopicAutoSummaryService(db, userId, workspaceId).summarize(topicId, { force });+ });+};++export const executeTopicAutoSummaryOptions = {+ flowControl: { key: 'topic-auto-summary.execute', parallelism: 10, ratePerSecond: 5 },+};diff --git a/apps/server/src/workflows-hono/topic-auto-summary/index.ts b/apps/server/src/workflows-hono/topic-auto-summary/index.tsnew file mode 100644index 00000000000..0cb2ffb1399--- /dev/null+++ b/apps/server/src/workflows-hono/topic-auto-summary/index.ts@@ -0,0 +1,31 @@+import { withOtelMetricsForUpstashWorkflows } from '@lobechat/observability-otel/modules/upstash-workflow';+import { serve } from '@upstash/workflow/hono';+import { Hono } from 'hono';++import { createWorkflowQstashClient } from '../qstashClient';+import { dispatchTopicAutoSummary, dispatchTopicAutoSummaryOptions } from './dispatch';+import { executeTopicAutoSummary, executeTopicAutoSummaryOptions } from './execute';++const app = new Hono();++app.post(+ '/dispatch',+ serve(+ withOtelMetricsForUpstashWorkflows(dispatchTopicAutoSummary, {+ url: '/api/workflows/topic-auto-summary/dispatch',+ }),+ { ...dispatchTopicAutoSummaryOptions, qstashClient: createWorkflowQstashClient() },+ ),+);++app.post(+ '/execute',+ serve(+ withOtelMetricsForUpstashWorkflows(executeTopicAutoSummary, {+ url: '/api/workflows/topic-auto-summary/execute',+ }),+ { ...executeTopicAutoSummaryOptions, qstashClient: createWorkflowQstashClient() },+ ),+);++export default app;diff --git a/apps/server/src/workflows/topicAutoSummary/index.ts b/apps/server/src/workflows/topicAutoSummary/index.tsnew file mode 100644index 00000000000..11e705f7b06--- /dev/null+++ b/apps/server/src/workflows/topicAutoSummary/index.ts@@ -0,0 +1,54 @@+import type { FlowControl } from '@upstash/qstash';+import type { Client } from '@upstash/workflow';++import { appEnv } from '@/envs/app';+import { OtelWorkflowClient } from '@/libs/qstash';++import type { DispatchTopicAutoSummaryPayload, ExecuteTopicAutoSummaryPayload } from './types';++const DISPATCH_PATH = '/api/workflows/topic-auto-summary/dispatch';+const EXECUTE_PATH = '/api/workflows/topic-auto-summary/execute';++const getClient = (): Client => {+ const token = process.env.QSTASH_TOKEN;+ if (!token) throw new Error('QSTASH_TOKEN is required to trigger topic auto-summary workflows');+ const config: ConstructorParameters<typeof Client>[0] = { token };+ if (process.env.QSTASH_URL) (config as Record<string, unknown>).url = process.env.QSTASH_URL;+ return new OtelWorkflowClient(config);+};++const getUrl = (path: string) => {+ const baseUrl = appEnv.INTERNAL_APP_URL || appEnv.APP_URL;+ if (!baseUrl) throw new Error('APP_URL is required to trigger topic auto-summary workflows');+ return new URL(path, baseUrl).toString();+};++export class TopicAutoSummaryWorkflow {+ private static client: Client;++ private static getClient() {+ this.client ??= getClient();+ return this.client;+ }++ static triggerDispatch(payload: DispatchTopicAutoSummaryPayload) {+ return this.getClient().trigger({+ body: payload,+ flowControl: { key: 'topic-auto-summary.dispatch', parallelism: 1 } satisfies FlowControl,+ url: getUrl(DISPATCH_PATH),+ });+ }++ static triggerExecute(payload: ExecuteTopicAutoSummaryPayload) {+ return this.getClient().trigger({+ body: payload,+ flowControl: {+ key: `topic-auto-summary.execute.user.${payload.userId}`,+ parallelism: 2,+ } satisfies FlowControl,+ url: getUrl(EXECUTE_PATH),+ });+ }+}++export type { DispatchTopicAutoSummaryPayload, ExecuteTopicAutoSummaryPayload } from './types';diff --git a/apps/server/src/workflows/topicAutoSummary/types.ts b/apps/server/src/workflows/topicAutoSummary/types.tsnew file mode 100644index 00000000000..debab1b3778--- /dev/null+++ b/apps/server/src/workflows/topicAutoSummary/types.ts@@ -0,0 +1,23 @@+export interface TopicAutoSummaryCursor {+ id: string;+ lastMessageUpdatedAt: string;+}++/** Explicit operator controls. Omitted values use conservative production defaults. */+export interface DispatchTopicAutoSummaryPayload {+ cursor?: TopicAutoSummaryCursor;+ dryRun?: boolean;+ force?: boolean;+ idleMinutes?: number;+ lookbackHours?: number;+ maxTopics?: number;+ pageSize?: number;+ processed?: number;+}++export interface ExecuteTopicAutoSummaryPayload {+ force?: boolean;+ topicId: string;+ userId: string;+ workspaceId?: string;+}diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex 14f099e335f..aa595e6a754 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -652,6 +652,7 @@"serviceModel.memoryModels.title": "Memory","serviceModel.modelAssignments.title": "General","serviceModel.optionalFeatures.title": "Optional Features",+ "serviceModel.topicAutoSummary.desc": "Summarizes topics created in the rolling 24-hour window after one hour without message activity.","settingAgent.agentTools.add": "Add Tool","settingAgent.agentTools.agentEmpty": "No agent-exclusive tools yet","settingAgent.agentTools.authorizedBy": "Authorized by {{name}}",@@ -1194,6 +1195,9 @@"systemAgent.topic.label": "Model","systemAgent.topic.modelDesc": "Model used to rename topics","systemAgent.topic.title": "Topic Auto-Naming",+ "systemAgent.topicAutoSummary.modelDesc": "Writes a short description and a reusable conversation summary after a topic becomes inactive.",+ "systemAgent.topicAutoSummary.promptPlaceholder": "Optional custom instructions. The conversation and required JSON output schema are added automatically.",+ "systemAgent.topicAutoSummary.title": "Automatic Topic Summary","systemAgent.translation.label": "Model","systemAgent.translation.modelDesc": "Model used to translate messages","systemAgent.translation.title": "Message Translation",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex b417bcf947d..c4f4868c9d9 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -652,6 +652,7 @@"serviceModel.memoryModels.title": "记忆","serviceModel.modelAssignments.title": "通用","serviceModel.optionalFeatures.title": "可选功能",+ "serviceModel.topicAutoSummary.desc": "针对滚动 24 小时内创建、消息已停止更新一小时的话题自动生成摘要。","settingAgent.agentTools.add": "添加工具","settingAgent.agentTools.agentEmpty": "还没有 Agent 专属工具","settingAgent.agentTools.authorizedBy": "由 {{name}} 授权",@@ -1194,6 +1195,9 @@"systemAgent.topic.label": "模型","systemAgent.topic.modelDesc": "用于自动命名话题的模型","systemAgent.topic.title": "话题自动命名",+ "systemAgent.topicAutoSummary.modelDesc": "话题停止更新后,自动写入简短描述和可复用的会话摘要。",+ "systemAgent.topicAutoSummary.promptPlaceholder": "可选的自定义指令。系统会自动附加会话内容和必要的 JSON 输出格式。",+ "systemAgent.topicAutoSummary.title": "话题自动总结","systemAgent.translation.label": "模型","systemAgent.translation.modelDesc": "用于翻译消息内容的模型","systemAgent.translation.title": "消息内容翻译",diff --git a/packages/const/src/llmGenerationTracing.ts b/packages/const/src/llmGenerationTracing.tsindex 5b6ba427032..b21726841d7 100644--- a/packages/const/src/llmGenerationTracing.ts+++ b/packages/const/src/llmGenerationTracing.ts@@ -24,6 +24,7 @@ export const TRACING_SCENARIOS = {TaskBriefJudge: 'task_brief_judge',TaskHandoff: 'task_handoff',TopicTitle: 'topic_title',+ TopicAutoSummary: 'topic_auto_summary',Unknown: 'unknown',VerifyJudge: 'verify_judge',VerifyPlanGen: 'verify_plan_gen',diff --git a/packages/const/src/settings/systemAgent.ts b/packages/const/src/settings/systemAgent.tsindex ff55302bae8..cc37acf09e3 100644--- a/packages/const/src/settings/systemAgent.ts+++ b/packages/const/src/settings/systemAgent.ts@@ -39,6 +39,12 @@ export const DEFAULT_FOLLOW_UP_ACTION_SYSTEM_AGENT_ITEM: SystemAgentItem = {provider: DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,};+export const DEFAULT_TOPIC_AUTO_SUMMARY_SYSTEM_AGENT_ITEM: SystemAgentItem = {+ enabled: true,+ model: 'deepseek-v4-flash',+ provider: 'deepseek',+};+export const DEFAULT_USER_MEMORY_EMBEDDING_SYSTEM_AGENT_ITEM: SystemAgentItem = {model: DEFAULT_EMBEDDING_MODEL,provider: DEFAULT_EMBEDDING_PROVIDER,@@ -58,5 +64,6 @@ export const DEFAULT_SYSTEM_AGENT_CONFIG: UserServiceModelConfig = {promptRewrite: DEFAULT_PROMPT_REWRITE_SYSTEM_AGENT_ITEM,thread: DEFAULT_SYSTEM_AGENT_ITEM,topic: DEFAULT_MINI_SYSTEM_AGENT_ITEM,+ topicAutoSummary: DEFAULT_TOPIC_AUTO_SUMMARY_SYSTEM_AGENT_ITEM,translation: DEFAULT_MINI_SYSTEM_AGENT_ITEM,};diff --git a/packages/database/src/models/__tests__/topicSummary.test.ts b/packages/database/src/models/__tests__/topicSummary.test.tsnew file mode 100644index 00000000000..b0bfe20b207--- /dev/null+++ b/packages/database/src/models/__tests__/topicSummary.test.ts@@ -0,0 +1,221 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import { messages, topics, users, userSettings } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { TopicSummaryModel } from '../topicSummary';++const db: LobeChatDatabase = await getTestDB();+const model = new TopicSummaryModel(db);+const userId = 'topic-summary-user';+const otherUserId = 'topic-summary-other';+const now = new Date('2026-07-31T12:00:00.000Z');++describe('TopicSummaryModel', () => {+ beforeEach(async () => {+ await db.delete(users);+ await db.insert(users).values([{ id: userId }, { id: otherUserId }]);+ });++ afterEach(async () => {+ await db.delete(users);+ });++ it('lists only enabled, stale candidates inside the rolling lookback window', async () => {+ await db.insert(userSettings).values({+ id: otherUserId,+ systemAgent: { topicAutoSummary: { enabled: false } },+ });+ await db.insert(topics).values([+ { createdAt: new Date('2026-07-31T00:00:00Z'), id: 'eligible', userId },+ { createdAt: new Date('2026-07-29T00:00:00Z'), id: 'too-old', userId },+ { createdAt: new Date('2026-07-31T00:00:00Z'), id: 'disabled', userId: otherUserId },+ { createdAt: new Date('2026-07-31T00:00:00Z'), id: 'active', status: 'running', userId },+ ]);+ await db.insert(messages).values([+ {+ content: 'a',+ id: 'm-eligible',+ role: 'user',+ topicId: 'eligible',+ updatedAt: new Date('2026-07-31T10:00:00Z'),+ userId,+ },+ {+ content: 'b',+ id: 'm-old',+ role: 'user',+ topicId: 'too-old',+ updatedAt: new Date('2026-07-29T10:00:00Z'),+ userId,+ },+ {+ content: 'c',+ id: 'm-disabled',+ role: 'user',+ topicId: 'disabled',+ updatedAt: new Date('2026-07-31T10:00:00Z'),+ userId: otherUserId,+ },+ {+ content: 'd',+ id: 'm-active',+ role: 'user',+ topicId: 'active',+ updatedAt: new Date('2026-07-31T10:00:00Z'),+ userId,+ },+ ]);++ const result = await model.listCandidates({+ idleBefore: new Date('2026-07-31T11:00:00Z'),+ limit: 20,+ topicCreatedAfter: new Date('2026-07-30T12:00:00Z'),+ });++ expect(result.map(({ id }) => id)).toEqual(['eligible']);+ });++ it('skips a topic whose watermark matches its latest message', async () => {+ const lastMessageUpdatedAt = new Date('2026-07-31T10:00:00Z');+ await db.insert(topics).values({+ createdAt: new Date('2026-07-31T00:00:00Z'),+ id: 'summarized',+ metadata: {+ autoSummary: {+ lastMessageId: 'm-summary',+ lastMessageUpdatedAt: lastMessageUpdatedAt.toISOString(),+ summarizedAt: now.toISOString(),+ version: 1,+ },+ },+ userId,+ });+ await db.insert(messages).values({+ content: 'done',+ id: 'm-summary',+ role: 'assistant',+ topicId: 'summarized',+ updatedAt: lastMessageUpdatedAt,+ userId,+ });++ const result = await model.listCandidates({+ idleBefore: new Date('2026-07-31T11:00:00Z'),+ limit: 20,+ topicCreatedAfter: new Date('2026-07-30T12:00:00Z'),+ });++ expect(result).toEqual([]);+ });++ it('excludes system-generated topics from candidates', async () => {+ await db.insert(topics).values([+ { createdAt: new Date('2026-07-31T00:00:00Z'), id: 'regular', userId },+ {+ createdAt: new Date('2026-07-31T00:00:00Z'),+ id: 'evaluation',+ trigger: 'eval',+ userId,+ },+ ]);+ await db.insert(messages).values([+ {+ content: 'regular message',+ id: 'm-regular',+ role: 'user',+ topicId: 'regular',+ updatedAt: new Date('2026-07-31T10:00:00Z'),+ userId,+ },+ {+ content: 'evaluation message',+ id: 'm-evaluation',+ role: 'user',+ topicId: 'evaluation',+ updatedAt: new Date('2026-07-31T10:00:00Z'),+ userId,+ },+ ]);++ const result = await model.listCandidates({+ idleBefore: new Date('2026-07-31T11:00:00Z'),+ limit: 20,+ topicCreatedAfter: new Date('2026-07-30T12:00:00Z'),+ });++ expect(result.map(({ id }) => id)).toEqual(['regular']);+ });++ it('does not overwrite the summary when a newer message arrives', async () => {+ await db.insert(topics).values({ id: 'racing', userId });+ await db.insert(messages).values([+ {+ content: 'old',+ id: 'm-old',+ role: 'user',+ topicId: 'racing',+ updatedAt: new Date('2026-07-31T10:00:00Z'),+ userId,+ },+ {+ content: 'new',+ id: 'm-new',+ role: 'assistant',+ topicId: 'racing',+ updatedAt: new Date('2026-07-31T10:01:00Z'),+ userId,+ },+ ]);++ const updated = await model.updateSummaryIfCurrent({+ description: 'Old description',+ lastMessageId: 'm-old',+ lastMessageUpdatedAt: new Date('2026-07-31T10:00:00Z'),+ summary: 'Old summary',+ topicId: 'racing',+ });+ const [topic] = await db.select().from(topics).where(eq(topics.id, 'racing'));++ expect(updated).toBe(false);+ expect(topic.description).toBeNull();+ expect(topic.historySummary).toBeNull();+ });++ it('ignores newer ineligible messages when checking the write fence', async () => {+ await db.insert(topics).values({ id: 'tool-followup', userId });+ await db.insert(messages).values([+ {+ content: 'answer',+ id: 'm-answer',+ role: 'assistant',+ topicId: 'tool-followup',+ updatedAt: new Date('2026-07-31T10:00:00Z'),+ userId,+ },+ {+ content: 'tool result',+ id: 'm-tool',+ role: 'tool',+ topicId: 'tool-followup',+ updatedAt: new Date('2026-07-31T10:01:00Z'),+ userId,+ },+ ]);++ const updated = await model.updateSummaryIfCurrent({+ description: 'Description',+ lastMessageId: 'm-answer',+ lastMessageUpdatedAt: new Date('2026-07-31T10:00:00Z'),+ summary: 'Summary',+ topicId: 'tool-followup',+ });+ const [topic] = await db.select().from(topics).where(eq(topics.id, 'tool-followup'));++ expect(updated).toBe(true);+ expect(topic.description).toBe('Description');+ expect(topic.historySummary).toBe('Summary');+ });+});diff --git a/packages/database/src/models/topicSummary.ts b/packages/database/src/models/topicSummary.tsnew file mode 100644index 00000000000..5e2eb5dc140--- /dev/null+++ b/packages/database/src/models/topicSummary.ts@@ -0,0 +1,166 @@+import type { ChatTopicMetadata } from '@lobechat/types';+import {+ and,+ asc,+ eq,+ exists,+ gt,+ gte,+ inArray,+ isNotNull,+ isNull,+ lte,+ max,+ ne,+ not,+ notExists,+ notInArray,+ or,+ sql,+} from 'drizzle-orm';++import { messages, topics, userSettings } from '../schemas';+import type { LobeChatDatabase } from '../type';++export interface TopicSummaryCandidateCursor {+ id: string;+ lastMessageUpdatedAt: Date;+}++export interface ListTopicSummaryCandidatesOptions {+ cursor?: TopicSummaryCandidateCursor;+ force?: boolean;+ idleBefore: Date;+ limit: number;+ topicCreatedAfter: Date;+}++export interface TopicSummaryCandidate {+ id: string;+ lastMessageUpdatedAt: Date;+ userId: string;+ workspaceId: string | null;+}++const isTopicAutoSummaryEnabled = sql<boolean>`COALESCE((${userSettings.systemAgent}->'topicAutoSummary'->>'enabled')::boolean, true) = true`;+const SYSTEM_TOPIC_TRIGGERS = ['cron', 'eval', 'task_manager', 'task', 'document'];++export const topicSummaryEligibleMessage = and(+ isNotNull(messages.content),+ ne(messages.content, ''),+ inArray(messages.role, ['assistant', 'user']),+);++const getAutoSummaryWatermark = () =>+ sql<Date>`COALESCE(NULLIF(COALESCE(${topics.metadata}->'autoSummary'->>'lastMessageUpdatedAt', ''), '')::timestamptz, 'epoch'::timestamptz)`.mapWith(+ topics.updatedAt,+ );++const mergeAutoSummaryMetadata = (marker: NonNullable<ChatTopicMetadata['autoSummary']>) =>+ sql`COALESCE(${topics.metadata}, '{}'::jsonb) || ${JSON.stringify({ autoSummary: marker })}::jsonb`;++/** System-scoped queries used only by the authenticated background summary workflow. */+export class TopicSummaryModel {+ constructor(private readonly db: LobeChatDatabase) {}++ listCandidates = async ({+ cursor,+ force = false,+ idleBefore,+ limit,+ topicCreatedAfter,+ }: ListTopicSummaryCandidatesOptions): Promise<TopicSummaryCandidate[]> => {+ const lastMessageUpdatedAt = max(messages.updatedAt).mapWith(messages.updatedAt);+ const cursorCondition = cursor+ ? or(+ gt(lastMessageUpdatedAt, cursor.lastMessageUpdatedAt),+ and(eq(lastMessageUpdatedAt, cursor.lastMessageUpdatedAt), gt(topics.id, cursor.id)),+ )+ : undefined;++ return this.db+ .select({+ id: topics.id,+ lastMessageUpdatedAt,+ userId: topics.userId,+ workspaceId: topics.workspaceId,+ })+ .from(topics)+ .innerJoin(messages, eq(messages.topicId, topics.id))+ .leftJoin(userSettings, eq(userSettings.id, topics.userId))+ .where(+ and(+ gte(topics.createdAt, topicCreatedAfter),+ topicSummaryEligibleMessage,+ or(isNull(topics.trigger), not(inArray(topics.trigger, SYSTEM_TOPIC_TRIGGERS))),+ or(isNull(topics.status), notInArray(topics.status, ['running', 'scheduled'])),+ force ? undefined : isTopicAutoSummaryEnabled,+ ),+ )+ .groupBy(topics.id, topics.userId, topics.workspaceId, topics.metadata)+ .having(+ and(+ lte(lastMessageUpdatedAt, idleBefore),+ force ? undefined : ne(getAutoSummaryWatermark(), lastMessageUpdatedAt),+ cursorCondition,+ ),+ )+ .orderBy(asc(lastMessageUpdatedAt), asc(topics.id))+ .limit(limit);+ };++ updateSummaryIfCurrent = async (input: {+ description: string;+ lastMessageId: string;+ lastMessageUpdatedAt: Date;+ summary: string;+ topicId: string;+ }): Promise<boolean> => {+ const marker: NonNullable<ChatTopicMetadata['autoSummary']> = {+ lastMessageId: input.lastMessageId,+ lastMessageUpdatedAt: input.lastMessageUpdatedAt.toISOString(),+ summarizedAt: new Date().toISOString(),+ version: 1,+ };+ const snapshotMessage = this.db+ .select({ id: messages.id })+ .from(messages)+ .where(+ and(+ eq(messages.topicId, input.topicId),+ topicSummaryEligibleMessage,+ eq(messages.id, input.lastMessageId),+ eq(messages.updatedAt, input.lastMessageUpdatedAt),+ ),+ );+ const newerMessage = this.db+ .select({ id: messages.id })+ .from(messages)+ .where(+ and(+ eq(messages.topicId, input.topicId),+ topicSummaryEligibleMessage,+ or(+ gt(messages.updatedAt, input.lastMessageUpdatedAt),+ and(+ eq(messages.updatedAt, input.lastMessageUpdatedAt),+ gt(messages.id, input.lastMessageId),+ ),+ ),+ ),+ );++ const rows = await this.db+ .update(topics)+ .set({+ description: input.description,+ historySummary: input.summary,+ metadata: mergeAutoSummaryMetadata(marker),+ updatedAt: new Date(),+ })+ .where(and(eq(topics.id, input.topicId), exists(snapshotMessage), notExists(newerMessage)))+ .returning({ id: topics.id });++ return rows.length > 0;+ };+}diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex 5a8fa5faf37..14f98c018e2 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -1118,6 +1118,8 @@ export default {'serviceModel.contextLimit.placeholder': 'Context limit','serviceModel.memoryModels.title': 'Memory','serviceModel.optionalFeatures.title': 'Optional Features',+ 'serviceModel.topicAutoSummary.desc':+ 'Summarizes topics created in the rolling 24-hour window after one hour without message activity.','settingSystemTools.appEnvironment.chromium.desc': 'Chromium browser engine version','settingSystemTools.appEnvironment.desc': 'Built-in runtime versions in the desktop app','settingSystemTools.appEnvironment.electron.desc': 'Electron framework version',@@ -1393,6 +1395,11 @@ When I am ___, I need ___'systemAgent.topic.label': 'Model','systemAgent.topic.modelDesc': 'Model used to rename topics','systemAgent.topic.title': 'Topic Auto-Naming',+ 'systemAgent.topicAutoSummary.modelDesc':+ 'Writes a short description and a reusable conversation summary after a topic becomes inactive.',+ 'systemAgent.topicAutoSummary.promptPlaceholder':+ 'Optional custom instructions. The conversation and required JSON output schema are added automatically.',+ 'systemAgent.topicAutoSummary.title': 'Automatic Topic Summary','systemAgent.translation.label': 'Model','systemAgent.translation.modelDesc': 'Model used to translate messages','systemAgent.translation.title': 'Message Translation',diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.tsindex 863498fb002..644d33286b3 100644--- a/packages/types/src/topic/topic.ts+++ b/packages/types/src/topic/topic.ts@@ -111,6 +111,13 @@ export interface OnboardingSessionSnapshot {}export interface ChatTopicMetadata {+ /** Watermark written by the background topic-summary workflow. */+ autoSummary?: {+ lastMessageId: string;+ lastMessageUpdatedAt: string;+ summarizedAt: string;+ version: number;+ };bot?: ChatTopicBotContext;boundDeviceId?: string;cronJobId?: string;diff --git a/packages/types/src/user/settings/systemAgent.ts b/packages/types/src/user/settings/systemAgent.tsindex 285645b1673..09f50c15505 100644--- a/packages/types/src/user/settings/systemAgent.ts+++ b/packages/types/src/user/settings/systemAgent.ts@@ -23,6 +23,8 @@ export interface UserSystemAgentConfig {promptRewrite: PromptRewriteSystemAgent;thread: SystemAgentItem;topic: SystemAgentItem;+ /** Background workflow that summarizes inactive topics into description/historySummary. */+ topicAutoSummary: SystemAgentItem;translation: SystemAgentItem;}diff --git a/src/features/ServiceModel/ModelAssignmentsForm.tsx b/src/features/ServiceModel/ModelAssignmentsForm.tsxindex 050f299c934..2c5ea521165 100644--- a/src/features/ServiceModel/ModelAssignmentsForm.tsx+++ b/src/features/ServiceModel/ModelAssignmentsForm.tsx@@ -1,7 +1,7 @@'use client';import type { FormGroupItemType, FormItemProps } from '@lobehub/ui';-import { Flexbox, Form, InputNumber, Skeleton, Tooltip } from '@lobehub/ui';+import { Flexbox, Form, InputNumber, Skeleton, TextArea, Tooltip } from '@lobehub/ui';import { Switch } from '@lobehub/ui/base-ui';import isEqual from 'fast-deep-equal';import { memo, useEffect, useState } from 'react';@@ -44,6 +44,7 @@ const SYSTEM_AGENT_MODEL_ITEMS: SystemAgentModelItem[] = [];const OPTIONAL_FEATURE_ITEMS: SystemAgentModelItem[] = [+ { key: 'topicAutoSummary' },{ key: 'followUpAction' },{ key: 'inputCompletion' },{ key: 'promptRewrite' },@@ -239,34 +240,41 @@ const ModelAssignmentsForm = memo(() => {return {children: (<Tooltip title={reason}>- <Flexbox- align="center"- direction="horizontal"- gap={12}- justify="flex-end"- style={{ width: 'min(100%, 448px)' }}- >- {/* Which model runs a feature is only worth asking once the feature+ <Flexbox gap={12} style={{ width: 'min(100%, 448px)' }}>+ <Flexbox align="center" direction="horizontal" gap={12} justify="flex-end">+ {/* Which model runs a feature is only worth asking once the featureitself is on — off, the picker is a dead control, so the switchstands alone until it's flipped back. */}- {!featureDisabled && (- <ModelSelect+ {!featureDisabled && (+ <ModelSelect+ disabled={!canManageServiceModel}+ showAbility={false}+ style={{ minWidth: 0, width: '100%' }}+ value={value}+ onChange={(props) => updateSystemAgentModel(key, props)}+ />+ )}+ <Flexbox align="center" direction="horizontal" gap={8}>+ <Switch+ aria-label={t(`systemAgent.${key}.title`)}+ checked={value.enabled}+ disabled={!canManageServiceModel}+ loading={loadingKey === key}+ onChange={(enabled) => updateSystemAgentModel(key, { enabled })}+ />+ </Flexbox>+ </Flexbox>+ {key === 'topicAutoSummary' && !featureDisabled && (+ <TextArea+ autoSize={{ maxRows: 8, minRows: 3 }}+ defaultValue={value.customPrompt}disabled={!canManageServiceModel}- showAbility={false}- style={{ minWidth: 0, width: '100%' }}- value={value}- onChange={(props) => updateSystemAgentModel(key, props)}+ placeholder={t('systemAgent.topicAutoSummary.promptPlaceholder')}+ onBlur={(event) =>+ updateSystemAgentModel(key, { customPrompt: event.currentTarget.value.trim() })+ }/>)}- <Flexbox align="center" direction="horizontal" gap={8}>- <Switch- aria-label={t(`systemAgent.${key}.title`)}- checked={value.enabled}- disabled={!canManageServiceModel}- loading={loadingKey === key}- onChange={(enabled) => updateSystemAgentModel(key, { enabled })}- />- </Flexbox></Flexbox></Tooltip>),diff --git a/src/store/user/slices/settings/selectors/__snapshots__/settings.test.ts.snap b/src/store/user/slices/settings/selectors/__snapshots__/settings.test.ts.snapindex c6b37882ad8..e28138092c8 100644--- a/src/store/user/slices/settings/selectors/__snapshots__/settings.test.ts.snap+++ b/src/store/user/slices/settings/selectors/__snapshots__/settings.test.ts.snap@@ -99,6 +99,11 @@ exports[`settingsSelectors > currentSystemAgent > should merge DEFAULT_SYSTEM_AG"model": "gpt-5.6-luna","provider": "openai",},+ "topicAutoSummary": {+ "enabled": true,+ "model": "deepseek-v4-flash",+ "provider": "deepseek",+ },"translation": {"model": "gpt-5.6-luna","provider": "openai",diff --git a/src/store/user/slices/settings/selectors/systemAgent.ts b/src/store/user/slices/settings/selectors/systemAgent.tsindex a71ced0665b..914713d1bcf 100644--- a/src/store/user/slices/settings/selectors/systemAgent.ts+++ b/src/store/user/slices/settings/selectors/systemAgent.ts@@ -9,6 +9,7 @@ const currentSystemAgent = (s: UserStore) =>const translation = (s: UserStore) => currentSystemAgent(s).translation;const topic = (s: UserStore) => currentSystemAgent(s).topic;+const topicAutoSummary = (s: UserStore) => currentSystemAgent(s).topicAutoSummary;const thread = (s: UserStore) => currentSystemAgent(s).thread;const agentMeta = (s: UserStore) => currentSystemAgent(s).agentMeta;const promptRewrite = (s: UserStore) => currentSystemAgent(s).promptRewrite;@@ -26,5 +27,6 @@ export const systemAgentSelectors = {promptRewrite,thread,topic,+ topicAutoSummary,translation,};