🤯 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: support export and import topic JSON (#10885)
Arvin Xu0c5a41f89604
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 9b0001d9689..ee7caa0d0f4 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -359,6 +359,11 @@"downloadFile": "Download File","downloadPdf": "Download PDF","downloadSuccess": "Download successful",+ "exportMode": {+ "full": "Default",+ "label": "Export Mode",+ "simple": "OpenAI Compatible"+ },"exportPdf": "Export as PDF","exportTitle": "Default Title","generatePdf": "Generate PDF",@@ -470,7 +475,7 @@"toolAuth": {"authorize": "Authorize","authorizing": "Authorizing...",- "hint": "Without authorization, these tools may not work properly, which could cause the assistant to have limited functionality or errors.",+ "hint": "Please complete the tool authorization for the assistant","signIn": "Sign In","title": "This assistant uses tools that require authorization"},diff --git a/locales/en-US/topic.json b/locales/en-US/topic.jsonindex 0caba87bed9..dfe6311a966 100644--- a/locales/en-US/topic.json+++ b/locales/en-US/topic.json@@ -7,6 +7,7 @@"confirmRemoveUnstarred": "You are about to delete unstarred topics. This action cannot be undone, please proceed with caution.","duplicate": "Create Copy","export": "Export Topics",+ "import": "Import Conversation","openInNewWindow": "Open in a new window","removeAll": "Delete All Topics","removeUnstarred": "Delete Unstarred Topics"@@ -34,6 +35,10 @@"desc": "Click the button on the left to save the current conversation as a historical topic and start a new conversation.","title": "Topic List"},+ "importError": "Import Failed",+ "importInvalidFormat": "Invalid file format. Please ensure it is a valid JSON file.",+ "importLoading": "Importing conversation...",+ "importSuccess": "Successfully imported {{count}} messages","loadMore": "Load More","searchPlaceholder": "Search Topics...","searchResultEmpty": "No search results found.",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex c230b967de7..6ceee9a9c1c 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -359,6 +359,11 @@"downloadFile": "下载文件","downloadPdf": "下载 PDF","downloadSuccess": "下载成功",+ "exportMode": {+ "full": "默认",+ "label": "导出模式",+ "simple": "OpenAI 兼容"+ },"exportPdf": "导出为 PDF","exportTitle": "默认标题","generatePdf": "生成 PDF",@@ -470,7 +475,7 @@"toolAuth": {"authorize": "授权","authorizing": "授权中...",- "hint": "如不授权或配置,这些工具将无法正常使用,可能导致助手功能缺失或报错。",+ "hint": "请为助手完成工具的授权","signIn": "登录","title": "该助手使用了以下需要授权的工具"},diff --git a/locales/zh-CN/topic.json b/locales/zh-CN/topic.jsonindex aa7b5a0d470..40fa11fca08 100644--- a/locales/zh-CN/topic.json+++ b/locales/zh-CN/topic.json@@ -7,6 +7,7 @@"confirmRemoveUnstarred": "即将删除未收藏话题,删除后将不可恢复,请谨慎操作。","duplicate": "创建副本","export": "导出话题",+ "import": "导入对话","openInNewWindow": "打开独立窗口","removeAll": "删除全部话题","removeUnstarred": "删除未收藏话题"@@ -34,6 +35,10 @@"desc": "点击发送左侧按钮可将当前会话保存为历史话题,并开启新一轮会话","title": "话题列表"},+ "importError": "导入失败",+ "importInvalidFormat": "文件格式无效,请确保是有效的 JSON 文件",+ "importLoading": "正在导入对话...",+ "importSuccess": "成功导入 {{count}} 条消息","loadMore": "更多","searchPlaceholder": "搜索话题...","searchResultEmpty": "暂无搜索结果",diff --git a/packages/database/src/repositories/topicImporter/__tests__/fixtures/exported-topic.json b/packages/database/src/repositories/topicImporter/__tests__/fixtures/exported-topic.jsonnew file mode 100644index 00000000000..6d6b1af5f20--- /dev/null+++ b/packages/database/src/repositories/topicImporter/__tests__/fixtures/exported-topic.json@@ -0,0 +1,147 @@+{+ "exportedAt": "2025-12-22T08:50:13.752Z",+ "messages": [+ {+ "content": "你好",+ "createdAt": "2025-12-22T05:28:22.890Z",+ "id": "msg_1",+ "role": "user",+ "updatedAt": "2025-12-22T05:28:39.982Z",+ "metadata": { "activeBranchIndex": 1 }+ },+ {+ "content": "你好!(回复A)",+ "createdAt": "2025-12-22T05:28:22.924Z",+ "id": "msg_2",+ "model": "claude-sonnet-4-5-20250929",+ "parentId": "msg_1",+ "provider": "anthropic",+ "role": "assistant",+ "updatedAt": "2025-12-22T05:28:31.794Z"+ },+ {+ "content": "你好!(回复B - 分支)",+ "createdAt": "2025-12-22T05:28:40.645Z",+ "id": "msg_3",+ "model": "claude-sonnet-4-5-20250929",+ "parentId": "msg_1",+ "provider": "anthropic",+ "role": "assistant",+ "updatedAt": "2025-12-22T05:28:45.853Z"+ },+ {+ "content": "你是谁?",+ "createdAt": "2025-12-22T08:13:22.122Z",+ "id": "msg_4",+ "parentId": "msg_3",+ "role": "user",+ "updatedAt": "2025-12-22T08:13:22.122Z"+ },+ {+ "content": "我是 Lobe",+ "createdAt": "2025-12-22T08:13:22.811Z",+ "id": "msg_5",+ "model": "claude-sonnet-4-5-20250929",+ "parentId": "msg_4",+ "provider": "anthropic",+ "role": "assistant",+ "updatedAt": "2025-12-22T08:13:33.887Z"+ },+ {+ "content": "杭州天气如何",+ "createdAt": "2025-12-22T08:13:39.070Z",+ "id": "msg_6",+ "parentId": "msg_5",+ "role": "user",+ "updatedAt": "2025-12-22T08:13:39.070Z"+ },+ {+ "content": "让我帮你查询一下杭州的天气情况。",+ "createdAt": "2025-12-22T08:13:40.327Z",+ "id": "msg_7",+ "model": "claude-sonnet-4-5-20250929",+ "parentId": "msg_6",+ "provider": "anthropic",+ "role": "assistant",+ "updatedAt": "2025-12-22T08:13:51.821Z",+ "tools": [+ {+ "id": "toolu_1",+ "type": "builtin",+ "apiName": "search",+ "arguments": "{\"query\": \"杭州天气\"}",+ "identifier": "lobe-web-browsing"+ }+ ]+ },+ {+ "content": "<searchResults><item>杭州今天多云,气温3-14℃</item></searchResults>",+ "createdAt": "2025-12-22T08:13:54.734Z",+ "id": "msg_8",+ "parentId": "msg_7",+ "role": "tool",+ "updatedAt": "2025-12-22T08:14:00.457Z",+ "plugin": {+ "apiName": "search",+ "arguments": "{\"query\": \"杭州天气\"}",+ "identifier": "lobe-web-browsing",+ "type": "builtin"+ },+ "pluginState": {+ "query": "杭州天气",+ "results": [{ "title": "杭州天气", "content": "多云 3-14℃" }]+ },+ "tool_call_id": "toolu_1"+ },+ {+ "content": "让我搜索更具体的信息。",+ "createdAt": "2025-12-22T08:14:04.076Z",+ "id": "msg_9",+ "model": "claude-sonnet-4-5-20250929",+ "parentId": "msg_8",+ "provider": "anthropic",+ "role": "assistant",+ "updatedAt": "2025-12-22T08:14:12.238Z",+ "tools": [+ {+ "id": "toolu_2",+ "type": "builtin",+ "apiName": "search",+ "arguments": "{\"query\": \"杭州天气预报\"}",+ "identifier": "lobe-web-browsing"+ }+ ]+ },+ {+ "content": "<searchResults><item>杭州明天多云转阴,最高16℃</item></searchResults>",+ "createdAt": "2025-12-22T08:14:18.182Z",+ "id": "msg_10",+ "parentId": "msg_9",+ "role": "tool",+ "updatedAt": "2025-12-22T08:14:29.605Z",+ "plugin": {+ "apiName": "search",+ "arguments": "{\"query\": \"杭州天气预报\"}",+ "identifier": "lobe-web-browsing",+ "type": "builtin"+ },+ "pluginState": {+ "query": "杭州天气预报",+ "results": [{ "title": "杭州天气预报", "content": "明天多云转阴 16℃" }]+ },+ "tool_call_id": "toolu_2"+ },+ {+ "content": "杭州今天多云,气温3-14℃,明天16℃。",+ "createdAt": "2025-12-22T08:14:37.596Z",+ "id": "msg_11",+ "model": "claude-sonnet-4-5-20250929",+ "parentId": "msg_10",+ "provider": "anthropic",+ "role": "assistant",+ "updatedAt": "2025-12-22T08:15:00.663Z"+ }+ ],+ "title": "简单问候",+ "version": "2.0"+}diff --git a/packages/database/src/repositories/topicImporter/__tests__/importTopic.test.ts b/packages/database/src/repositories/topicImporter/__tests__/importTopic.test.tsnew file mode 100644index 00000000000..04adb115a1e--- /dev/null+++ b/packages/database/src/repositories/topicImporter/__tests__/importTopic.test.ts@@ -0,0 +1,286 @@+import type { ExportedTopic, ImportedMessage } from '@lobechat/types';+import { eq } from 'drizzle-orm';+import { readFileSync } from 'node:fs';+import path from 'node:path';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../models/__tests__/_util';+import { agents, messagePlugins, messages, topics, users } from '../../../schemas';+import { LobeChatDatabase } from '../../../type';+import { TopicImporterRepo } from '../index';++const userId = 'topic-importer-user';+const agentId = 'topic-importer-agent';+let serverDB: LobeChatDatabase;++describe('TopicImporterRepo.importTopic', () => {+ beforeEach(async () => {+ serverDB = await getTestDB();+ await serverDB.delete(users);+ await serverDB.transaction(async (tx) => {+ await tx.insert(users).values([{ id: userId }]);+ await tx.insert(agents).values({ id: agentId, userId, title: 'Test Agent' });+ });+ });++ afterEach(async () => {+ await serverDB.delete(users);+ });++ describe('simple format (array without parentId)', () => {+ it('should import messages and build linear parentId chain', async () => {+ const repo = new TopicImporterRepo(serverDB, userId);+ const importData: ImportedMessage[] = [+ { content: 'Hello', role: 'user' },+ { content: 'Hi there!', role: 'assistant' },+ { content: 'How are you?', role: 'user' },+ ];++ const result = await repo.importTopic({+ agentId,+ data: importData,+ });++ expect(result.messageCount).toBe(3);+ expect(result.topicId).toBeDefined();++ // Verify messages are inserted with linear parentId chain+ const insertedMessages = await serverDB+ .select()+ .from(messages)+ .where(eq(messages.topicId, result.topicId))+ .orderBy(messages.createdAt);++ expect(insertedMessages.length).toBe(3);+ expect(insertedMessages[0].parentId).toBeNull();+ expect(insertedMessages[1].parentId).toBe(insertedMessages[0].id);+ expect(insertedMessages[2].parentId).toBe(insertedMessages[1].id);+ });+ });++ describe('full format (ExportedTopic with parentId)', () => {+ it('should restore parentId chain from real exported data', async () => {+ const repo = new TopicImporterRepo(serverDB, userId);+ const jsonPath = path.join(__dirname, 'fixtures/exported-topic.json');+ const fileContent = readFileSync(jsonPath, 'utf-8');+ const exportedData = JSON.parse(fileContent) as ExportedTopic;++ const result = await repo.importTopic({+ agentId,+ data: exportedData,+ });++ expect(result.messageCount).toBe(11);++ // Verify topic is created with correct title+ const [insertedTopic] = await serverDB+ .select()+ .from(topics)+ .where(eq(topics.id, result.topicId));++ expect(insertedTopic.title).toBe('简单问候');++ // Verify messages are inserted+ const insertedMessages = await serverDB+ .select()+ .from(messages)+ .where(eq(messages.topicId, result.topicId))+ .orderBy(messages.createdAt);++ expect(insertedMessages.length).toBe(11);++ // Build id -> message map for verification+ const messageMap = new Map(insertedMessages.map((m) => [m.id, m]));++ // Verify parentId relationships+ // Message 0: root - no parent+ expect(insertedMessages[0].parentId).toBeNull();++ // Messages 1 and 2: both should have message 0 as parent (branching)+ expect(insertedMessages[1].parentId).toBe(insertedMessages[0].id);+ expect(insertedMessages[2].parentId).toBe(insertedMessages[0].id);++ // Message 3: should have message 2 as parent+ expect(insertedMessages[3].parentId).toBe(insertedMessages[2].id);++ // Verify the rest of the chain+ expect(insertedMessages[4].parentId).toBe(insertedMessages[3].id);+ expect(insertedMessages[5].parentId).toBe(insertedMessages[4].id);+ expect(insertedMessages[6].parentId).toBe(insertedMessages[5].id);+ expect(insertedMessages[7].parentId).toBe(insertedMessages[6].id);+ expect(insertedMessages[8].parentId).toBe(insertedMessages[7].id);+ expect(insertedMessages[9].parentId).toBe(insertedMessages[8].id);+ expect(insertedMessages[10].parentId).toBe(insertedMessages[9].id);+ });++ it('should preserve plugin and pluginState fields in message_plugins table', async () => {+ const repo = new TopicImporterRepo(serverDB, userId);+ const jsonPath = path.join(__dirname, 'fixtures/exported-topic.json');+ const fileContent = readFileSync(jsonPath, 'utf-8');+ const exportedData = JSON.parse(fileContent) as ExportedTopic;++ const result = await repo.importTopic({+ agentId,+ data: exportedData,+ });++ // Get tool messages (index 7 and 9 in original data)+ const insertedMessages = await serverDB+ .select()+ .from(messages)+ .where(eq(messages.topicId, result.topicId))+ .orderBy(messages.createdAt);++ // Find tool messages+ const toolMessages = insertedMessages.filter((m) => m.role === 'tool');+ expect(toolMessages.length).toBe(2);++ // Get plugin records for tool messages+ const pluginRecords = await serverDB+ .select()+ .from(messagePlugins)+ .where(eq(messagePlugins.userId, userId));++ expect(pluginRecords.length).toBe(2);++ // Find plugin record for first tool message+ const firstPlugin = pluginRecords.find((p) => p.id === toolMessages[0].id);+ expect(firstPlugin).toBeDefined();+ expect(firstPlugin!.apiName).toBe('search');+ expect(firstPlugin!.arguments).toBe('{"query": "杭州天气"}');+ expect(firstPlugin!.identifier).toBe('lobe-web-browsing');+ expect(firstPlugin!.type).toBe('builtin');+ expect(firstPlugin!.toolCallId).toBe('toolu_1');+ expect(firstPlugin!.state).toEqual({+ query: '杭州天气',+ results: [{ title: '杭州天气', content: '多云 3-14℃' }],+ });++ // Find plugin record for second tool message+ const secondPlugin = pluginRecords.find((p) => p.id === toolMessages[1].id);+ expect(secondPlugin).toBeDefined();+ expect(secondPlugin!.apiName).toBe('search');+ expect(secondPlugin!.arguments).toBe('{"query": "杭州天气预报"}');+ expect(secondPlugin!.toolCallId).toBe('toolu_2');+ expect(secondPlugin!.state).toEqual({+ query: '杭州天气预报',+ results: [{ title: '杭州天气预报', content: '明天多云转阴 16℃' }],+ });+ });++ it('should preserve tools array on assistant messages', async () => {+ const repo = new TopicImporterRepo(serverDB, userId);+ const jsonPath = path.join(__dirname, 'fixtures/exported-topic.json');+ const fileContent = readFileSync(jsonPath, 'utf-8');+ const exportedData = JSON.parse(fileContent) as ExportedTopic;++ const result = await repo.importTopic({+ agentId,+ data: exportedData,+ });++ const insertedMessages = await serverDB+ .select()+ .from(messages)+ .where(eq(messages.topicId, result.topicId))+ .orderBy(messages.createdAt);++ // Find assistant messages with tools (index 6 and 8 in original)+ const assistantWithTools = insertedMessages.filter(+ (m) => m.role === 'assistant' && m.tools && (m.tools as any[]).length > 0,+ );+ expect(assistantWithTools.length).toBe(2);++ expect(assistantWithTools[0].tools).toEqual([+ {+ id: 'toolu_1',+ type: 'builtin',+ apiName: 'search',+ arguments: '{"query": "杭州天气"}',+ identifier: 'lobe-web-browsing',+ },+ ]);+ });++ it('should preserve model and provider fields', async () => {+ const repo = new TopicImporterRepo(serverDB, userId);+ const jsonPath = path.join(__dirname, 'fixtures/exported-topic.json');+ const fileContent = readFileSync(jsonPath, 'utf-8');+ const exportedData = JSON.parse(fileContent) as ExportedTopic;++ const result = await repo.importTopic({+ agentId,+ data: exportedData,+ });++ const insertedMessages = await serverDB+ .select()+ .from(messages)+ .where(eq(messages.topicId, result.topicId))+ .orderBy(messages.createdAt);++ // Check assistant messages have model and provider+ const assistantMessages = insertedMessages.filter((m) => m.role === 'assistant');+ for (const msg of assistantMessages) {+ expect(msg.model).toBe('claude-sonnet-4-5-20250929');+ expect(msg.provider).toBe('anthropic');+ }+ });++ it('should verify branching is preserved (2 children for root)', async () => {+ const repo = new TopicImporterRepo(serverDB, userId);+ const jsonPath = path.join(__dirname, 'fixtures/exported-topic.json');+ const fileContent = readFileSync(jsonPath, 'utf-8');+ const exportedData = JSON.parse(fileContent) as ExportedTopic;++ const result = await repo.importTopic({+ agentId,+ data: exportedData,+ });++ const insertedMessages = await serverDB+ .select()+ .from(messages)+ .where(eq(messages.topicId, result.topicId))+ .orderBy(messages.createdAt);++ const rootId = insertedMessages[0].id;+ const messagesWithRootAsParent = insertedMessages.filter((m) => m.parentId === rootId);++ // Should have 2 children (branching from root)+ expect(messagesWithRootAsParent.length).toBe(2);+ });+ });++ describe('string input', () => {+ it('should accept JSON string as input', async () => {+ const repo = new TopicImporterRepo(serverDB, userId);+ const importData: ImportedMessage[] = [+ { content: 'Hello', role: 'user' },+ { content: 'Hi!', role: 'assistant' },+ ];++ const result = await repo.importTopic({+ agentId,+ data: JSON.stringify(importData),+ });++ expect(result.messageCount).toBe(2);+ });+ });++ describe('error handling', () => {+ it('should throw error when no valid messages to import', async () => {+ const repo = new TopicImporterRepo(serverDB, userId);+ // Only system messages - should be filtered out+ const importData: ImportedMessage[] = [{ content: 'System prompt', role: 'system' }];++ await expect(+ repo.importTopic({+ agentId,+ data: importData,+ }),+ ).rejects.toThrow('No valid messages to import');+ });+ });+});diff --git a/packages/database/src/repositories/topicImporter/index.ts b/packages/database/src/repositories/topicImporter/index.tsnew file mode 100644index 00000000000..0d545870ee1--- /dev/null+++ b/packages/database/src/repositories/topicImporter/index.ts@@ -0,0 +1,252 @@+import type { ExportedTopic, ImportedMessage } from '@lobechat/types';++import { messagePlugins, messages, topics } from '../../schemas';+import { LobeChatDatabase } from '../../type';+import { idGenerator } from '../../utils/idGenerator';++export interface ImportTopicParams {+ agentId: string;+ /** JSON string or parsed object */+ data: ExportedTopic | ImportedMessage[] | string;+ groupId?: string | null;+}++export interface ImportTopicResult {+ messageCount: number;+ topicId: string;+}++interface PreparedMessage {+ agentId: string;+ content: string;+ createdAt: Date;+ error?: Record<string, any> | null;+ id: string;+ metadata?: Record<string, any> | null;+ model?: string | null;+ parentId: string | null;+ provider?: string | null;+ reasoning?: Record<string, any> | null;+ role: string;+ search?: Record<string, any> | null;+ tools?: Record<string, any>[] | null;+ topicId: string;+ traceId?: string | null;+ updatedAt: Date;+ userId: string;+}++interface PreparedMessagePlugin {+ apiName?: string | null;+ arguments?: string | null;+ error?: Record<string, any> | null;+ id: string;+ identifier?: string | null;+ state?: Record<string, any> | null;+ toolCallId?: string | null;+ type?: string | null;+ userId: string;+}++export class TopicImporterRepo {+ private userId: string;+ private db: LobeChatDatabase;++ constructor(db: LobeChatDatabase, userId: string) {+ this.userId = userId;+ this.db = db;+ }++ /**+ * Import messages as a new topic+ */+ importTopic = async (params: ImportTopicParams): Promise<ImportTopicResult> => {+ const { agentId, groupId, data } = params;++ // Parse data if it's a string+ const parsedData = typeof data === 'string' ? JSON.parse(data) : data;++ // Extract messages and title from parsed data+ const { messages: importedMessages, title } = this.parseImportData(parsedData);++ // Filter out system messages and prepare messages+ const filteredMessages = importedMessages.filter((m) => m.role !== 'system');++ if (filteredMessages.length === 0) {+ throw new Error('No valid messages to import');+ }++ return this.db.transaction(async (tx) => {+ // Generate new topic ID+ const topicId = idGenerator('topics');++ // Prepare messages with new IDs and rebuild parentId chain+ const { messages: preparedMessages, plugins: preparedPlugins } = this.prepareMessages(+ filteredMessages,+ topicId,+ agentId,+ );++ // Insert topic first+ await tx.insert(topics).values({+ agentId,+ groupId: groupId || null,+ id: topicId,+ title: title || 'Imported Topic',+ userId: this.userId,+ });++ // Batch insert messages+ if (preparedMessages.length > 0) {+ await tx.insert(messages).values(preparedMessages as any);+ }++ // Batch insert message plugins (for tool messages)+ if (preparedPlugins.length > 0) {+ await tx.insert(messagePlugins).values(preparedPlugins as any);+ }++ return {+ messageCount: preparedMessages.length,+ topicId,+ };+ });+ };++ /**+ * Parse import data to extract messages and title+ * Supports both simple array format and full ExportedTopic format+ */+ private parseImportData(data: unknown): { messages: ImportedMessage[]; title?: string } {+ // Format 1: Array (simple OpenAI compatible format)+ if (Array.isArray(data)) {+ return { messages: data as ImportedMessage[] };+ }++ // Format 2: ExportedTopic object (full lossless format)+ if (data && typeof data === 'object' && 'version' in data) {+ const fullData = data as ExportedTopic;+ return {+ messages: fullData.messages as ImportedMessage[],+ title: fullData.title,+ };+ }++ throw new Error('Invalid import format: expected array or ExportedTopic object');+ }++ /**+ * Prepare messages with new IDs and rebuild parentId chain+ */+ private prepareMessages(+ importedMessages: ImportedMessage[],+ topicId: string,+ agentId: string,+ ): { messages: PreparedMessage[]; plugins: PreparedMessagePlugin[] } {+ const now = Date.now();++ // Check if original data has any parentId info (before mapping)+ // This determines whether we should build a linear chain for missing parentIds+ const hasOriginalParentInfo = importedMessages.some(+ (m) => m.parentId !== undefined && m.parentId !== null,+ );++ // Build oldId -> newId mapping+ const idMapping = new Map<string, string>();++ // First pass: generate new IDs and create mapping+ const messagesWithNewIds = importedMessages.map((msg, index) => {+ const newId = idGenerator('messages');++ // If original message has an ID, create mapping+ if (msg.id) {+ idMapping.set(msg.id, newId);+ }++ return {+ ...msg,+ newId,+ originalParentId: msg.parentId,+ // Preserve original timestamp or generate sequential one+ timestamp: this.parseTimestamp(msg.createdAt, now + index),+ updatedTimestamp: this.parseTimestamp(msg.updatedAt, now + index),+ };+ });++ // Second pass: rebuild parentId chain and collect plugin data+ const preparedMessages: PreparedMessage[] = [];+ const preparedPlugins: PreparedMessagePlugin[] = [];++ for (const msg of messagesWithNewIds) {+ let parentId: string | null = null;++ // Try to restore original parentId relationship+ if (msg.originalParentId) {+ parentId = idMapping.get(msg.originalParentId) ?? null;+ }++ // Prepare message (without plugin fields - they go to separate table)+ preparedMessages.push({+ agentId,+ content: msg.content,+ createdAt: new Date(msg.timestamp),+ error: msg.error || null,+ id: msg.newId,+ metadata: msg.metadata || null,+ model: msg.model || null,+ parentId,+ provider: msg.provider || null,+ reasoning: msg.reasoning || null,+ role: msg.role,+ search: msg.search || null,+ tools: msg.tools || null,+ topicId,+ traceId: msg.traceId || null,+ updatedAt: new Date(msg.updatedTimestamp),+ userId: this.userId,+ });++ // If message has plugin data (tool messages), prepare plugin record+ if (msg.plugin || msg.pluginState || msg.pluginError || msg.tool_call_id) {+ const plugin = msg.plugin as Record<string, any> | undefined;+ preparedPlugins.push({+ apiName: plugin?.apiName || null,+ arguments: plugin?.arguments || null,+ error: msg.pluginError || null,+ id: msg.newId,+ identifier: plugin?.identifier || null,+ state: msg.pluginState || null,+ toolCallId: msg.tool_call_id || null,+ type: plugin?.type || null,+ userId: this.userId,+ });+ }+ }++ // If no parentId info exists in original data (simple format), build linear chain+ if (!hasOriginalParentInfo && preparedMessages.length > 1) {+ for (let i = 1; i < preparedMessages.length; i++) {+ preparedMessages[i].parentId = preparedMessages[i - 1].id;+ }+ }++ return { messages: preparedMessages, plugins: preparedPlugins };+ }++ /**+ * Parse timestamp from various formats+ */+ private parseTimestamp(value: number | string | undefined, fallback: number): number {+ if (value === undefined) {+ return fallback;+ }++ if (typeof value === 'number') {+ return value;+ }++ // Try to parse ISO string+ const parsed = Date.parse(value);+ return Number.isNaN(parsed) ? fallback : parsed;+ }+}diff --git a/packages/types/src/export.ts b/packages/types/src/export.tsindex 96d143df019..190387d8920 100644--- a/packages/types/src/export.ts+++ b/packages/types/src/export.ts@@ -9,3 +9,77 @@ export interface ImportPgDataStructure {mode: 'pglite' | 'postgres';schemaHash: string;}++// ===== Topic Export Types =====++/**+ * Export mode for topic JSON export+ * - simple: OpenAI compatible format (only role and content)+ * - full: Lossless backup format (includes all metadata)+ */+export type TopicExportMode = 'simple' | 'full';++/**+ * Complete lossless export format for a topic+ * Messages are exported as-is from UIChatMessage with timestamps converted to ISO strings+ */+export interface ExportedTopic {+ /** ISO timestamp when the export was created */+ exportedAt: string;+ /** All messages in the topic (UIChatMessage with cleaned null/undefined values) */+ messages: Record<string, any>[];+ /** Topic title (optional, not present for non-topic exports) */+ title?: string;+ /** Export format version for forward compatibility */+ version: '2.0';+}++// ===== Topic Import Types =====++/**+ * Message format for importing into a topic+ * Supports both simple (OpenAI compatible) and full (lossless) formats+ */+export interface ImportedMessage {+ content: string;+ /** ISO timestamp or Unix timestamp (ms) */+ createdAt?: number | string;+ /** Error information */+ error?: Record<string, any>;+ /** Original message ID (used for parentId mapping) */+ id?: string;+ /** Metadata */+ metadata?: Record<string, any>;+ /** Model used */+ model?: string;+ /** Parent message ID (for conversation tree) */+ parentId?: string | null;+ /** Plugin information */+ plugin?: Record<string, any>;+ /** Plugin error */+ pluginError?: Record<string, any>;+ /** Plugin intervention state */+ pluginIntervention?: Record<string, any>;+ /** Plugin state */+ pluginState?: Record<string, any>;+ /** Provider used */+ provider?: string;+ /** Reasoning content */+ reasoning?: Record<string, any>;+ role: 'user' | 'assistant' | 'system' | 'tool';+ /** Search results */+ search?: Record<string, any>;+ /** Tool call ID */+ tool_call_id?: string;+ /** Tool calls */+ tools?: Record<string, any>[];+ /** Trace ID */+ traceId?: string;+ /** ISO timestamp or Unix timestamp (ms) */+ updatedAt?: number | string;+}++/**+ * Import data format - can be either simple array or full ExportedTopic format+ */+export type ImportTopicData = ExportedTopic | ImportedMessage[];diff --git a/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/useDropdownMenu.tsx b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/useDropdownMenu.tsxindex beef73fc002..e9d1c0ec833 100644--- a/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/useDropdownMenu.tsx+++ b/src/app/[variants]/(main)/chat/_layout/Sidebar/Topic/useDropdownMenu.tsx@@ -1,7 +1,8 @@import { Icon, type MenuProps } from '@lobehub/ui';-import { App } from 'antd';-import { Hash, LucideCheck, Trash } from 'lucide-react';-import { useMemo } from 'react';+import { App, Upload } from 'antd';+import { css, cx } from 'antd-style';+import { Hash, Import, LucideCheck, Trash } from 'lucide-react';+import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';import { useChatStore } from '@/store/chat';@@ -11,15 +12,43 @@ import { useUserStore } from '@/store/user';import { preferenceSelectors } from '@/store/user/selectors';import { TopicDisplayMode } from '@/types/topic';+const hotArea = css`+ &::before {+ content: '';+ position: absolute;+ inset: 0;+ background-color: transparent;+ }+`;+export const useTopicActionsDropdownMenu = (): MenuProps['items'] => {const { t } = useTranslation(['topic', 'common']);const { modal } = App.useApp();- const [removeUnstarredTopic, removeAllTopic] = useChatStore((s) => [+ const [removeUnstarredTopic, removeAllTopic, importTopic] = useChatStore((s) => [s.removeUnstarredTopic,s.removeSessionTopics,+ s.importTopic,]);+ const handleImport = useCallback(+ async (file: File) => {+ try {+ const text = await file.text();+ // Validate JSON format+ JSON.parse(text);+ await importTopic(text);+ } catch {+ modal.error({+ content: t('importInvalidFormat'),+ title: t('importError'),+ });+ }+ return false; // Prevent default upload behavior+ },+ [importTopic, modal, t],+ );+const [topicDisplayMode, updatePreference] = useUserStore((s) => [preferenceSelectors.topicDisplayMode(s),s.updatePreference,@@ -64,6 +93,18 @@ export const useTopicActionsDropdownMenu = (): MenuProps['items'] => {{type: 'divider' as const,},+ {+ icon: <Icon icon={Import} />,+ key: 'import',+ label: (+ <Upload accept=".json" beforeUpload={handleImport} showUploadList={false}>+ <div className={cx(hotArea)}>{t('actions.import')}</div>+ </Upload>+ ),+ },+ {+ type: 'divider' as const,+ },{icon: <Icon icon={Trash} />,key: 'deleteUnstarred',@@ -101,6 +142,7 @@ export const useTopicActionsDropdownMenu = (): MenuProps['items'] => {topicPageSize,updatePreference,updateSystemStatus,+ handleImport,removeUnstarredTopic,removeAllTopic,t,diff --git a/src/app/[variants]/(main)/chat/features/Conversation/AgentWelcome/ToolAuthAlert.tsx b/src/app/[variants]/(main)/chat/features/Conversation/AgentWelcome/ToolAuthAlert.tsxindex f8d5cc2120b..449d05b629e 100644--- a/src/app/[variants]/(main)/chat/features/Conversation/AgentWelcome/ToolAuthAlert.tsx+++ b/src/app/[variants]/(main)/chat/features/Conversation/AgentWelcome/ToolAuthAlert.tsx@@ -1,8 +1,7 @@'use client';import { KLAVIS_SERVER_TYPES, KlavisServerType } from '@lobechat/const';-import { Alert, Button, Flexbox, Icon, Image } from '@lobehub/ui';-import { Typography } from 'antd';+import { Block, Button, Flexbox, Icon, Image, Text } from '@lobehub/ui';import { useTheme } from 'antd-style';import isEqual from 'fast-deep-equal';import { Loader2, LogIn, SquareArrowOutUpRight, TriangleAlert } from 'lucide-react';@@ -301,37 +300,37 @@ const ToolAuthAlert = memo(() => {}return (- <Alert- description={- <Flexbox gap={12} style={{ marginTop: 8 }}>- {pendingAuthTools.map((tool) =>- tool.authType === 'klavis' ? (- <KlavisToolAuthItem- key={tool.identifier}- onAuthComplete={() => {- // Component will re-render and tool will be removed from list- }}- tool={tool}- />- ) : (- <MarketToolAuthItem key={tool.identifier} tool={tool} />- ),- )}- <Typography.Text style={{ color: theme.colorTextSecondary, fontSize: 12 }}>- {t('toolAuth.hint')}- </Typography.Text>- </Flexbox>- }- message={- <Flexbox align="center" gap={6} horizontal>- <Icon icon={TriangleAlert} size={18} />- {t('toolAuth.title')}- </Flexbox>- }- showIcon={false}- style={{ width: '100%' }}- type="warning"- />+ <Block+ gap={12}+ padding={12}+ style={{+ width: '100%',+ }}+ variant={'filled'}+ >+ <Flexbox align="center" gap={6} horizontal style={{ fontWeight: 500 }}>+ <Icon color={theme.colorWarning} icon={TriangleAlert} size={18} />+ {t('toolAuth.title')}+ </Flexbox>+ <Text style={{ fontSize: 12 }} type="secondary">+ {t('toolAuth.hint')}+ </Text>+ <Block gap={12} padding={12} variant={'outlined'}>+ {pendingAuthTools.map((tool) =>+ tool.authType === 'klavis' ? (+ <KlavisToolAuthItem+ key={tool.identifier}+ onAuthComplete={() => {+ // Component will re-render and tool will be removed from list+ }}+ tool={tool}+ />+ ) : (+ <MarketToolAuthItem key={tool.identifier} tool={tool} />+ ),+ )}+ </Block>+ </Block>);});diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.tsxindex beef73fc002..e9d1c0ec833 100644--- a/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.tsx+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.tsx@@ -1,7 +1,8 @@import { Icon, type MenuProps } from '@lobehub/ui';-import { App } from 'antd';-import { Hash, LucideCheck, Trash } from 'lucide-react';-import { useMemo } from 'react';+import { App, Upload } from 'antd';+import { css, cx } from 'antd-style';+import { Hash, Import, LucideCheck, Trash } from 'lucide-react';+import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';import { useChatStore } from '@/store/chat';@@ -11,15 +12,43 @@ import { useUserStore } from '@/store/user';import { preferenceSelectors } from '@/store/user/selectors';import { TopicDisplayMode } from '@/types/topic';+const hotArea = css`+ &::before {+ content: '';+ position: absolute;+ inset: 0;+ background-color: transparent;+ }+`;+export const useTopicActionsDropdownMenu = (): MenuProps['items'] => {const { t } = useTranslation(['topic', 'common']);const { modal } = App.useApp();- const [removeUnstarredTopic, removeAllTopic] = useChatStore((s) => [+ const [removeUnstarredTopic, removeAllTopic, importTopic] = useChatStore((s) => [s.removeUnstarredTopic,s.removeSessionTopics,+ s.importTopic,]);+ const handleImport = useCallback(+ async (file: File) => {+ try {+ const text = await file.text();+ // Validate JSON format+ JSON.parse(text);+ await importTopic(text);+ } catch {+ modal.error({+ content: t('importInvalidFormat'),+ title: t('importError'),+ });+ }+ return false; // Prevent default upload behavior+ },+ [importTopic, modal, t],+ );+const [topicDisplayMode, updatePreference] = useUserStore((s) => [preferenceSelectors.topicDisplayMode(s),s.updatePreference,@@ -64,6 +93,18 @@ export const useTopicActionsDropdownMenu = (): MenuProps['items'] => {{type: 'divider' as const,},+ {+ icon: <Icon icon={Import} />,+ key: 'import',+ label: (+ <Upload accept=".json" beforeUpload={handleImport} showUploadList={false}>+ <div className={cx(hotArea)}>{t('actions.import')}</div>+ </Upload>+ ),+ },+ {+ type: 'divider' as const,+ },{icon: <Icon icon={Trash} />,key: 'deleteUnstarred',@@ -101,6 +142,7 @@ export const useTopicActionsDropdownMenu = (): MenuProps['items'] => {topicPageSize,updatePreference,updateSystemStatus,+ handleImport,removeUnstarredTopic,removeAllTopic,t,diff --git a/src/features/ShareModal/ShareJSON/generateFullExport.test.ts b/src/features/ShareModal/ShareJSON/generateFullExport.test.tsnew file mode 100644index 00000000000..9226673e7ee--- /dev/null+++ b/src/features/ShareModal/ShareJSON/generateFullExport.test.ts@@ -0,0 +1,150 @@+import { ChatTopic, UIChatMessage } from '@lobechat/types';+import { describe, expect, it, vi } from 'vitest';++import { LOADING_FLAT } from '@/const/message';++import { generateFullExport } from './generateFullExport';++describe('generateFullExport', () => {+ const mockMessages = [+ {+ id: 'msg-1',+ content: 'Hello',+ role: 'user',+ parentId: null,+ createdAt: 1700000000000,+ updatedAt: 1700000000000,+ model: null,+ provider: null,+ },+ {+ id: 'msg-2',+ content: 'Hi there!',+ role: 'assistant',+ parentId: 'msg-1',+ createdAt: 1700000001000,+ updatedAt: 1700000001000,+ model: 'gpt-4',+ provider: 'openai',+ },+ {+ id: 'msg-3',+ content: LOADING_FLAT,+ role: 'assistant',+ parentId: 'msg-2',+ createdAt: 1700000002000,+ updatedAt: 1700000002000,+ },+ ] as UIChatMessage[];++ const mockTopic: ChatTopic = {+ id: 'topic-1',+ title: 'Test Topic',+ favorite: true,+ createdAt: 1700000000000,+ updatedAt: 1700000003000,+ };++ beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2024-01-01T00:00:00.000Z'));+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('should export messages with correct structure', () => {+ const result = generateFullExport({+ messages: mockMessages,+ withSystemRole: false,+ includeTool: false,+ systemRole: '',+ });++ expect(result.version).toBe('2.0');+ expect(result.exportedAt).toBe('2024-01-01T00:00:00.000Z');+ expect(result.messages).toHaveLength(2); // Excluding loading message+ });++ it('should include topic title when provided', () => {+ const result = generateFullExport({+ messages: mockMessages,+ withSystemRole: false,+ includeTool: false,+ systemRole: '',+ topic: mockTopic,+ });++ expect(result.title).toBe('Test Topic');+ });++ it('should not include title when topic not provided', () => {+ const result = generateFullExport({+ messages: mockMessages,+ withSystemRole: false,+ includeTool: false,+ systemRole: '',+ });++ expect(result.title).toBeUndefined();+ });++ it('should include system role message when withSystemRole is true', () => {+ const systemRole = 'I am a helpful assistant';+ const result = generateFullExport({+ messages: mockMessages,+ withSystemRole: true,+ includeTool: false,+ systemRole,+ });++ expect(result.messages[0].role).toBe('system');+ expect(result.messages[0].content).toBe(systemRole);+ expect(result.messages[0].id).toBe('system-role');+ // system role message doesn't have parentId field+ expect(result.messages[0].parentId).toBeUndefined();+ });++ it('should preserve message metadata', () => {+ const result = generateFullExport({+ messages: mockMessages,+ withSystemRole: false,+ includeTool: false,+ systemRole: '',+ });++ const userMessage = result.messages.find((m) => m.id === 'msg-1');+ const assistantMessage = result.messages.find((m) => m.id === 'msg-2');++ // parentId is cleaned when null (cleanObject removes null values)+ expect(userMessage?.parentId).toBeUndefined();+ expect(assistantMessage?.parentId).toBe('msg-1');+ expect(assistantMessage?.model).toBe('gpt-4');+ expect(assistantMessage?.provider).toBe('openai');+ });++ it('should convert timestamps to ISO format', () => {+ const result = generateFullExport({+ messages: mockMessages,+ withSystemRole: false,+ includeTool: false,+ systemRole: '',+ });++ const message = result.messages[0];+ expect(message.createdAt).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z$/);+ expect(message.updatedAt).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z$/);+ });++ it('should filter out loading messages', () => {+ const result = generateFullExport({+ messages: mockMessages,+ withSystemRole: false,+ includeTool: false,+ systemRole: '',+ });++ expect(result.messages.some((m) => m.content === LOADING_FLAT)).toBeFalsy();+ });+});diff --git a/src/features/ShareModal/ShareJSON/generateFullExport.ts b/src/features/ShareModal/ShareJSON/generateFullExport.tsnew file mode 100644index 00000000000..d492f0342ae--- /dev/null+++ b/src/features/ShareModal/ShareJSON/generateFullExport.ts@@ -0,0 +1,73 @@+import { ChatTopic, ExportedTopic, UIChatMessage } from '@lobechat/types';+import { cleanObject } from '@lobechat/utils';++import { LOADING_FLAT } from '@/const/message';++import { BaseExportOptions } from './type';++interface FullExportParams extends BaseExportOptions {+ messages: UIChatMessage[];+ systemRole: string;+ topic?: ChatTopic;+}++/**+ * Generates a lossless export of topic data including all message metadata+ */+export const generateFullExport = ({+ topic,+ messages,+ systemRole,+ withSystemRole,+}: FullExportParams): ExportedTopic => {+ const exportedMessages: Record<string, any>[] = messages+ .filter((m) => m.content !== LOADING_FLAT)+ .map((m) =>+ /* eslint-disable sort-keys-fix/sort-keys-fix */+ cleanObject({+ // Core fields+ content: m.content,+ createdAt: new Date(m.createdAt).toISOString(),+ error: m.error,+ id: m.id,+ model: m.model,+ parentId: m.parentId,+ provider: m.provider,+ role: m.role,+ updatedAt: new Date(m.updatedAt).toISOString(),++ // Tool/Plugin fields+ plugin: m.plugin,+ pluginError: m.pluginError,+ pluginIntervention: m.pluginIntervention,+ pluginState: m.pluginState,+ tool_call_id: m.tool_call_id,+ tools: m.tools,++ // Extended fields+ metadata: m.metadata,+ reasoning: m.reasoning,+ search: m.search,+ traceId: m.traceId,+ }),+ );++ // Add system role as a separate message if requested+ if (withSystemRole && !!systemRole) {+ const now = new Date().toISOString();+ exportedMessages.unshift({+ content: systemRole,+ createdAt: now,+ id: 'system-role',+ role: 'system',+ updatedAt: now,+ });+ }++ return cleanObject({+ version: '2.0',+ title: topic?.title,+ messages: exportedMessages,+ exportedAt: new Date().toISOString(),+ });+};diff --git a/src/features/ShareModal/ShareJSON/generateMessages.ts b/src/features/ShareModal/ShareJSON/generateMessages.tsindex 06f419b420a..b0ce071f7f3 100644--- a/src/features/ShareModal/ShareJSON/generateMessages.ts+++ b/src/features/ShareModal/ShareJSON/generateMessages.ts@@ -2,9 +2,9 @@ import { UIChatMessage } from '@lobechat/types';import { LOADING_FLAT } from '@/const/message';-import { FieldType } from './type';+import { BaseExportOptions } from './type';-interface JSONParams extends FieldType {+interface JSONParams extends BaseExportOptions {messages: UIChatMessage[];systemRole: string;}diff --git a/src/features/ShareModal/ShareJSON/index.tsx b/src/features/ShareModal/ShareJSON/index.tsxindex 16caaad09df..846928f495b 100644--- a/src/features/ShareModal/ShareJSON/index.tsx+++ b/src/features/ShareModal/ShareJSON/index.tsx@@ -1,11 +1,12 @@import { FORM_STYLE } from '@lobechat/const';+import { TopicExportMode } from '@lobechat/types';import { exportFile } from '@lobechat/utils/client';import { Button, Form, type FormItemProps, copyToClipboard } from '@lobehub/ui';import { Flexbox } from '@lobehub/ui';-import { App, Switch } from 'antd';+import { App, Segmented, Switch } from 'antd';import isEqual from 'fast-deep-equal';import { CopyIcon } from 'lucide-react';-import { memo, useState } from 'react';+import { memo, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import { useIsMobile } from '@/hooks/useIsMobile';@@ -16,45 +17,73 @@ import { dbMessageSelectors, topicSelectors } from '@/store/chat/selectors';import { useStyles } from '../style';import Preview from './Preview';+import { generateFullExport } from './generateFullExport';import { generateMessages } from './generateMessages';import { FieldType } from './type';const DEFAULT_FIELD_VALUE: FieldType = {+ exportMode: 'full',includeTool: true,withSystemRole: true,};-const ShareImage = memo(() => {+const ShareJSON = memo(() => {const [fieldValue, setFieldValue] = useState(DEFAULT_FIELD_VALUE);const { t } = useTranslation(['chat', 'common']);const { styles } = useStyles();const { message } = App.useApp();+ const exportModeOptions = useMemo(+ () => [+ { label: t('shareModal.exportMode.full'), value: 'full' as TopicExportMode },+ { label: t('shareModal.exportMode.simple'), value: 'simple' as TopicExportMode },+ ],+ [t],+ );+const settings: FormItemProps[] = [{- children: <Switch />,- label: t('shareModal.withSystemRole'),- layout: 'horizontal',+ children: (+ <Segmented+ block+ onChange={(value) => setFieldValue((prev) => ({ ...prev, exportMode: value }))}+ options={exportModeOptions}+ value={fieldValue.exportMode}+ />+ ),+ label: t('shareModal.exportMode.label'),+ layout: 'vertical',minWidth: undefined,- name: 'withSystemRole',- valuePropName: 'checked',+ name: 'exportMode',},{children: <Switch />,- label: t('shareModal.includeTool'),+ label: t('shareModal.withSystemRole'),layout: 'horizontal',minWidth: undefined,- name: 'includeTool',+ name: 'withSystemRole',valuePropName: 'checked',},];const systemRole = useAgentStore(agentSelectors.currentAgentSystemRole);const messages = useChatStore(dbMessageSelectors.activeDbMessages, isEqual);- const data = generateMessages({ ...fieldValue, messages, systemRole });+ const topic = useChatStore(topicSelectors.currentActiveTopic, isEqual);++ // Always include tool messages (includeTool: true)+ const data =+ fieldValue.exportMode === 'simple'+ ? generateMessages({ ...fieldValue, includeTool: true, messages, systemRole })+ : generateFullExport({+ ...fieldValue,+ includeTool: true,+ messages,+ systemRole,+ topic: topic ?? undefined,+ });+const content = JSON.stringify(data, null, 2);- const topic = useChatStore(topicSelectors.currentActiveTopic, isEqual);const title = topic?.title || t('shareModal.exportTitle');const isMobile = useIsMobile();@@ -109,4 +138,4 @@ const ShareImage = memo(() => {);});-export default ShareImage;+export default ShareJSON;diff --git a/src/features/ShareModal/ShareJSON/type.ts b/src/features/ShareModal/ShareJSON/type.tsindex b18e83f7394..f74af9e0ec3 100644--- a/src/features/ShareModal/ShareJSON/type.ts+++ b/src/features/ShareModal/ShareJSON/type.ts@@ -1,4 +1,10 @@-export interface FieldType {+import { TopicExportMode } from '@lobechat/types';++export interface BaseExportOptions {includeTool: boolean;withSystemRole: boolean;}++export interface FieldType extends BaseExportOptions {+ exportMode: TopicExportMode;+}diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.tsindex 300ee3cc3b3..e742529438f 100644--- a/src/locales/default/chat.ts+++ b/src/locales/default/chat.ts@@ -384,6 +384,11 @@ export default {downloadFile: '下载文件',downloadPdf: '下载 PDF',downloadSuccess: '下载成功',+ exportMode: {+ full: '默认',+ label: '导出模式',+ simple: 'OpenAI 兼容',+ },exportPdf: '导出为 PDF',exportTitle: '默认标题',generatePdf: '生成 PDF',@@ -497,7 +502,7 @@ export default {authorizing: '授权中...',hint: '如不授权或配置,这些工具将无法正常使用,可能导致助手功能缺失或报错。',signIn: '登录',- title: '该助手使用了以下需要授权的工具',+ title: '请为助手完成工具的授权',},topic: {checkOpenNewTopic: '是否开启新话题?',diff --git a/src/locales/default/topic.ts b/src/locales/default/topic.tsindex 721076b97ff..532ed79445d 100644--- a/src/locales/default/topic.ts+++ b/src/locales/default/topic.ts@@ -7,6 +7,7 @@ export default {confirmRemoveUnstarred: '即将删除未收藏话题,删除后将不可恢复,请谨慎操作。',duplicate: '创建副本',export: '导出话题',+ import: '导入对话',openInNewWindow: '打开独立窗口',removeAll: '删除全部话题',removeUnstarred: '删除未收藏话题',@@ -34,6 +35,10 @@ export default {desc: '点击发送左侧按钮可将当前会话保存为历史话题,并开启新一轮会话',title: '话题列表',},+ importError: '导入失败',+ importInvalidFormat: '文件格式无效,请确保是有效的 JSON 文件',+ importLoading: '正在导入对话...',+ importSuccess: '成功导入 {{count}} 条消息',loadMore: '更多',searchPlaceholder: '搜索话题...',searchResultEmpty: '暂无搜索结果',diff --git a/src/server/routers/lambda/topic.ts b/src/server/routers/lambda/topic.tsindex 45693123e9b..caf700c9fd3 100644--- a/src/server/routers/lambda/topic.ts+++ b/src/server/routers/lambda/topic.ts@@ -5,6 +5,7 @@ import { z } from 'zod';import { TopicModel } from '@/database/models/topic';import { AgentMigrationRepo } from '@/database/repositories/agentMigration';+import { TopicImporterRepo } from '@/database/repositories/topicImporter';import { agents, chatGroups, chatGroupsAgents } from '@/database/schemas';import { authedProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';@@ -23,6 +24,7 @@ const topicProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {return opts.next({ctx: {agentMigrationRepo: new AgentMigrationRepo(ctx.serverDB, ctx.userId),+ topicImporterRepo: new TopicImporterRepo(ctx.serverDB, ctx.userId),topicModel: new TopicModel(ctx.serverDB, ctx.userId),},});@@ -200,6 +202,24 @@ export const topicRouter = router({return (await ctx.topicModel.count()) === 0;}),+ importTopic: topicProcedure+ .input(+ z.object({+ agentId: z.string(),+ data: z.string(),+ groupId: z.string().nullable().optional(),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ const result = await ctx.topicImporterRepo.importTopic({+ agentId: input.agentId,+ data: input.data,+ groupId: input.groupId,+ });++ return result;+ }),+rankTopics: topicProcedure.input(z.number().optional()).query(async ({ ctx, input }) => {return ctx.topicModel.rank(input);}),diff --git a/src/services/topic/index.ts b/src/services/topic/index.tsindex c3cdedbcbb0..fadfd8cd801 100644--- a/src/services/topic/index.ts+++ b/src/services/topic/index.ts@@ -25,6 +25,14 @@ export class TopicService {return lambdaClient.topic.cloneTopic.mutate({ id, newTitle });};+ importTopic = (params: {+ agentId: string;+ data: string;+ groupId?: string | null;+ }): Promise<{ messageCount: number; topicId: string }> => {+ return lambdaClient.topic.importTopic.mutate(params);+ };+getTopics = async (params: QueryTopicParams): Promise<{ items: ChatTopic[]; total: number }> => {return lambdaClient.topic.getTopics.query({agentId: params.agentId,diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.tsindex 0c468bd83fa..2112761ce2d 100644--- a/src/store/chat/slices/topic/action.ts+++ b/src/store/chat/slices/topic/action.ts@@ -37,6 +37,7 @@ const SWR_USE_SEARCH_TOPIC = 'SWR_USE_SEARCH_TOPIC';export interface ChatTopicAction {closeAllTopicsDrawer: () => void;favoriteTopic: (id: string, favState: boolean) => Promise<void>;+ importTopic: (data: string) => Promise<string | undefined>;loadMoreTopics: () => Promise<void>;openAllTopicsDrawer: () => void;openNewTopicOrSaveTopic: () => Promise<void>;@@ -178,6 +179,39 @@ export const chatTopic: StateCreator<await switchTopic(newTopicId);},++ importTopic: async (data) => {+ const { activeAgentId, activeGroupId, refreshTopic, switchTopic } = get();++ if (!activeAgentId) return;++ message.loading({+ content: t('importLoading', { ns: 'topic' }),+ duration: 0,+ key: 'importTopic',+ });++ try {+ const result = await topicService.importTopic({+ agentId: activeAgentId,+ data,+ groupId: activeGroupId,+ });++ await refreshTopic();+ message.destroy('importTopic');+ message.success(t('importSuccess', { count: result.messageCount, ns: 'topic' }));++ await switchTopic(result.topicId);++ return result.topicId;+ } catch (error) {+ message.destroy('importTopic');+ message.error(t('importError', { ns: 'topic' }));+ console.error('[importTopic] Failed:', error);+ return undefined;+ }+ },// updatesummaryTopicTitle: async (topicId, messages) => {const { internal_updateTopicTitleInSummary, internal_updateTopicLoading } = get();