🤯 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
💄 style(conversation): persist per-topic chat scroll position (#14191)
Arvin Xua176288670bc
diff --git a/docs/self-hosting/environment-variables/basic.mdx b/docs/self-hosting/environment-variables/basic.mdxindex 68a03745c8e..5632e082740 100644--- a/docs/self-hosting/environment-variables/basic.mdx+++ b/docs/self-hosting/environment-variables/basic.mdx@@ -91,14 +91,13 @@ Configuration details:Available system agents and their functions:-| System Agent | Key Name | Function Description |-| ------------------- | ----------------- | --------------------------------------------------------------------------------------------------- |-| Topic Generation | `topic` | Automatically generates topic names and summaries based on chat content |-| Translation | `translation` | Handles text translation between multiple languages |-| Metadata Generation | `agentMeta` | Generates descriptive information and metadata for assistants |-| History Compression | `historyCompress` | Compresses and organizes history for long conversations, optimizing context management |-| Query Rewrite | `queryRewrite` | Rewrites follow-up questions as standalone questions with context, improving conversation coherence |-| Thread Management | `thread` | Handles the creation and management of conversation threads |+| System Agent | Key Name | Function Description |+| ------------------- | ----------------- | -------------------------------------------------------------------------------------- |+| Topic Generation | `topic` | Automatically generates topic names and summaries based on chat content |+| Translation | `translation` | Handles text translation between multiple languages |+| Metadata Generation | `agentMeta` | Generates descriptive information and metadata for assistants |+| History Compression | `historyCompress` | Compresses and organizes history for long conversations, optimizing context management |+| Thread Management | `thread` | Handles the creation and management of conversation threads |### `FEATURE_FLAGS`diff --git a/docs/self-hosting/environment-variables/basic.zh-CN.mdx b/docs/self-hosting/environment-variables/basic.zh-CN.mdxindex 191a1e5292a..b0d7b50ca1a 100644--- a/docs/self-hosting/environment-variables/basic.zh-CN.mdx+++ b/docs/self-hosting/environment-variables/basic.zh-CN.mdx@@ -88,14 +88,13 @@ LobeHub 在部署时提供了一些额外的配置项,你可以使用环境变可配置的系统助手及其作用:-| 系统助手 | 键名 | 作用描述 |-| ------- | ----------------- | --------------------------- |-| 主题生成 | `topic` | 根据聊天内容自动生成主题名称和摘要 |-| 翻译 | `translation` | 文本翻译使用的助手 |-| 元数据生成 | `agentMeta` | 为助手生成描述性信息和元数据 |-| 历史记录压缩 | `historyCompress` | 压缩和整理长对话的历史记录,优化上下文管理 |-| 知识库查询重写 | `queryRewrite` | 将后续问题改写为包含上下文的独立问题,提升对话的连贯性 |-| 分支对话 | `thread` | 自定生成分支对话的标题 |+| 系统助手 | 键名 | 作用描述 |+| ------ | ----------------- | --------------------- |+| 主题生成 | `topic` | 根据聊天内容自动生成主题名称和摘要 |+| 翻译 | `translation` | 文本翻译使用的助手 |+| 元数据生成 | `agentMeta` | 为助手生成描述性信息和元数据 |+| 历史记录压缩 | `historyCompress` | 压缩和整理长对话的历史记录,优化上下文管理 |+| 分支对话 | `thread` | 自定生成分支对话的标题 |### `FEATURE_FLAGS`diff --git a/locales/ar/setting.json b/locales/ar/setting.jsonindex 1a78d99064e..2a9ac4aeb5d 100644--- a/locales/ar/setting.json+++ b/locales/ar/setting.json@@ -798,9 +798,6 @@"systemAgent.promptRewrite.label": "النموذج","systemAgent.promptRewrite.modelDesc": "حدد النموذج المستخدم لإعادة صياغة المطالبات","systemAgent.promptRewrite.title": "وكيل إعادة صياغة المطالبات",- "systemAgent.queryRewrite.label": "النموذج",- "systemAgent.queryRewrite.modelDesc": "تحديد النموذج المستخدم لتحسين استفسارات المستخدم",- "systemAgent.queryRewrite.title": "وكيل إعادة صياغة استعلام المكتبة","systemAgent.thread.label": "النموذج","systemAgent.thread.modelDesc": "النموذج المخصص لإعادة تسمية المواضيع الفرعية تلقائيًا","systemAgent.thread.title": "وكيل التسمية التلقائية للمواضيع الفرعية",diff --git a/locales/bg-BG/setting.json b/locales/bg-BG/setting.jsonindex b4ebbd65e65..a71be89e3a5 100644--- a/locales/bg-BG/setting.json+++ b/locales/bg-BG/setting.json@@ -798,9 +798,6 @@"systemAgent.promptRewrite.label": "Модел","systemAgent.promptRewrite.modelDesc": "Определете модела, използван за пренаписване на подсказки","systemAgent.promptRewrite.title": "Агент за пренаписване на подсказки",- "systemAgent.queryRewrite.label": "Модел",- "systemAgent.queryRewrite.modelDesc": "Посочете модел за оптимизиране на потребителски заявки",- "systemAgent.queryRewrite.title": "Агент за пренаписване на заявки в библиотеката","systemAgent.thread.label": "Модел","systemAgent.thread.modelDesc": "Модел, използван за автоматично преименуване на подтеми","systemAgent.thread.title": "Агент за автоматично именуване на подтеми",diff --git a/locales/de-DE/setting.json b/locales/de-DE/setting.jsonindex f3b2b5ac5f4..288c859fddc 100644--- a/locales/de-DE/setting.json+++ b/locales/de-DE/setting.json@@ -798,9 +798,6 @@"systemAgent.promptRewrite.label": "Modell","systemAgent.promptRewrite.modelDesc": "Geben Sie das Modell an, das zum Umschreiben von Prompts verwendet wird","systemAgent.promptRewrite.title": "Prompt-Umschreibagent",- "systemAgent.queryRewrite.label": "Modell",- "systemAgent.queryRewrite.modelDesc": "Modell zur Optimierung von Benutzeranfragen",- "systemAgent.queryRewrite.title": "Agent zur Umschreibung von Bibliotheksanfragen","systemAgent.thread.label": "Modell","systemAgent.thread.modelDesc": "Modell zur automatischen Umbenennung von Unterthemen","systemAgent.thread.title": "Agent zur automatischen Unterthemenbenennung",diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex 7e52e665425..e618d58c4fa 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -797,9 +797,6 @@"systemAgent.promptRewrite.label": "Model","systemAgent.promptRewrite.modelDesc": "Specify the model used to rewrite prompts","systemAgent.promptRewrite.title": "Prompt Rewrite Agent",- "systemAgent.queryRewrite.label": "Model",- "systemAgent.queryRewrite.modelDesc": "Specify the model used to optimize user inquiries",- "systemAgent.queryRewrite.title": "Library query rewrite Agent","systemAgent.thread.label": "Model","systemAgent.thread.modelDesc": "The model designated for automatic renaming of subtopics","systemAgent.thread.title": "Subtopic Auto-Naming Agent",diff --git a/locales/es-ES/setting.json b/locales/es-ES/setting.jsonindex 4b1ec492e16..8230b736ce0 100644--- a/locales/es-ES/setting.json+++ b/locales/es-ES/setting.json@@ -798,9 +798,6 @@"systemAgent.promptRewrite.label": "Modelo","systemAgent.promptRewrite.modelDesc": "Especifica el modelo utilizado para reescribir indicaciones","systemAgent.promptRewrite.title": "Agente de Reescritura de Indicaciones",- "systemAgent.queryRewrite.label": "Modelo",- "systemAgent.queryRewrite.modelDesc": "Especifica el modelo usado para optimizar las consultas del usuario",- "systemAgent.queryRewrite.title": "Agente de Reescritura de Consultas","systemAgent.thread.label": "Modelo","systemAgent.thread.modelDesc": "Modelo designado para renombrar automáticamente subtemas","systemAgent.thread.title": "Agente de Renombrado Automático de Subtemas",diff --git a/locales/fa-IR/setting.json b/locales/fa-IR/setting.jsonindex 3a297dbdaa5..4e2a0ce2735 100644--- a/locales/fa-IR/setting.json+++ b/locales/fa-IR/setting.json@@ -798,9 +798,6 @@"systemAgent.promptRewrite.label": "مدل","systemAgent.promptRewrite.modelDesc": "مدلی را که برای بازنویسی پرامپت استفاده میشود مشخص کنید","systemAgent.promptRewrite.title": "عامل بازنویسی پرامپت",- "systemAgent.queryRewrite.label": "مدل",- "systemAgent.queryRewrite.modelDesc": "مدلی که برای بهینهسازی پرسشهای کاربران استفاده میشود",- "systemAgent.queryRewrite.title": "عامل بازنویسی پرسش کتابخانه","systemAgent.thread.label": "مدل","systemAgent.thread.modelDesc": "مدلی که برای نامگذاری خودکار زیرموضوعات استفاده میشود","systemAgent.thread.title": "عامل نامگذاری خودکار زیرموضوع",diff --git a/locales/fr-FR/setting.json b/locales/fr-FR/setting.jsonindex f7ad27d498b..7d49004e7e7 100644--- a/locales/fr-FR/setting.json+++ b/locales/fr-FR/setting.json@@ -798,9 +798,6 @@"systemAgent.promptRewrite.label": "Modèle","systemAgent.promptRewrite.modelDesc": "Spécifiez le modèle utilisé pour réécrire les invites","systemAgent.promptRewrite.title": "Agent de Réécriture d’Invites",- "systemAgent.queryRewrite.label": "Modèle",- "systemAgent.queryRewrite.modelDesc": "Modèle utilisé pour optimiser les requêtes des utilisateurs",- "systemAgent.queryRewrite.title": "Agent de réécriture de requêtes","systemAgent.thread.label": "Modèle","systemAgent.thread.modelDesc": "Modèle utilisé pour renommer automatiquement les sous-sujets","systemAgent.thread.title": "Agent de renommage de sous-sujets",diff --git a/locales/it-IT/setting.json b/locales/it-IT/setting.jsonindex 5c9ee17462e..d4e13954388 100644--- a/locales/it-IT/setting.json+++ b/locales/it-IT/setting.json@@ -798,9 +798,6 @@"systemAgent.promptRewrite.label": "Modello","systemAgent.promptRewrite.modelDesc": "Specifica il modello utilizzato per riscrivere i prompt","systemAgent.promptRewrite.title": "Agente di Riscrittura Prompt",- "systemAgent.queryRewrite.label": "Modello",- "systemAgent.queryRewrite.modelDesc": "Specifica il modello utilizzato per ottimizzare le richieste degli utenti",- "systemAgent.queryRewrite.title": "Agente Riscrittura Richieste Libreria","systemAgent.thread.label": "Modello","systemAgent.thread.modelDesc": "Modello designato per la rinominazione automatica dei sottotemi","systemAgent.thread.title": "Agente Rinomina Automatica Sottotemi",diff --git a/locales/ja-JP/setting.json b/locales/ja-JP/setting.jsonindex b532f1eb555..15b515ae261 100644--- a/locales/ja-JP/setting.json+++ b/locales/ja-JP/setting.json@@ -798,9 +798,6 @@"systemAgent.promptRewrite.label": "モデル","systemAgent.promptRewrite.modelDesc": "プロンプトを書き換える際に使用するモデルを指定します","systemAgent.promptRewrite.title": "プロンプトリライトエージェント",- "systemAgent.queryRewrite.label": "モデル",- "systemAgent.queryRewrite.modelDesc": "ユーザーの質問を最適化するために指定されたモデル",- "systemAgent.queryRewrite.title": "リソースライブラリ質問リライトアシスタント","systemAgent.thread.label": "モデル","systemAgent.thread.modelDesc": "サブトピックの自動命名に使用されるモデルを指定します","systemAgent.thread.title": "サブトピック自動命名アシスタント",diff --git a/locales/ko-KR/setting.json b/locales/ko-KR/setting.jsonindex 3f448352d47..f7651228839 100644--- a/locales/ko-KR/setting.json+++ b/locales/ko-KR/setting.json@@ -798,9 +798,6 @@"systemAgent.promptRewrite.label": "모델","systemAgent.promptRewrite.modelDesc": "프롬프트 재작성에 사용할 모델을 지정합니다","systemAgent.promptRewrite.title": "프롬프트 재작성 에이전트",- "systemAgent.queryRewrite.label": "모델",- "systemAgent.queryRewrite.modelDesc": "사용자의 질문을 최적화하는 데 사용되는 모델 지정",- "systemAgent.queryRewrite.title": "자료실 질문 재작성 도우미","systemAgent.thread.label": "모델","systemAgent.thread.modelDesc": "하위 주제 자동 이름 변경에 사용되는 모델 지정","systemAgent.thread.title": "하위 주제 자동 명명 도우미",diff --git a/locales/nl-NL/setting.json b/locales/nl-NL/setting.jsonindex e876e7cf186..3ea84638129 100644--- a/locales/nl-NL/setting.json+++ b/locales/nl-NL/setting.json@@ -798,9 +798,6 @@"systemAgent.promptRewrite.label": "Model","systemAgent.promptRewrite.modelDesc": "Geef het model op dat wordt gebruikt om prompts te herschrijven","systemAgent.promptRewrite.title": "Prompt Rewrite Agent",- "systemAgent.queryRewrite.label": "Model",- "systemAgent.queryRewrite.modelDesc": "Specificeer het model dat wordt gebruikt om gebruikersvragen te optimaliseren",- "systemAgent.queryRewrite.title": "Bibliotheekvraag Herschrijfagent","systemAgent.thread.label": "Model","systemAgent.thread.modelDesc": "Model dat wordt gebruikt voor automatische hernoeming van subonderwerpen","systemAgent.thread.title": "Subonderwerp Auto-Naamgevingsagent",diff --git a/locales/pl-PL/setting.json b/locales/pl-PL/setting.jsonindex fb2b090fbeb..e97da31b24a 100644--- a/locales/pl-PL/setting.json+++ b/locales/pl-PL/setting.json@@ -798,9 +798,6 @@"systemAgent.promptRewrite.label": "Model","systemAgent.promptRewrite.modelDesc": "Określ model używany do przepisywania promptów","systemAgent.promptRewrite.title": "Agent Przepisywania Promptów",- "systemAgent.queryRewrite.label": "Model",- "systemAgent.queryRewrite.modelDesc": "Określ model używany do optymalizacji zapytań użytkownika",- "systemAgent.queryRewrite.title": "Agent przekształcania zapytań bibliotecznych","systemAgent.thread.label": "Model","systemAgent.thread.modelDesc": "Model przeznaczony do automatycznego nadawania nazw podtematom","systemAgent.thread.title": "Agent automatycznego nazewnictwa podtematów",diff --git a/locales/pt-BR/setting.json b/locales/pt-BR/setting.jsonindex 2d322c21e3e..08eb4af9a2f 100644--- a/locales/pt-BR/setting.json+++ b/locales/pt-BR/setting.json@@ -798,9 +798,6 @@"systemAgent.promptRewrite.label": "Modelo","systemAgent.promptRewrite.modelDesc": "Especifique o modelo usado para reescrever prompts","systemAgent.promptRewrite.title": "Agente de Reescrita de Prompt",- "systemAgent.queryRewrite.label": "Modelo",- "systemAgent.queryRewrite.modelDesc": "Especifique o modelo usado para otimizar as perguntas dos usuários",- "systemAgent.queryRewrite.title": "Agente de Reescrita de Consultas da Biblioteca","systemAgent.thread.label": "Modelo","systemAgent.thread.modelDesc": "Modelo designado para renomeação automática de subtópicos","systemAgent.thread.title": "Agente de Nomeação Automática de Subtópicos",diff --git a/locales/ru-RU/setting.json b/locales/ru-RU/setting.jsonindex 969025596f4..e6b7a474ae2 100644--- a/locales/ru-RU/setting.json+++ b/locales/ru-RU/setting.json@@ -798,9 +798,6 @@"systemAgent.promptRewrite.label": "Модель","systemAgent.promptRewrite.modelDesc": "Укажите модель, используемую для переформулирования запросов","systemAgent.promptRewrite.title": "Агент перезаписи запросов",- "systemAgent.queryRewrite.label": "Модель",- "systemAgent.queryRewrite.modelDesc": "Укажите модель для оптимизации пользовательских запросов",- "systemAgent.queryRewrite.title": "Агент переформулировки запросов","systemAgent.thread.label": "Модель","systemAgent.thread.modelDesc": "Модель, используемая для автоматического наименования подтем","systemAgent.thread.title": "Агент автонаименования подтем",diff --git a/locales/tr-TR/setting.json b/locales/tr-TR/setting.jsonindex 9f887c29095..a40ca1fee56 100644--- a/locales/tr-TR/setting.json+++ b/locales/tr-TR/setting.json@@ -798,9 +798,6 @@"systemAgent.promptRewrite.label": "Model","systemAgent.promptRewrite.modelDesc": "İstemleri yeniden yazmak için kullanılan modeli belirtin","systemAgent.promptRewrite.title": "İstem Yenileme Aracısı",- "systemAgent.queryRewrite.label": "Model",- "systemAgent.queryRewrite.modelDesc": "Kullanıcı sorgularını optimize etmek için kullanılacak modeli belirtin",- "systemAgent.queryRewrite.title": "Kütüphane Sorgusu Yeniden Yazma Temsilcisi","systemAgent.thread.label": "Model","systemAgent.thread.modelDesc": "Alt konuların otomatik yeniden adlandırılması için belirlenen model","systemAgent.thread.title": "Alt Konu Otomatik Adlandırma Temsilcisi",diff --git a/locales/vi-VN/setting.json b/locales/vi-VN/setting.jsonindex 305ea8bf505..d4621af3f03 100644--- a/locales/vi-VN/setting.json+++ b/locales/vi-VN/setting.json@@ -798,9 +798,6 @@"systemAgent.promptRewrite.label": "Mô hình","systemAgent.promptRewrite.modelDesc": "Chỉ định mô hình được sử dụng để viết lại prompt","systemAgent.promptRewrite.title": "Tác nhân Viết lại Prompt",- "systemAgent.queryRewrite.label": "Mô Hình",- "systemAgent.queryRewrite.modelDesc": "Chỉ định mô hình dùng để tối ưu hóa câu hỏi người dùng",- "systemAgent.queryRewrite.title": "Tác Nhân Viết Lại Truy Vấn Thư Viện","systemAgent.thread.label": "Mô Hình","systemAgent.thread.modelDesc": "Mô hình được chỉ định để tự động đặt tên cho các chủ đề phụ","systemAgent.thread.title": "Tác Nhân Đặt Tên Chủ Đề Phụ Tự Động",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex b4b5d757063..c61d2a28d9d 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -804,9 +804,6 @@"systemAgent.promptRewrite.label": "模型","systemAgent.promptRewrite.modelDesc": "指定用于重写提示词的模型","systemAgent.promptRewrite.title": "提示词重写助理",- "systemAgent.queryRewrite.label": "模型",- "systemAgent.queryRewrite.modelDesc": "指定用于优化用户提问的模型",- "systemAgent.queryRewrite.title": "资源库提问重写助理","systemAgent.thread.label": "模型","systemAgent.thread.modelDesc": "指定用于子话题自动重命名的模型","systemAgent.thread.title": "子话题自动命名助理",diff --git a/locales/zh-TW/setting.json b/locales/zh-TW/setting.jsonindex 04533f78c3a..e7fa1f140f3 100644--- a/locales/zh-TW/setting.json+++ b/locales/zh-TW/setting.json@@ -798,9 +798,6 @@"systemAgent.promptRewrite.label": "模型","systemAgent.promptRewrite.modelDesc": "指定用於重寫提示詞的模型","systemAgent.promptRewrite.title": "提示詞重寫代理",- "systemAgent.queryRewrite.label": "模型",- "systemAgent.queryRewrite.modelDesc": "指定用於優化用戶提問的模型",- "systemAgent.queryRewrite.title": "資源庫提問重寫助手","systemAgent.thread.label": "模型","systemAgent.thread.modelDesc": "指定用於子主題自動重命名的模型","systemAgent.thread.title": "子主題自動命名助手",diff --git a/packages/const/src/settings/systemAgent.ts b/packages/const/src/settings/systemAgent.tsindex 3e5cb3fa2df..f37dea07a28 100644--- a/packages/const/src/settings/systemAgent.ts+++ b/packages/const/src/settings/systemAgent.ts@@ -1,7 +1,6 @@import { DEFAULT_MINI_PROVIDER, DEFAULT_PROVIDER } from '@lobechat/business-const';import type {PromptRewriteSystemAgent,- QueryRewriteSystemAgent,SystemAgentItem,UserSystemAgentConfig,} from '@lobechat/types';@@ -18,12 +17,6 @@ export const DEFAULT_MINI_SYSTEM_AGENT_ITEM: SystemAgentItem = {provider: DEFAULT_MINI_PROVIDER,};-export const DEFAULT_QUERY_REWRITE_SYSTEM_AGENT_ITEM: QueryRewriteSystemAgent = {- enabled: true,- model: DEFAULT_MINI_SYSTEM_AGENT_ITEM.model,- provider: DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,-};-export const DEFAULT_PROMPT_REWRITE_SYSTEM_AGENT_ITEM: PromptRewriteSystemAgent = {enabled: true,model: DEFAULT_MINI_SYSTEM_AGENT_ITEM.model,@@ -42,7 +35,6 @@ export const DEFAULT_SYSTEM_AGENT_CONFIG: UserSystemAgentConfig = {historyCompress: DEFAULT_SYSTEM_AGENT_ITEM,inputCompletion: DEFAULT_INPUT_COMPLETION_SYSTEM_AGENT_ITEM,promptRewrite: DEFAULT_PROMPT_REWRITE_SYSTEM_AGENT_ITEM,- queryRewrite: DEFAULT_QUERY_REWRITE_SYSTEM_AGENT_ITEM,thread: DEFAULT_SYSTEM_AGENT_ITEM,topic: DEFAULT_MINI_SYSTEM_AGENT_ITEM,translation: DEFAULT_MINI_SYSTEM_AGENT_ITEM,diff --git a/packages/prompts/src/chains/__tests__/rewriteQuery.test.ts b/packages/prompts/src/chains/__tests__/rewriteQuery.test.tsdeleted file mode 100644index 56a72681edf..00000000000--- a/packages/prompts/src/chains/__tests__/rewriteQuery.test.ts+++ /dev/null@@ -1,87 +0,0 @@-import { describe, expect, it } from 'vitest';--// Mock DEFAULT_REWRITE_QUERY-import { chainRewriteQuery, DEFAULT_REWRITE_QUERY } from '../rewriteQuery';--describe('chainRewriteQuery', () => {- it('should generate correct chat payload with default instruction', () => {- const query = 'What about the weather?';- const context = ['Previous message 1', 'Previous message 2'];-- const result = chainRewriteQuery(query, context);-- expect(result.messages).toHaveLength(2);- expect(result.messages![0].role).toBe('system');- expect(result.messages![1].role).toBe('user');- expect(result.messages![0].content).toContain(DEFAULT_REWRITE_QUERY);- expect(result.messages![1].content).toContain(query);- });-- it('should include chat history in system message', () => {- const query = 'Follow up question';- const context = ['User: Hello', 'Assistant: Hi there'];-- const result = chainRewriteQuery(query, context);-- expect(result.messages![0].content).toContain('<chatHistory>');- expect(result.messages![0].content).toContain('User: Hello');- expect(result.messages![0].content).toContain('Assistant: Hi there');- expect(result.messages![0].content).toContain('</chatHistory>');- });-- it('should use custom instruction when provided', () => {- const query = 'Test query';- const context = ['Context'];- const customInstruction = 'Custom rewrite instruction';-- const result = chainRewriteQuery(query, context, customInstruction);-- expect(result.messages![0].content).toContain(customInstruction);- expect(result.messages![0].content).not.toContain(DEFAULT_REWRITE_QUERY);- });-- it('should format user message correctly', () => {- const query = 'What is the status?';- const context = ['Previous context'];-- const result = chainRewriteQuery(query, context);-- expect(result.messages![1].content).toBe(`Follow Up Input: ${query}, it's standalone query:`);- });-- it('should handle empty context array', () => {- const query = 'Empty context query';- const context: string[] = [];-- const result = chainRewriteQuery(query, context);-- expect(result.messages![0].content).toContain('<chatHistory>\n\n</chatHistory>');- });-- it('should handle single context item', () => {- const query = 'Single context query';- const context = ['Only one message'];-- const result = chainRewriteQuery(query, context);-- expect(result.messages![0].content).toContain('Only one message');- });-- it('should join multiple context items with newlines', () => {- const query = 'Multi context query';- const context = ['Message 1', 'Message 2', 'Message 3'];-- const result = chainRewriteQuery(query, context);-- expect(result.messages![0].content).toContain('Message 1\nMessage 2\nMessage 3');- });-- it('should handle special characters in query', () => {- const query = 'Query with special chars: @#$%^&*()';- const context = ['Context'];-- const result = chainRewriteQuery(query, context);-- expect(result.messages![1].content).toContain(query);- });-});diff --git a/packages/prompts/src/chains/index.ts b/packages/prompts/src/chains/index.tsindex 78ea7c3ad8b..ec2380022d0 100644--- a/packages/prompts/src/chains/index.ts+++ b/packages/prompts/src/chains/index.ts@@ -5,7 +5,6 @@ export * from './inputCompletion';export * from './langDetect';export * from './pickEmoji';export * from './rewriteGenerationPrompt';-export * from './rewriteQuery';export * from './summaryAgentName';export * from './summaryDescription';export * from './summaryGenerationTitle';diff --git a/packages/prompts/src/chains/rewriteQuery.ts b/packages/prompts/src/chains/rewriteQuery.tsdeleted file mode 100644index 35d1371198d..00000000000--- a/packages/prompts/src/chains/rewriteQuery.ts+++ /dev/null@@ -1,25 +0,0 @@-import type { ChatStreamPayload } from '@lobechat/types';--export const DEFAULT_REWRITE_QUERY =- 'Given the following conversation and a follow-up question, rephrase the follow up question to be a standalone question, in its original language. Keep as much details as possible from previous messages. Keep entity names and all.';--export const chainRewriteQuery = (- query: string,- context: string[],- instruction: string = DEFAULT_REWRITE_QUERY,-): Partial<ChatStreamPayload> => ({- messages: [- {- content: `${instruction}-<chatHistory>-${context.join('\n')}-</chatHistory>-`,- role: 'system',- },- {- content: `Follow Up Input: ${query}, it's standalone query:`,- role: 'user',- },- ],-});diff --git a/packages/prompts/src/index.test.ts b/packages/prompts/src/index.test.tsindex 92bd9cbe5d0..80f43ef2506 100644--- a/packages/prompts/src/index.test.ts+++ b/packages/prompts/src/index.test.ts@@ -24,7 +24,6 @@ describe('Main Index Export', () => {'chainAnswerWithContext','chainLangDetect','chainPickEmoji',- 'chainRewriteQuery','chainSummaryAgentName','chainSummaryDescription','chainSummaryGenerationTitle',diff --git a/packages/types/src/user/settings/systemAgent.ts b/packages/types/src/user/settings/systemAgent.tsindex 174069b9eff..2e7b85d5e42 100644--- a/packages/types/src/user/settings/systemAgent.ts+++ b/packages/types/src/user/settings/systemAgent.ts@@ -5,10 +5,6 @@ export interface SystemAgentItem {provider: string;}-export interface QueryRewriteSystemAgent extends Omit<SystemAgentItem, 'enabled'> {- enabled: boolean;-}-export interface PromptRewriteSystemAgent extends Omit<SystemAgentItem, 'enabled'> {enabled: boolean;}@@ -19,7 +15,6 @@ export interface UserSystemAgentConfig {historyCompress: SystemAgentItem;inputCompletion: SystemAgentItem;promptRewrite: PromptRewriteSystemAgent;- queryRewrite: QueryRewriteSystemAgent;thread: SystemAgentItem;topic: SystemAgentItem;translation: SystemAgentItem;diff --git a/src/features/Conversation/ChatList/components/VirtualizedList.tsx b/src/features/Conversation/ChatList/components/VirtualizedList.tsxindex 7b44d35e82d..e863ceae7ef 100644--- a/src/features/Conversation/ChatList/components/VirtualizedList.tsx+++ b/src/features/Conversation/ChatList/components/VirtualizedList.tsx@@ -1,12 +1,14 @@'use client';import isEqual from 'fast-deep-equal';-import { type ReactElement, type ReactNode } from 'react';+import type { ReactElement, ReactNode } from 'react';import { memo, useCallback, useEffect, useMemo, useRef } from 'react';-import { type VListHandle } from 'virtua';+import type { VListHandle } from 'virtua';import { VList } from 'virtua';import { useShallow } from 'zustand/react/shallow';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';+import WideScreenContainer from '../../../WideScreenContainer';import {dataSelectors,@@ -19,6 +21,7 @@ import {useConversationScroll,} from '../hooks/useConversationScroll';import { useSelectionMessageIds } from '../hooks/useSelectionMessageIds';+import { useTopicScrollPersist } from '../hooks/useTopicScrollPersist';import AutoScroll from './AutoScroll';import { AT_BOTTOM_THRESHOLD } from './AutoScroll/const';import DebugInspector, { OPEN_DEV_INSPECTOR } from './AutoScroll/DebugInspector';@@ -37,9 +40,18 @@ interface VirtualizedListProps {*/const VirtualizedList = memo<VirtualizedListProps>(({ dataSource, itemContent }) => {const virtuaRef = useRef<VListHandle>(null);- const didInitialScrollRef = useRef(false);const scrollEndTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ // Per-topic scroll restoration. Provider does not remount on topic switch,+ // so we key the scroll snapshot by the message-map key derived from+ // ConversationStore's `context`.+ const contextKey = useConversationStore((s) => messageMapKey(s.context));+ const { recordScroll } = useTopicScrollPersist({+ contextKey,+ dataSourceLength: dataSource.length,+ virtuaRef,+ });+// Second-to-last message is the user turn when sending (user + assistant pair)const isSecondLastMessageFromUser = useConversationStore(dataSelectors.isSecondLastMessageFromUser,@@ -103,6 +115,10 @@ const VirtualizedList = memo<VirtualizedListProps>(({ dataSource, itemContent })const isAtBottom = checkAtBottom();setScrollState({ atBottom: isAtBottom });+ if (ref) {+ recordScroll(ref.scrollOffset, isAtBottom);+ }+// Clear existing timerif (scrollEndTimerRef.current) {clearTimeout(scrollEndTimerRef.current);@@ -112,7 +128,7 @@ const VirtualizedList = memo<VirtualizedListProps>(({ dataSource, itemContent })scrollEndTimerRef.current = setTimeout(() => {setScrollState({ isScrolling: false });}, 150);- }, [activeIndex, checkAtBottom, onScrollOffset, setActiveIndex, setScrollState]);+ }, [activeIndex, checkAtBottom, onScrollOffset, recordScroll, setActiveIndex, setScrollState]);const handleScrollEnd = useCallback(() => {setScrollState({ isScrolling: false });@@ -183,14 +199,6 @@ const VirtualizedList = memo<VirtualizedListProps>(({ dataSource, itemContent })return [...merged].sort((a, b) => a - b);}, [dataSource, streamingIndices, selectionMessageIds]);- // Scroll to bottom on initial render- useEffect(() => {- if (didInitialScrollRef.current || !virtuaRef.current || dataSource.length === 0) return;-- virtuaRef.current.scrollToIndex(dataSource.length - 1, { align: 'end' });- didInitialScrollRef.current = true;- }, [dataSource.length]);-const atBottom = useConversationStore(virtuaListSelectors.atBottom);const scrollToBottom = useConversationStore((s) => s.scrollToBottom);diff --git a/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.ts b/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.tsnew file mode 100644index 00000000000..b86182086a5--- /dev/null+++ b/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.ts@@ -0,0 +1,139 @@+import type { RefObject } from 'react';+import { useCallback, useEffect, useRef } from 'react';+import type { VListHandle } from 'virtua';++import {+ isDraftPromotionKey,+ loadScrollSnapshot,+ migrateScrollSnapshot,+ pruneScrollSnapshots,+ saveScrollSnapshot,+} from '../utils/scrollSnapshotStore';++const FLUSH_THROTTLE_MS = 200;++interface PendingWrite {+ atBottom: boolean;+ key: string;+ offset: number;+}++interface UseTopicScrollPersistOptions {+ contextKey: string;+ dataSourceLength: number;+ virtuaRef: RefObject<VListHandle | null>;+}++/**+ * Persists per-topic chat scroll position to localStorage.+ *+ * The Provider does not remount on topic switch — the same VirtualizedList+ * instance handles every topic, so we react to `contextKey` changes ourselves+ * to flush the previous topic and restore the next.+ */+export const useTopicScrollPersist = ({+ contextKey,+ dataSourceLength,+ virtuaRef,+}: UseTopicScrollPersistOptions) => {+ const pendingWriteRef = useRef<PendingWrite | null>(null);+ const flushTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ // Initial mount counts as a "key change" so the first restore attempt fires.+ const needsRestoreRef = useRef(true);+ const prevContextKeyRef = useRef(contextKey);+ const dataSourceLengthRef = useRef(dataSourceLength);+ dataSourceLengthRef.current = dataSourceLength;++ const flushNow = useCallback(() => {+ if (flushTimerRef.current) {+ clearTimeout(flushTimerRef.current);+ flushTimerRef.current = null;+ }+ const pending = pendingWriteRef.current;+ if (!pending) return;+ saveScrollSnapshot(pending.key, {+ atBottom: pending.atBottom,+ offset: pending.offset,+ savedAt: Date.now(),+ });+ pendingWriteRef.current = null;+ }, []);++ const recordScroll = useCallback(+ (offset: number, atBottom: boolean) => {+ pendingWriteRef.current = { atBottom, key: contextKey, offset };+ if (flushTimerRef.current) return;+ flushTimerRef.current = setTimeout(() => {+ flushTimerRef.current = null;+ flushNow();+ }, FLUSH_THROTTLE_MS);+ },+ [contextKey, flushNow],+ );++ // On contextKey change: flush any pending writes against the previous key,+ // then either preserve scroll (draft → real-id promotion of the same+ // conversation) or arm a restore (real topic switch).+ useEffect(() => {+ const prevKey = prevContextKeyRef.current;+ if (prevKey === contextKey) return;+ prevContextKeyRef.current = contextKey;++ flushNow();++ if (isDraftPromotionKey(prevKey, contextKey)) {+ // `onTopicCreated` mutates context mid-stream: same conversation, new+ // key. Move the snapshot so future visits resolve the new key, and+ // skip the restore so we don't yank the user away from content they+ // were already reading.+ migrateScrollSnapshot(prevKey, contextKey);+ // If data hasn't rendered yet, leave the default first-mount restore+ // (scroll-to-bottom) in place — there's nothing to preserve.+ if (dataSourceLengthRef.current > 0) {+ needsRestoreRef.current = false;+ }+ return;+ }++ needsRestoreRef.current = true;+ }, [contextKey, flushNow]);++ // Restore (or fall back to scroll-to-bottom) once data is available for+ // the active contextKey. Re-runs on contextKey or data length change.+ useEffect(() => {+ if (!needsRestoreRef.current) return;+ if (!virtuaRef.current || dataSourceLength === 0) return;++ needsRestoreRef.current = false;++ const snapshot = loadScrollSnapshot(contextKey);++ if (snapshot && !snapshot.atBottom) {+ // virtua needs item sizes measured before scrollTo lands at the right+ // pixel — defer one frame so the just-mounted items have layout.+ requestAnimationFrame(() => {+ virtuaRef.current?.scrollTo(snapshot.offset);+ });+ return;+ }++ virtuaRef.current.scrollToIndex(dataSourceLength - 1, { align: 'end' });+ }, [contextKey, dataSourceLength, virtuaRef]);++ // One-shot housekeeping: drop expired entries and enforce the cap.+ useEffect(() => {+ pruneScrollSnapshots();+ }, []);++ // Flush on unmount and on tab close so the most recent offset survives.+ useEffect(() => {+ const handleBeforeUnload = () => flushNow();+ window.addEventListener('beforeunload', handleBeforeUnload);+ return () => {+ window.removeEventListener('beforeunload', handleBeforeUnload);+ flushNow();+ };+ }, [flushNow]);++ return { recordScroll };+};diff --git a/src/features/Conversation/ChatList/utils/scrollSnapshotStore.test.ts b/src/features/Conversation/ChatList/utils/scrollSnapshotStore.test.tsnew file mode 100644index 00000000000..8444f60ebcf--- /dev/null+++ b/src/features/Conversation/ChatList/utils/scrollSnapshotStore.test.ts@@ -0,0 +1,252 @@+/**+ * @vitest-environment happy-dom+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ isDraftPromotionKey,+ loadScrollSnapshot,+ migrateScrollSnapshot,+ pruneScrollSnapshots,+ saveScrollSnapshot,+ SCROLL_SNAPSHOT_KEY_PREFIX,+ SCROLL_SNAPSHOT_MAX_AGE_MS,+ SCROLL_SNAPSHOT_MAX_ENTRIES,+} from './scrollSnapshotStore';++describe('scrollSnapshotStore', () => {+ beforeEach(() => {+ localStorage.clear();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ describe('saveScrollSnapshot / loadScrollSnapshot', () => {+ it('persists and reads back the latest snapshot for a context key', () => {+ const savedAt = Date.now();+ saveScrollSnapshot('main_agt_1_tpc_a', { atBottom: false, offset: 1234, savedAt });++ expect(loadScrollSnapshot('main_agt_1_tpc_a')).toEqual({+ atBottom: false,+ offset: 1234,+ savedAt,+ });+ });++ it('namespaces entries by context key so different topics do not collide', () => {+ const savedAt = Date.now();+ saveScrollSnapshot('main_agt_1_tpc_a', { atBottom: false, offset: 100, savedAt });+ saveScrollSnapshot('main_agt_1_tpc_b', { atBottom: true, offset: 0, savedAt });++ expect(loadScrollSnapshot('main_agt_1_tpc_a')?.offset).toBe(100);+ expect(loadScrollSnapshot('main_agt_1_tpc_b')?.atBottom).toBe(true);+ });++ it('returns null when key is missing', () => {+ expect(loadScrollSnapshot('missing')).toBeNull();+ });++ it('returns null and removes corrupt entries on read', () => {+ const storageKey = `${SCROLL_SNAPSHOT_KEY_PREFIX}:bad`;+ localStorage.setItem(storageKey, 'not-json');++ expect(loadScrollSnapshot('bad')).toBeNull();+ });++ it('expires snapshots older than the max age', () => {+ const fixedNow = 1_000_000_000_000;+ vi.useFakeTimers();+ vi.setSystemTime(fixedNow);++ saveScrollSnapshot('stale', {+ atBottom: false,+ offset: 1,+ savedAt: fixedNow - SCROLL_SNAPSHOT_MAX_AGE_MS - 1,+ });++ expect(loadScrollSnapshot('stale')).toBeNull();+ expect(localStorage.getItem(`${SCROLL_SNAPSHOT_KEY_PREFIX}:stale`)).toBeNull();+ });+ });++ describe('pruneScrollSnapshots', () => {+ it('drops expired entries', () => {+ const fixedNow = 1_000_000_000_000;+ vi.useFakeTimers();+ vi.setSystemTime(fixedNow);++ saveScrollSnapshot('fresh', { atBottom: false, offset: 1, savedAt: fixedNow });+ saveScrollSnapshot('expired', {+ atBottom: false,+ offset: 1,+ savedAt: fixedNow - SCROLL_SNAPSHOT_MAX_AGE_MS - 1,+ });++ const result = pruneScrollSnapshots();++ expect(result.evictedExpired).toBe(1);+ expect(localStorage.getItem(`${SCROLL_SNAPSHOT_KEY_PREFIX}:fresh`)).not.toBeNull();+ expect(localStorage.getItem(`${SCROLL_SNAPSHOT_KEY_PREFIX}:expired`)).toBeNull();+ });++ it('removes corrupt entries', () => {+ const corruptKey = `${SCROLL_SNAPSHOT_KEY_PREFIX}:corrupt`;+ localStorage.setItem(corruptKey, '{garbage');++ pruneScrollSnapshots();++ expect(localStorage.getItem(corruptKey)).toBeNull();+ });++ it('evicts oldest entries when over the cap, keeping at most MAX_ENTRIES', () => {+ const fixedNow = Date.now();+ const overflow = 3;+ const total = SCROLL_SNAPSHOT_MAX_ENTRIES + overflow;++ for (let i = 0; i < total; i++) {+ saveScrollSnapshot(`topic_${i}`, {+ atBottom: false,+ offset: i,+ savedAt: fixedNow + i,+ });+ }++ const result = pruneScrollSnapshots();++ expect(result.evictedOverflow).toBe(overflow);+ expect(result.remaining).toBe(SCROLL_SNAPSHOT_MAX_ENTRIES);++ // Oldest entries (lowest savedAt) should be evicted.+ for (let i = 0; i < overflow; i++) {+ expect(localStorage.getItem(`${SCROLL_SNAPSHOT_KEY_PREFIX}:topic_${i}`)).toBeNull();+ }+ // The newest entry must survive.+ expect(+ localStorage.getItem(`${SCROLL_SNAPSHOT_KEY_PREFIX}:topic_${total - 1}`),+ ).not.toBeNull();+ });++ it('ignores unrelated localStorage keys', () => {+ localStorage.setItem('LOBE_PREFERENCE', '{"theme":"dark"}');+ saveScrollSnapshot('topic', { atBottom: false, offset: 0, savedAt: Date.now() });++ pruneScrollSnapshots();++ expect(localStorage.getItem('LOBE_PREFERENCE')).toBe('{"theme":"dark"}');+ });+ });++ describe('isDraftPromotionKey', () => {+ it('matches main scope draft promotion: _new → _<topicId>', () => {+ expect(isDraftPromotionKey('main_agt_xxx_new', 'main_agt_xxx_tpc_yyy')).toBe(true);+ });++ it('matches thread scope draft promotion: ..._new → ..._thd_<id>', () => {+ expect(+ isDraftPromotionKey('thread_agt_xxx_tpc_yyy_new', 'thread_agt_xxx_tpc_yyy_thd_zzz'),+ ).toBe(true);+ });++ it('matches group scope draft promotion', () => {+ expect(isDraftPromotionKey('group_grp_xxx_new', 'group_grp_xxx_tpc_yyy')).toBe(true);+ });++ it('rejects unrelated keys with a coincidentally similar prefix', () => {+ // `xxx_` boundary check: `xxxx` must NOT match `xxx`.+ expect(isDraftPromotionKey('main_agt_xxx_new', 'main_agt_xxxx_tpc_yyy')).toBe(false);+ });++ it('rejects when previous key is not a draft', () => {+ expect(isDraftPromotionKey('main_agt_xxx_tpc_aaa', 'main_agt_xxx_tpc_bbb')).toBe(false);+ });++ it('rejects when keys are identical', () => {+ expect(isDraftPromotionKey('main_agt_xxx_new', 'main_agt_xxx_new')).toBe(false);+ });++ it('rejects switching between two different drafts', () => {+ expect(isDraftPromotionKey('main_agt_xxx_new', 'main_agt_yyy_new')).toBe(false);+ });+ });++ describe('migrateScrollSnapshot', () => {+ it('moves the snapshot from old key to new key and removes the old entry', () => {+ const savedAt = Date.now();+ saveScrollSnapshot('main_agt_xxx_new', { atBottom: false, offset: 4321, savedAt });++ migrateScrollSnapshot('main_agt_xxx_new', 'main_agt_xxx_tpc_yyy');++ expect(loadScrollSnapshot('main_agt_xxx_new')).toBeNull();+ expect(loadScrollSnapshot('main_agt_xxx_tpc_yyy')).toEqual({+ atBottom: false,+ offset: 4321,+ savedAt,+ });+ });++ it('is a no-op when there is no snapshot under the old key', () => {+ migrateScrollSnapshot('main_agt_xxx_new', 'main_agt_xxx_tpc_yyy');++ expect(loadScrollSnapshot('main_agt_xxx_tpc_yyy')).toBeNull();+ });++ it('is a no-op when old and new keys are equal', () => {+ const savedAt = Date.now();+ saveScrollSnapshot('main_agt_xxx_tpc_yyy', { atBottom: false, offset: 1, savedAt });++ migrateScrollSnapshot('main_agt_xxx_tpc_yyy', 'main_agt_xxx_tpc_yyy');++ expect(loadScrollSnapshot('main_agt_xxx_tpc_yyy')?.offset).toBe(1);+ });++ it('drops corrupt source entries instead of migrating them', () => {+ const corruptKey = `${SCROLL_SNAPSHOT_KEY_PREFIX}:main_agt_xxx_new`;+ localStorage.setItem(corruptKey, '{garbage');++ migrateScrollSnapshot('main_agt_xxx_new', 'main_agt_xxx_tpc_yyy');++ expect(localStorage.getItem(corruptKey)).toBeNull();+ expect(loadScrollSnapshot('main_agt_xxx_tpc_yyy')).toBeNull();+ });+ });++ describe('saveScrollSnapshot quota recovery', () => {+ it('prunes and retries once when setItem throws QuotaExceededError', () => {+ const fixedNow = 1_000_000_000_000;+ vi.useFakeTimers();+ vi.setSystemTime(fixedNow);++ // Pre-populate one expired entry that pruning can free.+ saveScrollSnapshot('expired', {+ atBottom: false,+ offset: 1,+ savedAt: fixedNow - SCROLL_SNAPSHOT_MAX_AGE_MS - 1,+ });++ // Spy on setItem: throw on first call (the save we're testing), succeed afterwards.+ let callCount = 0;+ const originalSetItem = Storage.prototype.setItem;+ const spy = vi.spyOn(Storage.prototype, 'setItem').mockImplementation(function (+ this: Storage,+ key,+ value,+ ) {+ callCount += 1;+ if (callCount === 1) {+ const err = new Error('QuotaExceeded');+ err.name = 'QuotaExceededError';+ throw err;+ }+ originalSetItem.call(this, key, value);+ });++ saveScrollSnapshot('next', { atBottom: false, offset: 9, savedAt: fixedNow });++ // After pruning the expired entry, the retry should have written `next`.+ spy.mockRestore();+ expect(loadScrollSnapshot('next')?.offset).toBe(9);+ });+ });+});diff --git a/src/features/Conversation/ChatList/utils/scrollSnapshotStore.ts b/src/features/Conversation/ChatList/utils/scrollSnapshotStore.tsnew file mode 100644index 00000000000..b4ea7bec455--- /dev/null+++ b/src/features/Conversation/ChatList/utils/scrollSnapshotStore.ts@@ -0,0 +1,216 @@+export const SCROLL_SNAPSHOT_KEY_PREFIX = 'LOBEHUB_SCROLL';+export const SCROLL_SNAPSHOT_MAX_ENTRIES = 500;+export const SCROLL_SNAPSHOT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;++export interface ScrollSnapshot {+ atBottom: boolean;+ offset: number;+ savedAt: number;+}++const buildStorageKey = (contextKey: string) => `${SCROLL_SNAPSHOT_KEY_PREFIX}:${contextKey}`;++const getStorage = (): Storage | null => {+ try {+ if (typeof window === 'undefined') return null;+ return window.localStorage;+ } catch {+ return null;+ }+};++const isValidSnapshot = (value: unknown): value is ScrollSnapshot => {+ if (!value || typeof value !== 'object') return false;+ const v = value as Record<string, unknown>;+ return (+ typeof v.offset === 'number' &&+ Number.isFinite(v.offset) &&+ typeof v.atBottom === 'boolean' &&+ typeof v.savedAt === 'number' &&+ Number.isFinite(v.savedAt)+ );+};++const collectPrefixedKeys = (storage: Storage): string[] => {+ const keys: string[] = [];+ for (let i = 0; i < storage.length; i++) {+ const key = storage.key(i);+ if (key && key.startsWith(`${SCROLL_SNAPSHOT_KEY_PREFIX}:`)) keys.push(key);+ }+ return keys;+};++export interface PruneResult {+ evictedExpired: number;+ evictedOverflow: number;+ remaining: number;+}++export const pruneScrollSnapshots = (storage: Storage | null = getStorage()): PruneResult => {+ const result: PruneResult = { evictedExpired: 0, evictedOverflow: 0, remaining: 0 };+ if (!storage) return result;++ const now = Date.now();+ const valid: { key: string; savedAt: number }[] = [];++ for (const key of collectPrefixedKeys(storage)) {+ try {+ const raw = storage.getItem(key);+ if (!raw) {+ storage.removeItem(key);+ continue;+ }+ const parsed = JSON.parse(raw) as unknown;+ if (!isValidSnapshot(parsed)) {+ storage.removeItem(key);+ continue;+ }+ if (now - parsed.savedAt > SCROLL_SNAPSHOT_MAX_AGE_MS) {+ storage.removeItem(key);+ result.evictedExpired += 1;+ continue;+ }+ valid.push({ key, savedAt: parsed.savedAt });+ } catch {+ try {+ storage.removeItem(key);+ } catch {+ // ignore+ }+ }+ }++ if (valid.length > SCROLL_SNAPSHOT_MAX_ENTRIES) {+ valid.sort((a, b) => a.savedAt - b.savedAt);+ const overflow = valid.length - SCROLL_SNAPSHOT_MAX_ENTRIES;+ for (let i = 0; i < overflow; i++) {+ try {+ storage.removeItem(valid[i].key);+ result.evictedOverflow += 1;+ } catch {+ // ignore+ }+ }+ }++ result.remaining = valid.length - result.evictedOverflow;+ return result;+};++export const loadScrollSnapshot = (contextKey: string): ScrollSnapshot | null => {+ const storage = getStorage();+ if (!storage) return null;++ const storageKey = buildStorageKey(contextKey);++ try {+ const raw = storage.getItem(storageKey);+ if (!raw) return null;++ const parsed = JSON.parse(raw) as unknown;+ if (!isValidSnapshot(parsed)) {+ storage.removeItem(storageKey);+ return null;+ }++ if (Date.now() - parsed.savedAt > SCROLL_SNAPSHOT_MAX_AGE_MS) {+ storage.removeItem(storageKey);+ return null;+ }++ return parsed;+ } catch {+ return null;+ }+};++export const saveScrollSnapshot = (contextKey: string, snapshot: ScrollSnapshot): void => {+ const storage = getStorage();+ if (!storage) return;++ const storageKey = buildStorageKey(contextKey);+ const payload = JSON.stringify(snapshot);++ try {+ storage.setItem(storageKey, payload);+ } catch (error) {+ // Likely QuotaExceededError or storage disabled — try to free space and retry once.+ try {+ pruneScrollSnapshots(storage);+ storage.setItem(storageKey, payload);+ } catch {+ console.error('[scrollSnapshotStore] failed to persist scroll snapshot', error);+ }+ }+};++const NEW_KEY_SUFFIX = '_new';++/**+ * Detects "draft promoted to a real id" — `messageMapKey()` returns a `*_new`+ * key while a topic/thread is still optimistic, and switches to the+ * id-bearing key once `onTopicCreated` / `onThreadCreated` lands. The new key+ * is the previous one with `_new` replaced by `_<id>`, so the logical+ * conversation is unchanged. Callers should preserve scroll position across+ * this transition rather than treating it as a topic switch.+ */+export const isDraftPromotionKey = (prevKey: string, nextKey: string): boolean => {+ if (prevKey === nextKey) return false;+ if (!prevKey.endsWith(NEW_KEY_SUFFIX)) return false;+ // Keep the trailing underscore so we don't match unrelated keys whose base+ // happens to share a prefix (e.g. `main_agt_xxx_new` vs `main_agt_xxxx_*`).+ const baseWithSeparator = prevKey.slice(0, -(NEW_KEY_SUFFIX.length - 1));+ return nextKey.startsWith(baseWithSeparator);+};++/**+ * Move a snapshot from one context key to another, dropping the old entry.+ * Used when a draft conversation key is promoted to its real id (see+ * `isDraftPromotionKey`).+ */+export const migrateScrollSnapshot = (oldContextKey: string, newContextKey: string): void => {+ if (oldContextKey === newContextKey) return;+ const storage = getStorage();+ if (!storage) return;++ const oldStorageKey = buildStorageKey(oldContextKey);+ const newStorageKey = buildStorageKey(newContextKey);++ let raw: string | null;+ try {+ raw = storage.getItem(oldStorageKey);+ } catch (error) {+ console.error('[scrollSnapshotStore] failed to read snapshot during migration', error);+ return;+ }+ if (!raw) return;++ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch {+ // Corrupt entry — drop it rather than carry it forward to the new key.+ try {+ storage.removeItem(oldStorageKey);+ } catch {+ // ignore+ }+ return;+ }++ if (!isValidSnapshot(parsed)) {+ try {+ storage.removeItem(oldStorageKey);+ } catch {+ // ignore+ }+ return;+ }++ try {+ storage.setItem(newStorageKey, raw);+ storage.removeItem(oldStorageKey);+ } catch (error) {+ console.error('[scrollSnapshotStore] failed to write migrated snapshot', error);+ }+};diff --git a/src/locales/default/setting.ts b/src/locales/default/setting.tsindex b08b0dcc225..d5a538e963a 100644--- a/src/locales/default/setting.ts+++ b/src/locales/default/setting.ts@@ -926,9 +926,6 @@ When I am ___, I need ___'systemAgent.promptRewrite.label': 'Model','systemAgent.promptRewrite.modelDesc': 'Specify the model used to rewrite prompts','systemAgent.promptRewrite.title': 'Prompt Rewrite Agent',- 'systemAgent.queryRewrite.label': 'Model',- 'systemAgent.queryRewrite.modelDesc': 'Specify the model used to optimize user inquiries',- 'systemAgent.queryRewrite.title': 'Library query rewrite Agent','systemAgent.thread.label': 'Model','systemAgent.thread.modelDesc': 'The model designated for automatic renaming of subtopics','systemAgent.thread.title': 'Subtopic Auto-Naming Agent',diff --git a/src/routes/(main)/settings/agent/index.tsx b/src/routes/(main)/settings/agent/index.tsxindex 7954a8c252c..6943fc1a9a4 100644--- a/src/routes/(main)/settings/agent/index.tsx+++ b/src/routes/(main)/settings/agent/index.tsx@@ -1,16 +1,13 @@'use client';-import { DEFAULT_REWRITE_QUERY } from '@lobechat/prompts';import { useTranslation } from 'react-i18next';import SettingHeader from '@/routes/(main)/settings/features/SettingHeader';-import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';import SystemAgentForm from './features/SystemAgentForm';const Page = () => {const { t } = useTranslation('setting');- const { enableKnowledgeBase } = useServerConfigStore(featureFlagsSelectors);return (<><SettingHeader title={t('tab.agent')} />@@ -21,14 +18,6 @@ const Page = () => {<SystemAgentForm systemAgentKey="agentMeta" /><SystemAgentForm allowDisable systemAgentKey="inputCompletion" /><SystemAgentForm allowDisable systemAgentKey="promptRewrite" />- {enableKnowledgeBase && (- <SystemAgentForm- allowCustomPrompt- allowDisable- defaultPrompt={DEFAULT_REWRITE_QUERY}- systemAgentKey="queryRewrite"- />- )}</>);};diff --git a/src/routes/(main)/settings/service-model/index.tsx b/src/routes/(main)/settings/service-model/index.tsxindex 4940843bd25..504e98f492c 100644--- a/src/routes/(main)/settings/service-model/index.tsx+++ b/src/routes/(main)/settings/service-model/index.tsx@@ -1,6 +1,5 @@'use client';-import { DEFAULT_REWRITE_QUERY } from '@lobechat/prompts';import { useTranslation } from 'react-i18next';import SettingHeader from '@/routes/(main)/settings/features/SettingHeader';@@ -13,8 +12,7 @@ import STT from '../tts/features/STT';const Page = () => {const { t } = useTranslation('setting');- const { enableKnowledgeBase, enableSTT, showAiImage } =- useServerConfigStore(featureFlagsSelectors);+ const { enableSTT, showAiImage } = useServerConfigStore(featureFlagsSelectors);return (<><SettingHeader title={t('tab.serviceModel')} />@@ -25,14 +23,6 @@ const Page = () => {<SystemAgentForm systemAgentKey="agentMeta" /><SystemAgentForm allowDisable systemAgentKey="inputCompletion" /><SystemAgentForm allowDisable systemAgentKey="promptRewrite" />- {enableKnowledgeBase && (- <SystemAgentForm- allowCustomPrompt- allowDisable- defaultPrompt={DEFAULT_REWRITE_QUERY}- systemAgentKey="queryRewrite"- />- )}{enableSTT && (<><STT />diff --git a/src/server/globalConfig/parseSystemAgent.test.ts b/src/server/globalConfig/parseSystemAgent.test.tsindex 70ff014a59e..4424a82b0b7 100644--- a/src/server/globalConfig/parseSystemAgent.test.ts+++ b/src/server/globalConfig/parseSystemAgent.test.ts@@ -103,11 +103,6 @@ describe('parseSystemAgent', () => {expect(result.agentMeta).toEqual({ provider: 'ollama', model: 'deepseek-v3' });expect(result.historyCompress).toEqual({ provider: 'ollama', model: 'deepseek-v3' });expect(result.thread).toEqual({ provider: 'ollama', model: 'deepseek-v3' });- expect(result.queryRewrite).toEqual({- provider: 'ollama',- model: 'deepseek-v3',- enabled: true,- });});it('should override default setting with specific settings', () => {@@ -121,11 +116,6 @@ describe('parseSystemAgent', () => {expect(result.agentMeta).toEqual({ provider: 'ollama', model: 'deepseek-v3' });expect(result.historyCompress).toEqual({ provider: 'ollama', model: 'deepseek-v3' });expect(result.thread).toEqual({ provider: 'ollama', model: 'deepseek-v3' });- expect(result.queryRewrite).toEqual({- provider: 'ollama',- model: 'deepseek-v3',- enabled: true,- });});it('should properly handle priority when topic appears before default in the string', () => {@@ -142,10 +132,5 @@ describe('parseSystemAgent', () => {expect(result.agentMeta).toEqual({ provider: 'ollama', model: 'deepseek-v3' });expect(result.historyCompress).toEqual({ provider: 'ollama', model: 'deepseek-v3' });expect(result.thread).toEqual({ provider: 'ollama', model: 'deepseek-v3' });- expect(result.queryRewrite).toEqual({- provider: 'ollama',- model: 'deepseek-v3',- enabled: true,- });});});diff --git a/src/server/globalConfig/parseSystemAgent.ts b/src/server/globalConfig/parseSystemAgent.tsindex 33d903f04c3..dee79891926 100644--- a/src/server/globalConfig/parseSystemAgent.ts+++ b/src/server/globalConfig/parseSystemAgent.ts@@ -3,7 +3,7 @@ import { type UserSystemAgentConfig } from '@/types/user/settings';const protectedKeys = Object.keys(DEFAULT_SYSTEM_AGENT_CONFIG);-const defaultTrueLey = new Set(['queryRewrite', 'promptRewrite', 'autoSuggestion']);+const defaultTrueLey = new Set(['promptRewrite', 'autoSuggestion']);export const parseSystemAgent = (envString: string = ''): Partial<UserSystemAgentConfig> => {if (!envString) return {};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 b513410d757..1fd10eda00a 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@@ -73,11 +73,6 @@ exports[`settingsSelectors > currentSystemAgent > should merge DEFAULT_SYSTEM_AG"model": "gpt-5.4-mini","provider": "openai",},- "queryRewrite": {- "enabled": true,- "model": "gpt-5.4-mini",- "provider": "openai",- },"replyMessage": "Custom auto reply","thread": {"model": "claude-sonnet-4-6",diff --git a/src/store/user/slices/settings/selectors/systemAgent.ts b/src/store/user/slices/settings/selectors/systemAgent.tsindex 52948031769..b6f65609228 100644--- a/src/store/user/slices/settings/selectors/systemAgent.ts+++ b/src/store/user/slices/settings/selectors/systemAgent.ts@@ -11,7 +11,6 @@ const translation = (s: UserStore) => currentSystemAgent(s).translation;const topic = (s: UserStore) => currentSystemAgent(s).topic;const thread = (s: UserStore) => currentSystemAgent(s).thread;const agentMeta = (s: UserStore) => currentSystemAgent(s).agentMeta;-const queryRewrite = (s: UserStore) => currentSystemAgent(s).queryRewrite;const promptRewrite = (s: UserStore) => currentSystemAgent(s).promptRewrite;const historyCompress = (s: UserStore) => currentSystemAgent(s).historyCompress;const generationTopic = (s: UserStore) => currentSystemAgent(s).generationTopic;@@ -23,7 +22,6 @@ export const systemAgentSelectors = {historyCompress,inputCompletion,promptRewrite,- queryRewrite,thread,topic,translation,